<?php
declare(strict_types=1);

/**
 * Pure Chemical Admin
 * File: admin/menu_sorting.php
 *
 * Purpose:
 * - Drag & Drop menu sorting
 * - Parent / Submenu / Child hierarchy sorting
 * - Saves sort_order + parent_id
 *
 * Existing tables only:
 * - menus
 * - menu_items
 */

session_start();

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/csrf.php';

if (function_exists('requireAdmin')) {
    requireAdmin();
}

if (!isset($pdo) || !$pdo instanceof PDO) {
    http_response_code(500);
    exit('Database connection is not available.');
}

/* =========================================================
   HELPERS
========================================================= */

function h(?string $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function getInt(string $key, int $default = 0): int
{
    return isset($_GET[$key]) ? (int)$_GET[$key] : $default;
}

function postString(string $key, string $default = ''): string
{
    return isset($_POST[$key])
        ? trim((string)$_POST[$key])
        : $default;
}

function redirectTo(string $url): never
{
    header('Location: ' . $url);
    exit;
}

function csrfInput(): string
{
    if (function_exists('csrf_field')) {
        return csrf_field();
    }

    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }

    return '<input type="hidden" name="csrf_token" value="' .
        h($_SESSION['csrf_token']) .
        '">';
}

function verifyCsrf(): void
{
    if (function_exists('csrf_verify')) {
        csrf_verify();
        return;
    }

    $token = $_POST['csrf_token'] ?? '';

    if (
        empty($_SESSION['csrf_token']) ||
        !hash_equals(
            (string)$_SESSION['csrf_token'],
            (string)$token
        )
    ) {
        http_response_code(419);
        exit('Invalid CSRF token.');
    }
}

/* =========================================================
   ADMIN BASE
========================================================= */

$scriptPath = str_replace(
    '\\',
    '/',
    $_SERVER['SCRIPT_NAME'] ?? ''
);

$adminPosition = strpos(
    $scriptPath,
    '/admin/'
);

if ($adminPosition !== false) {
    $adminBase = substr(
        $scriptPath,
        0,
        $adminPosition + 7
    );
} else {
    $adminBase = '/admin/';
}

$adminBase = rtrim($adminBase, '/') . '/';

/* =========================================================
   AJAX SORT SAVE
========================================================= */

if (
    $_SERVER['REQUEST_METHOD'] === 'POST' &&
    postString('action') === 'save_sorting'
) {

    header('Content-Type: application/json; charset=utf-8');

    try {

        verifyCsrf();

        $menuId = (int)($_POST['menu_id'] ?? 0);
        $treeJson = (string)($_POST['tree'] ?? '');

        if ($menuId <= 0) {
            throw new RuntimeException(
                'Invalid menu selected.'
            );
        }

        if ($treeJson === '') {
            throw new RuntimeException(
                'Sorting data is missing.'
            );
        }

        $tree = json_decode(
            $treeJson,
            true
        );

        if (
            !is_array($tree) ||
            json_last_error() !== JSON_ERROR_NONE
        ) {
            throw new RuntimeException(
                'Invalid sorting data.'
            );
        }

        /*
         * Verify menu exists.
         */
        $menuCheck = $pdo->prepare("
            SELECT id
            FROM menus
            WHERE id = ?
            LIMIT 1
        ");

        $menuCheck->execute([
            $menuId
        ]);

        if (!$menuCheck->fetchColumn()) {
            throw new RuntimeException(
                'Menu not found.'
            );
        }

        /*
         * Collect all IDs from submitted tree.
         */
        $submittedItems = [];

        $collectItems = function (
            array $items,
            ?int $parentId = null
        ) use (
            &$collectItems,
            &$submittedItems
        ): void {

            $sortOrder = 0;

            foreach ($items as $item) {

                if (!is_array($item)) {
                    continue;
                }

                $id = isset($item['id'])
                    ? (int)$item['id']
                    : 0;

                if ($id <= 0) {
                    continue;
                }

                $submittedItems[$id] = [
                    'parent_id' => $parentId,
                    'sort_order' => $sortOrder
                ];

                $sortOrder++;

                if (
                    isset($item['children']) &&
                    is_array($item['children'])
                ) {

                    $collectItems(
                        $item['children'],
                        $id
                    );
                }
            }
        };

        $collectItems($tree);

        if (empty($submittedItems)) {
            throw new RuntimeException(
                'No menu items found.'
            );
        }

        /*
         * Fetch actual menu item IDs.
         */
        $existingStmt = $pdo->prepare("
            SELECT id
            FROM menu_items
            WHERE menu_id = ?
        ");

        $existingStmt->execute([
            $menuId
        ]);

        $existingIds = array_map(
            'intval',
            $existingStmt->fetchAll(PDO::FETCH_COLUMN)
        );

        $existingLookup = array_fill_keys(
            $existingIds,
            true
        );

        /*
         * Make sure client cannot update
         * another menu's records.
         */
        foreach ($submittedItems as $id => $data) {

            if (!isset($existingLookup[$id])) {
                throw new RuntimeException(
                    'Invalid menu item detected.'
                );
            }

            if (
                $data['parent_id'] !== null &&
                !isset(
                    $existingLookup[
                        (int)$data['parent_id']
                    ]
                )
            ) {
                throw new RuntimeException(
                    'Invalid parent menu item detected.'
                );
            }
        }

        /*
         * Prevent circular parent relation.
         */
        foreach ($submittedItems as $id => $data) {

            $parentId = $data['parent_id'];
            $visited = [];

            while ($parentId !== null) {

                $parentId = (int)$parentId;

                if ($parentId === $id) {
                    throw new RuntimeException(
                        'Circular menu hierarchy detected.'
                    );
                }

                if (isset($visited[$parentId])) {
                    throw new RuntimeException(
                        'Invalid circular menu structure.'
                    );
                }

                $visited[$parentId] = true;

                if (!isset($submittedItems[$parentId])) {
                    break;
                }

                $parentId =
                    $submittedItems[$parentId]['parent_id'];
            }
        }

        /*
         * Transaction.
         */
        $pdo->beginTransaction();

        /*
         * Temporary parent IDs prevent problems when
         * changing hierarchy.
         */
        $temporaryStmt = $pdo->prepare("
            UPDATE menu_items
            SET
                parent_id = NULL,
                sort_order = sort_order + 100000
            WHERE id = ?
              AND menu_id = ?
        ");

        foreach ($submittedItems as $id => $data) {

            $temporaryStmt->execute([
                $id,
                $menuId
            ]);
        }

        /*
         * Save final hierarchy + order.
         */
        $updateStmt = $pdo->prepare("
            UPDATE menu_items
            SET
                parent_id = :parent_id,
                sort_order = :sort_order,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = :id
              AND menu_id = :menu_id
        ");

        foreach ($submittedItems as $id => $data) {

            $updateStmt->execute([
                ':parent_id' => $data['parent_id'],
                ':sort_order' => $data['sort_order'],
                ':id' => $id,
                ':menu_id' => $menuId
            ]);
        }

        $pdo->commit();

        echo json_encode([
            'success' => true,
            'message' => 'Menu order saved successfully.'
        ]);

        exit;

    } catch (Throwable $e) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        error_log(
            'Pure Chemical menu_sorting.php: ' .
            $e->getMessage()
        );

        http_response_code(400);

        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);

        exit;
    }
}

/* =========================================================
   SELECT MENU
========================================================= */

$selectedMenuId = getInt(
    'menu_id',
    0
);

/* =========================================================
   MENUS
========================================================= */

$menusStmt = $pdo->query("
    SELECT
        id,
        name,
        slug,
        location,
        description,
        status
    FROM menus
    ORDER BY
        id ASC
");

$menus = $menusStmt->fetchAll();

if (
    $selectedMenuId <= 0 &&
    !empty($menus)
) {

    foreach ($menus as $menu) {

        if ((int)$menu['status'] === 1) {

            $selectedMenuId =
                (int)$menu['id'];

            break;
        }
    }

    if ($selectedMenuId <= 0) {
        $selectedMenuId =
            (int)$menus[0]['id'];
    }
}

/* =========================================================
   SELECTED MENU
========================================================= */

$selectedMenu = null;

foreach ($menus as $menu) {

    if (
        (int)$menu['id'] ===
        $selectedMenuId
    ) {

        $selectedMenu = $menu;

        break;
    }
}

/* =========================================================
   FETCH ITEMS
========================================================= */

$items = [];

if ($selectedMenuId > 0) {

    $stmt = $pdo->prepare("
        SELECT
            id,
            menu_id,
            parent_id,
            title,
            slug,
            item_type,
            reference_id,
            url,
            target,
            icon,
            image_id,
            css_class,
            css_id,
            sort_order,
            mega_menu,
            status
        FROM menu_items
        WHERE menu_id = ?
        ORDER BY
            sort_order ASC,
            id ASC
    ");

    $stmt->execute([
        $selectedMenuId
    ]);

    $items = $stmt->fetchAll();
}

/* =========================================================
   BUILD TREE
========================================================= */

$itemsById = [];

foreach ($items as $item) {

    $item['id'] =
        (int)$item['id'];

    $item['parent_id'] =
        $item['parent_id'] !== null
            ? (int)$item['parent_id']
            : null;

    $itemsById[
        $item['id']
    ] = $item;
}

$tree = [];

foreach ($itemsById as $id => &$item) {

    $parentId =
        $item['parent_id'];

    if (
        $parentId !== null &&
        isset($itemsById[$parentId])
    ) {

        $itemsById[$parentId]['children'][] =
            &$item;

    } else {

        $tree[] = &$item;
    }
}

unset($item);

/*
 * Recursive sort.
 */
$sortTree = function (
    array &$nodes
) use (
    &$sortTree
): void {

    usort(
        $nodes,
        static function (
            array $a,
            array $b
        ): int {

            $sortA =
                (int)($a['sort_order'] ?? 0);

            $sortB =
                (int)($b['sort_order'] ?? 0);

            if ($sortA === $sortB) {
                return
                    (int)$a['id'] <=>
                    (int)$b['id'];
            }

            return $sortA <=> $sortB;
        }
    );

    foreach ($nodes as &$node) {

        if (
            isset($node['children']) &&
            is_array($node['children'])
        ) {

            $sortTree(
                $node['children']
            );
        }
    }

    unset($node);
};

$sortTree($tree);

/* =========================================================
   PAGE
========================================================= */

$page_title = 'Menu Sorting';
$active_menu = 'menu_sorting';

require_once __DIR__ . '/header.php';

?>

<style>
:root {
    --pc-primary: #0f766e;
    --pc-primary-2: #14b8a6;
    --pc-primary-soft: #ecfdf5;
    --pc-bg: #f5f7fb;
    --pc-card: #ffffff;
    --pc-border: #e5e7eb;
    --pc-text: #172033;
    --pc-muted: #64748b;
    --pc-success: #059669;
    --pc-danger: #dc2626;
    --pc-shadow: 0 18px 50px rgba(15, 23, 42, .07);
}

.sorting-page {
    min-height: calc(100vh - 70px);
    background: var(--pc-bg);
    padding: 28px;
}

.sorting-container {
    max-width: 1450px;
    margin: 0 auto;
}

.sorting-hero {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 20px;
    margin-bottom: 24px;
}

.hero-left {
    display: flex;
    align-items: center;
    gap: 14px;
}

.hero-icon {
    width: 54px;
    height: 54px;
    border-radius: 17px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    font-size: 21px;
    background: linear-gradient(
        135deg,
        var(--pc-primary),
        var(--pc-primary-2)
    );
    box-shadow:
        0 14px 30px
        rgba(20, 184, 166, .24);
}

.hero-left h1 {
    margin: 0;
    color: var(--pc-text);
    font-size: 27px;
    font-weight: 850;
    letter-spacing: -.5px;
}

.hero-left p {
    margin: 5px 0 0;
    color: var(--pc-muted);
    font-size: 13px;
}

.menu-selector {
    min-width: 290px;
    padding: 8px;
    background: #fff;
    border: 1px solid var(--pc-border);
    border-radius: 14px;
    box-shadow: var(--pc-shadow);
}

.menu-selector select {
    width: 100%;
    border: 0;
    outline: 0;
    padding: 9px 10px;
    background: transparent;
    color: var(--pc-text);
    font-size: 13px;
    font-weight: 750;
}

.info-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 15px;
    padding: 17px 19px;
    background: #fff;
    border: 1px solid var(--pc-border);
    border-radius: 17px;
    box-shadow: var(--pc-shadow);
    margin-bottom: 20px;
}

.info-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.info-icon {
    width: 39px;
    height: 39px;
    border-radius: 11px;
    background: var(--pc-primary-soft);
    color: var(--pc-primary);
    display: flex;
    align-items: center;
    justify-content: center;
}

.info-title {
    color: var(--pc-text);
    font-size: 14px;
    font-weight: 800;
}

.info-meta {
    margin-top: 3px;
    color: var(--pc-muted);
    font-size: 11px;
}

.save-area {
    display: flex;
    align-items: center;
    gap: 10px;
}

.save-status {
    color: var(--pc-muted);
    font-size: 12px;
    font-weight: 700;
}

.btn {
    border: 0;
    border-radius: 11px;
    padding: 11px 16px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
    text-decoration: none;
    transition: .2s ease;
}

.btn-primary {
    color: #fff;
    background: linear-gradient(
        135deg,
        var(--pc-primary),
        var(--pc-primary-2)
    );
    box-shadow:
        0 9px 22px
        rgba(20, 184, 166, .22);
}

.btn-primary:hover {
    transform: translateY(-1px);
}

.btn-primary:disabled {
    opacity: .65;
    cursor: not-allowed;
    transform: none;
}

.btn-light {
    color: #475569;
    background: #f8fafc;
    border: 1px solid var(--pc-border);
}

.sort-card {
    background: #fff;
    border: 1px solid var(--pc-border);
    border-radius: 20px;
    box-shadow: var(--pc-shadow);
    overflow: hidden;
}

.sort-card-header {
    padding: 19px 21px;
    border-bottom: 1px solid var(--pc-border);
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 15px;
}

.card-title {
    display: flex;
    align-items: center;
    gap: 11px;
}

.card-title-icon {
    width: 38px;
    height: 38px;
    border-radius: 11px;
    background: var(--pc-primary-soft);
    color: var(--pc-primary);
    display: flex;
    align-items: center;
    justify-content: center;
}

.card-title h2 {
    margin: 0;
    color: var(--pc-text);
    font-size: 16px;
    font-weight: 850;
}

.card-title span {
    display: block;
    margin-top: 3px;
    color: var(--pc-muted);
    font-size: 11px;
}

.sort-card-body {
    padding: 22px;
}

.sort-tree {
    display: flex;
    flex-direction: column;
    gap: 9px;
}

.sort-item {
    list-style: none;
}

.sort-node {
    display: flex;
    align-items: center;
    gap: 11px;
    min-height: 58px;
    padding: 9px 12px;
    background: #fff;
    border: 1px solid var(--pc-border);
    border-radius: 14px;
    cursor: default;
    transition: .2s ease;
}

.sort-node:hover {
    border-color: #99f6e4;
    box-shadow:
        0 8px 25px
        rgba(15, 23, 42, .055);
}

.sort-node.dragging {
    opacity: .45;
}

.sort-node.drag-over {
    border-color: var(--pc-primary-2);
    background: #f0fdfa;
}

.drag-handle {
    width: 32px;
    height: 32px;
    border-radius: 9px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #94a3b8;
    background: #f8fafc;
    cursor: grab;
    flex-shrink: 0;
}

.drag-handle:active {
    cursor: grabbing;
}

.node-icon {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--pc-primary);
    background: #f0fdfa;
    flex-shrink: 0;
}

.node-content {
    flex: 1;
    min-width: 0;
}

.node-title {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.node-title strong {
    color: var(--pc-text);
    font-size: 13px;
}

.node-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    margin-top: 4px;
}

.badge {
    display: inline-flex;
    align-items: center;
    padding: 3px 7px;
    border-radius: 999px;
    font-size: 9px;
    font-weight: 850;
    text-transform: uppercase;
    letter-spacing: .35px;
}

.badge-type {
    color: #475569;
    background: #f1f5f9;
}

.badge-active {
    color: #047857;
    background: #ecfdf5;
}

.badge-inactive {
    color: #b91c1c;
    background: #fef2f2;
}

.badge-mega {
    color: #1d4ed8;
    background: #eff6ff;
}

.children-list {
    list-style: none;
    display: flex;
    flex-direction: column;
    gap: 7px;
    margin: 8px 0 0 45px;
    padding: 0 0 0 15px;
    border-left: 2px solid #ccfbf1;
    min-height: 5px;
}

.children-list .sort-node {
    min-height: 50px;
}

.children-list .node-icon {
    width: 32px;
    height: 32px;
}

.empty-tree {
    text-align: center;
    padding: 65px 20px;
    color: var(--pc-muted);
}

.empty-tree-icon {
    width: 65px;
    height: 65px;
    margin: 0 auto 15px;
    border-radius: 18px;
    background: #f8fafc;
    color: #cbd5e1;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 27px;
}

.empty-tree h3 {
    margin: 0 0 5px;
    color: var(--pc-text);
    font-size: 17px;
}

.empty-tree p {
    margin: 0;
    font-size: 12px;
}

.tip-box {
    margin-top: 18px;
    padding: 14px 16px;
    border: 1px solid #dbeafe;
    background: #eff6ff;
    border-radius: 13px;
    color: #1e40af;
    font-size: 12px;
    line-height: 1.6;
}

.tip-box strong {
    display: block;
    margin-bottom: 3px;
}

@media (max-width: 800px) {

    .sorting-page {
        padding: 16px;
    }

    .sorting-hero {
        align-items: stretch;
        flex-direction: column;
    }

    .menu-selector {
        width: 100%;
        min-width: 0;
        box-sizing: border-box;
    }

    .info-bar {
        align-items: stretch;
        flex-direction: column;
    }

    .save-area {
        justify-content: space-between;
    }

    .sort-card-body {
        padding: 14px;
    }

    .children-list {
        margin-left: 18px;
    }
}

@media (max-width: 520px) {

    .hero-left h1 {
        font-size: 23px;
    }

    .sort-node {
        gap: 7px;
    }

    .node-meta {
        display: none;
    }

    .save-area {
        flex-direction: column;
        align-items: stretch;
    }

    .save-area .btn {
        width: 100%;
    }
}
</style>

<div class="sorting-page">

    <div class="sorting-container">

        <!-- HERO -->
        <div class="sorting-hero">

            <div class="hero-left">

                <div class="hero-icon">
                    <i class="fa-solid fa-arrow-down-up-across-line"></i>
                </div>

                <div>
                    <h1>Menu Sorting</h1>

                    <p>
                        Drag and drop menu items to change their order
                        and hierarchy.
                    </p>
                </div>

            </div>

            <div class="menu-selector">

                <form method="get">

                    <select
                        name="menu_id"
                        onchange="this.form.submit()"
                    >

                        <?php foreach ($menus as $menu): ?>

                            <option
                                value="<?= (int)$menu['id'] ?>"
                                <?= (
                                    (int)$menu['id'] ===
                                    $selectedMenuId
                                )
                                    ? 'selected'
                                    : ''
                                ?>
                            >
                                <?= h($menu['name']) ?>
                                —
                                <?= h($menu['location']) ?>
                            </option>

                        <?php endforeach; ?>

                    </select>

                </form>

            </div>

        </div>

        <?php if (!$selectedMenu): ?>

            <div class="sort-card">

                <div class="empty-tree">

                    <div class="empty-tree-icon">
                        <i class="fa-solid fa-bars-staggered"></i>
                    </div>

                    <h3>No menu available</h3>

                    <p>
                        Please create a menu first.
                    </p>

                </div>

            </div>

        <?php else: ?>

            <!-- INFO BAR -->
            <div class="info-bar">

                <div class="info-left">

                    <div class="info-icon">
                        <i class="fa-solid fa-layer-group"></i>
                    </div>

                    <div>

                        <div class="info-title">
                            <?= h($selectedMenu['name']) ?>
                        </div>

                        <div class="info-meta">
                            <?= h($selectedMenu['slug']) ?>
                            ·
                            <?= h($selectedMenu['location']) ?>
                            ·
                            <?= count($items) ?> items
                        </div>

                    </div>

                </div>

                <div class="save-area">

                    <span
                        class="save-status"
                        id="saveStatus"
                    >
                        Changes not saved
                    </span>

                    <button
                        type="button"
                        class="btn btn-primary"
                        id="saveSorting"
                    >
                        <i class="fa-solid fa-floppy-disk"></i>
                        Save Order
                    </button>

                </div>

            </div>

            <!-- TREE CARD -->
            <div class="sort-card">

                <div class="sort-card-header">

                    <div class="card-title">

                        <div class="card-title-icon">
                            <i class="fa-solid fa-sitemap"></i>
                        </div>

                        <div>

                            <h2>
                                Navigation Structure
                            </h2>

                            <span>
                                Drag items vertically or move them
                                inside another item.
                            </span>

                        </div>

                    </div>

                    <a
                        href="submenu.php?menu_id=<?= $selectedMenuId ?>"
                        class="btn btn-light"
                    >
                        <i class="fa-solid fa-pen-to-square"></i>
                        Manage Items
                    </a>

                </div>

                <div class="sort-card-body">

                    <?php if (empty($tree)): ?>

                        <div class="empty-tree">

                            <div class="empty-tree-icon">
                                <i class="fa-solid fa-folder-tree"></i>
                            </div>

                            <h3>
                                No menu items
                            </h3>

                            <p>
                                Add menu items from Submenu Management.
                            </p>

                        </div>

                    <?php else: ?>

                        <ul
                            class="sort-tree"
                            id="sortTree"
                        >

                            <?php
                            /*
                             * Recursive rendering function.
                             */
                            $renderTree = function (
                                array $nodes
                            ) use (
                                &$renderTree
                            ): void {

                                foreach ($nodes as $node):

                                    $nodeId =
                                        (int)$node['id'];

                                    $icon =
                                        trim(
                                            (string)($node['icon'] ?? '')
                                        );

                                    ?>

                                    <li
                                        class="sort-item"
                                        data-id="<?= $nodeId ?>"
                                    >

                                        <div
                                            class="sort-node"
                                            draggable="true"
                                        >

                                            <div
                                                class="drag-handle"
                                                title="Drag to reorder"
                                            >
                                                <i class="fa-solid fa-grip-vertical"></i>
                                            </div>

                                            <div class="node-icon">

                                                <?php if ($icon !== ''): ?>

                                                    <i
                                                        class="<?= h($icon) ?>"
                                                    ></i>

                                                <?php else: ?>

                                                    <i class="fa-solid fa-bars"></i>

                                                <?php endif; ?>

                                            </div>

                                            <div class="node-content">

                                                <div class="node-title">

                                                    <strong>
                                                        <?= h($node['title']) ?>
                                                    </strong>

                                                    <?php if (
                                                        (int)$node['mega_menu'] === 1
                                                    ): ?>

                                                        <span class="badge badge-mega">
                                                            Mega
                                                        </span>

                                                    <?php endif; ?>

                                                </div>

                                                <div class="node-meta">

                                                    <span class="badge badge-type">
                                                        <?= h(
                                                            $node['item_type']
                                                        ) ?>
                                                    </span>

                                                    <?php if (
                                                        (int)$node['status'] === 1
                                                    ): ?>

                                                        <span class="badge badge-active">
                                                            Active
                                                        </span>

                                                    <?php else: ?>

                                                        <span class="badge badge-inactive">
                                                            Inactive
                                                        </span>

                                                    <?php endif; ?>

                                                    <span class="badge badge-type">
                                                        ID:
                                                        <?= $nodeId ?>
                                                    </span>

                                                    <span class="badge badge-type">
                                                        Order:
                                                        <?= (int)$node['sort_order'] ?>
                                                    </span>

                                                </div>

                                            </div>

                                        </div>

                                        <?php
                                        $children =
                                            $node['children']
                                            ?? [];
                                        ?>

                                        <ul
                                            class="children-list"
                                            data-parent="<?= $nodeId ?>"
                                        >

                                            <?php
                                            if (!empty($children)) {
                                                $renderTree(
                                                    $children
                                                );
                                            }
                                            ?>

                                        </ul>

                                    </li>

                                <?php
                                endforeach;
                            };

                            $renderTree($tree);
                            ?>

                        </ul>

                        <div class="tip-box">

                            <strong>
                                <i class="fa-solid fa-lightbulb"></i>
                                Sorting Tip
                            </strong>

                            Drag a menu item above or below another
                            item to change its order. Dragging an item
                            inside another item makes it a submenu.
                            Click <strong>Save Order</strong> when finished.

                        </div>

                    <?php endif; ?>

                </div>

            </div>

        <?php endif; ?>

    </div>

</div>

<script>
(function () {

    const tree =
        document.getElementById('sortTree');

    const saveButton =
        document.getElementById('saveSorting');

    const saveStatus =
        document.getElementById('saveStatus');

    if (!tree || !saveButton) {
        return;
    }

    let draggedItem = null;
    let hasChanges = false;

    /* =====================================================
       DRAG START
    ===================================================== */

    tree.addEventListener(
        'dragstart',
        function (event) {

            const node =
                event.target.closest(
                    '.sort-node'
                );

            if (!node) {
                return;
            }

            draggedItem =
                node.closest('.sort-item');

            if (!draggedItem) {
                return;
            }

            draggedItem.classList.add(
                'dragging'
            );

            event.dataTransfer.effectAllowed =
                'move';

            event.dataTransfer.setData(
                'text/plain',
                draggedItem.dataset.id
            );
        }
    );

    /* =====================================================
       DRAG END
    ===================================================== */

    tree.addEventListener(
        'dragend',
        function () {

            document
                .querySelectorAll('.drag-over')
                .forEach(function (element) {

                    element.classList.remove(
                        'drag-over'
                    );

                });

            document
                .querySelectorAll('.dragging')
                .forEach(function (element) {

                    element.classList.remove(
                        'dragging'
                    );

                });

            draggedItem = null;
        }
    );

    /* =====================================================
       DRAG OVER
    ===================================================== */

    tree.addEventListener(
        'dragover',
        function (event) {

            event.preventDefault();

            if (!draggedItem) {
                return;
            }

            const node =
                event.target.closest(
                    '.sort-node'
                );

            if (!node) {
                return;
            }

            const targetItem =
                node.closest('.sort-item');

            if (!targetItem) {
                return;
            }

            /*
             * Cannot drop inside itself.
             */
            if (
                targetItem === draggedItem ||
                draggedItem.contains(targetItem)
            ) {
                return;
            }

            document
                .querySelectorAll('.drag-over')
                .forEach(function (element) {

                    element.classList.remove(
                        'drag-over'
                    );

                });

            node.classList.add(
                'drag-over'
            );
        }
    );

    /* =====================================================
       DROP
    ===================================================== */

    tree.addEventListener(
        'drop',
        function (event) {

            event.preventDefault();

            if (!draggedItem) {
                return;
            }

            const node =
                event.target.closest(
                    '.sort-node'
                );

            if (!node) {
                return;
            }

            const targetItem =
                node.closest('.sort-item');

            if (!targetItem) {
                return;
            }

            if (
                targetItem === draggedItem ||
                draggedItem.contains(targetItem)
            ) {
                return;
            }

            const rect =
                node.getBoundingClientRect();

            const offset =
                event.clientY - rect.top;

            /*
             * Top half:
             * place before target.
             *
             * Bottom half:
             * place after target.
             */
            if (
                offset <
                rect.height / 2
            ) {

                targetItem.parentNode.insertBefore(
                    draggedItem,
                    targetItem
                );

            } else {

                targetItem.parentNode.insertBefore(
                    draggedItem,
                    targetItem.nextSibling
                );
            }

            /*
             * Mark changes.
             */
            markChanged();

            document
                .querySelectorAll('.drag-over')
                .forEach(function (element) {

                    element.classList.remove(
                        'drag-over'
                    );

                });
        }
    );

    /* =====================================================
       DOUBLE CLICK / TOUCH FRIENDLY
    ===================================================== */

    tree.addEventListener(
        'dblclick',
        function (event) {

            const node =
                event.target.closest(
                    '.sort-node'
                );

            if (!node) {
                return;
            }

            const item =
                node.closest('.sort-item');

            if (!item) {
                return;
            }

            const children =
                item.querySelector(
                    ':scope > .children-list'
                );

            if (!children) {
                return;
            }

            if (
                children.children.length === 0
            ) {
                return;
            }

            children.style.display =
                children.style.display === 'none'
                    ? 'flex'
                    : 'flex';

        }
    );

    /* =====================================================
       MARK CHANGED
    ===================================================== */

    function markChanged() {

        hasChanges = true;

        saveStatus.textContent =
            'Unsaved changes';

        saveStatus.style.color =
            '#d97706';
    }

    /* =====================================================
       BUILD TREE JSON
    ===================================================== */

    function buildTree(container) {

        const result = [];

        const children =
            Array.from(
                container.children
            );

        children.forEach(function (element) {

            if (
                !element.classList.contains(
                    'sort-item'
                )
            ) {
                return;
            }

            const id =
                parseInt(
                    element.dataset.id,
                    10
                );

            if (!id) {
                return;
            }

            const childContainer =
                element.querySelector(
                    ':scope > .children-list'
                );

            const childTree =
                childContainer
                    ? buildTree(childContainer)
                    : [];

            result.push({
                id: id,
                children: childTree
            });

        });

        return result;
    }

    /* =====================================================
       SAVE
    ===================================================== */

    saveButton.addEventListener(
        'click',
        async function () {

            if (!hasChanges) {

                saveStatus.textContent =
                    'Everything is already saved';

                saveStatus.style.color =
                    '#059669';

                return;
            }

            saveButton.disabled = true;

            saveStatus.textContent =
                'Saving...';

            saveStatus.style.color =
                '#64748b';

            const treeData =
                buildTree(tree);

            const formData =
                new FormData();

            formData.append(
                'action',
                'save_sorting'
            );

            formData.append(
                'menu_id',
                '<?= (int)$selectedMenuId ?>'
            );

            formData.append(
                'tree',
                JSON.stringify(treeData)
            );

            <?php if (function_exists('csrf_field')): ?>

            <?php
            /*
             * Generate token directly for JS
             * when csrf_field() is available.
             */
            ?>

            formData.append(
                'csrf_token',
                '<?= h($_SESSION['csrf_token'] ?? '') ?>'
            );

            <?php else: ?>

            formData.append(
                'csrf_token',
                '<?= h($_SESSION['csrf_token'] ?? '') ?>'
            );

            <?php endif; ?>

            try {

                const response =
                    await fetch(
                        'menu_sorting.php',
                        {
                            method: 'POST',
                            body: formData,
                            headers: {
                                'X-Requested-With':
                                    'XMLHttpRequest'
                            }
                        }
                    );

                const data =
                    await response.json();

                if (!data.success) {
                    throw new Error(
                        data.message ||
                        'Unable to save sorting.'
                    );
                }

                hasChanges = false;

                saveStatus.textContent =
                    'Saved successfully';

                saveStatus.style.color =
                    '#059669';

            } catch (error) {

                saveStatus.textContent =
                    error.message ||
                    'Save failed';

                saveStatus.style.color =
                    '#dc2626';

            } finally {

                saveButton.disabled = false;
            }
        }
    );

    /* =====================================================
       BEFORE LEAVE
    ===================================================== */

    window.addEventListener(
        'beforeunload',
        function (event) {

            if (!hasChanges) {
                return;
            }

            event.preventDefault();
            event.returnValue = '';
        }
    );

})();
</script>

<?php
require_once __DIR__ . '/footer.php';
?>