<?php
declare(strict_types=1);

/**
 * Pure Chemical Admin
 * File: admin/submenu.php
 *
 * Uses existing tables:
 *   menus
 *   menu_items
 *   media
 *
 * No new table required.
 */

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();
}

/* -------------------------------------------------------
   Helpers
------------------------------------------------------- */

function h(?string $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function redirectTo(string $url): never
{
    header('Location: ' . $url);
    exit;
}

function postInt(string $key, int $default = 0): int
{
    return isset($_POST[$key]) ? (int)$_POST[$key] : $default;
}

function postString(string $key, string $default = ''): string
{
    return isset($_POST[$key])
        ? trim((string)$_POST[$key])
        : $default;
}

function getInt(string $key, int $default = 0): int
{
    return isset($_GET[$key]) ? (int)$_GET[$key] : $default;
}

function csrfCheck(): void
{
    if (function_exists('csrf_verify')) {
        csrf_verify();
        return;
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $token = $_POST['csrf_token'] ?? '';

        if (
            empty($_SESSION['csrf_token']) ||
            !hash_equals($_SESSION['csrf_token'], (string)$token)
        ) {
            http_response_code(419);
            exit('Invalid CSRF token.');
        }
    }
}

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']) .
        '">';
}

/* -------------------------------------------------------
   Detect Admin Base URL
------------------------------------------------------- */

$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, '/') . '/';

if (!isset($pdo) || !$pdo instanceof PDO) {
    $_SESSION['submenu_error'] = 'Database connection unavailable.';
    redirectTo($adminBase . 'index.php');
}

/* -------------------------------------------------------
   Flash Messages
------------------------------------------------------- */

$successMessage = $_SESSION['submenu_success'] ?? '';
$errorMessage   = $_SESSION['submenu_error'] ?? '';

unset(
    $_SESSION['submenu_success'],
    $_SESSION['submenu_error']
);

/* -------------------------------------------------------
   Selected Menu
------------------------------------------------------- */

$selectedMenuId = getInt('menu_id', 0);

/* -------------------------------------------------------
   Fetch Menus
------------------------------------------------------- */

$menusStmt = $pdo->query("
    SELECT
        id,
        name,
        slug,
        location,
        description,
        status
    FROM menus
    ORDER BY sort_order ASC, id ASC
");

$menus = $menusStmt->fetchAll();

/*
 * If no menu selected, use first active menu.
 */
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 Details
------------------------------------------------------- */

$selectedMenu = null;

foreach ($menus as $menu) {
    if ((int)$menu['id'] === $selectedMenuId) {
        $selectedMenu = $menu;
        break;
    }
}

/* -------------------------------------------------------
   Handle POST
------------------------------------------------------- */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    csrfCheck();

    $action = postString('action');

    try {

        /* =================================================
           ADD MENU ITEM
        ================================================= */

        if ($action === 'add_item') {

            $menuId       = postInt('menu_id');
            $parentId     = postInt('parent_id', 0);
            $title        = postString('title');
            $slug         = postString('slug');
            $itemType     = postString('item_type', 'page');
            $referenceId  = postInt('reference_id', 0);
            $url          = postString('url');
            $target       = postString('target', '_self');
            $icon         = postString('icon');
            $imageId      = postInt('image_id', 0);
            $cssClass     = postString('css_class');
            $cssId        = postString('css_id');
            $sortOrder    = postInt('sort_order', 0);
            $megaMenu     = postInt('mega_menu', 0) ? 1 : 0;
            $status       = postInt('status', 1) ? 1 : 0;

            if ($menuId <= 0) {
                throw new RuntimeException('Please select a menu.');
            }

            if ($title === '') {
                throw new RuntimeException('Menu item title is required.');
            }

            $allowedTypes = [
                'page',
                'url',
                'category',
                'product',
                'industry',
                'service',
                'brand'
            ];

            if (!in_array($itemType, $allowedTypes, true)) {
                throw new RuntimeException('Invalid menu item type.');
            }

            if (!in_array($target, ['_self', '_blank'], true)) {
                $target = '_self';
            }

            /*
             * Parent validation
             */
            if ($parentId > 0) {

                $parentStmt = $pdo->prepare("
                    SELECT id
                    FROM menu_items
                    WHERE id = ?
                      AND menu_id = ?
                    LIMIT 1
                ");

                $parentStmt->execute([
                    $parentId,
                    $menuId
                ]);

                if (!$parentStmt->fetchColumn()) {
                    throw new RuntimeException(
                        'Selected parent menu item is invalid.'
                    );
                }
            }

            /*
             * Type specific validation
             */
            if ($itemType === 'url' && $url === '') {
                throw new RuntimeException(
                    'URL is required for URL type.'
                );
            }

            if (
                $itemType !== 'url' &&
                $referenceId <= 0 &&
                $url === ''
            ) {
                throw new RuntimeException(
                    'Please provide a reference ID or URL.'
                );
            }

            /*
             * Duplicate title under same parent
             */
            $duplicateStmt = $pdo->prepare("
                SELECT id
                FROM menu_items
                WHERE menu_id = ?
                  AND (
                        parent_id = ?
                        OR (parent_id IS NULL AND ? = 0)
                      )
                  AND title = ?
                LIMIT 1
            ");

            $duplicateStmt->execute([
                $menuId,
                $parentId > 0 ? $parentId : null,
                $parentId,
                $title
            ]);

            if ($duplicateStmt->fetchColumn()) {
                throw new RuntimeException(
                    'A menu item with this title already exists under the selected parent.'
                );
            }

            /*
             * Normalize parent
             */
            $databaseParentId = $parentId > 0 ? $parentId : null;
            $databaseReferenceId = $referenceId > 0
                ? $referenceId
                : null;

            $databaseImageId = $imageId > 0
                ? $imageId
                : null;

            $insertStmt = $pdo->prepare("
                INSERT INTO menu_items (
                    menu_id,
                    parent_id,
                    title,
                    slug,
                    item_type,
                    reference_id,
                    url,
                    target,
                    icon,
                    image_id,
                    css_class,
                    css_id,
                    sort_order,
                    mega_menu,
                    status
                ) VALUES (
                    :menu_id,
                    :parent_id,
                    :title,
                    :slug,
                    :item_type,
                    :reference_id,
                    :url,
                    :target,
                    :icon,
                    :image_id,
                    :css_class,
                    :css_id,
                    :sort_order,
                    :mega_menu,
                    :status
                )
            ");

            $insertStmt->execute([
                ':menu_id'      => $menuId,
                ':parent_id'    => $databaseParentId,
                ':title'        => $title,
                ':slug'         => $slug !== '' ? $slug : null,
                ':item_type'    => $itemType,
                ':reference_id' => $databaseReferenceId,
                ':url'          => $url !== '' ? $url : null,
                ':target'       => $target,
                ':icon'         => $icon !== '' ? $icon : null,
                ':image_id'     => $databaseImageId,
                ':css_class'    => $cssClass !== '' ? $cssClass : null,
                ':css_id'       => $cssId !== '' ? $cssId : null,
                ':sort_order'   => $sortOrder,
                ':mega_menu'    => $megaMenu,
                ':status'       => $status
            ]);

            $_SESSION['submenu_success'] =
                'Menu item created successfully.';

            redirectTo(
                'submenu.php?menu_id=' . $menuId
            );
        }

        /* =================================================
           UPDATE MENU ITEM
        ================================================= */

        if ($action === 'update_item') {

            $itemId       = postInt('item_id');
            $menuId       = postInt('menu_id');
            $parentId     = postInt('parent_id', 0);
            $title        = postString('title');
            $slug         = postString('slug');
            $itemType     = postString('item_type', 'page');
            $referenceId  = postInt('reference_id', 0);
            $url          = postString('url');
            $target       = postString('target', '_self');
            $icon         = postString('icon');
            $imageId      = postInt('image_id', 0);
            $cssClass     = postString('css_class');
            $cssId        = postString('css_id');
            $sortOrder    = postInt('sort_order', 0);
            $megaMenu     = postInt('mega_menu', 0) ? 1 : 0;
            $status       = postInt('status', 1) ? 1 : 0;

            if ($itemId <= 0 || $menuId <= 0) {
                throw new RuntimeException(
                    'Invalid menu item.'
                );
            }

            if ($title === '') {
                throw new RuntimeException(
                    'Menu item title is required.'
                );
            }

            $allowedTypes = [
                'page',
                'url',
                'category',
                'product',
                'industry',
                'service',
                'brand'
            ];

            if (!in_array($itemType, $allowedTypes, true)) {
                throw new RuntimeException(
                    'Invalid menu item type.'
                );
            }

            /*
             * Verify item belongs to selected menu.
             */
            $itemCheck = $pdo->prepare("
                SELECT id
                FROM menu_items
                WHERE id = ?
                  AND menu_id = ?
                LIMIT 1
            ");

            $itemCheck->execute([
                $itemId,
                $menuId
            ]);

            if (!$itemCheck->fetchColumn()) {
                throw new RuntimeException(
                    'Menu item not found.'
                );
            }

            /*
             * Prevent item becoming its own parent.
             */
            if ($parentId === $itemId) {
                throw new RuntimeException(
                    'A menu item cannot be its own parent.'
                );
            }

            /*
             * Validate parent.
             */
            if ($parentId > 0) {

                $parentStmt = $pdo->prepare("
                    SELECT id
                    FROM menu_items
                    WHERE id = ?
                      AND menu_id = ?
                    LIMIT 1
                ");

                $parentStmt->execute([
                    $parentId,
                    $menuId
                ]);

                if (!$parentStmt->fetchColumn()) {
                    throw new RuntimeException(
                        'Selected parent is invalid.'
                    );
                }

                /*
                 * Prevent simple circular hierarchy.
                 */
                $checkParent = $parentId;

                while ($checkParent > 0) {

                    if ($checkParent === $itemId) {
                        throw new RuntimeException(
                            'Circular menu hierarchy is not allowed.'
                        );
                    }

                    $parentLookup = $pdo->prepare("
                        SELECT parent_id
                        FROM menu_items
                        WHERE id = ?
                          AND menu_id = ?
                        LIMIT 1
                    ");

                    $parentLookup->execute([
                        $checkParent,
                        $menuId
                    ]);

                    $nextParent = $parentLookup->fetchColumn();

                    if (!$nextParent) {
                        break;
                    }

                    $checkParent = (int)$nextParent;
                }
            }

            if ($itemType === 'url' && $url === '') {
                throw new RuntimeException(
                    'URL is required for URL type.'
                );
            }

            if (
                $itemType !== 'url' &&
                $referenceId <= 0 &&
                $url === ''
            ) {
                throw new RuntimeException(
                    'Please provide a reference ID or URL.'
                );
            }

            if (!in_array($target, ['_self', '_blank'], true)) {
                $target = '_self';
            }

            $databaseParentId = $parentId > 0
                ? $parentId
                : null;

            $databaseReferenceId = $referenceId > 0
                ? $referenceId
                : null;

            $databaseImageId = $imageId > 0
                ? $imageId
                : null;

            $updateStmt = $pdo->prepare("
                UPDATE menu_items
                SET
                    parent_id = :parent_id,
                    title = :title,
                    slug = :slug,
                    item_type = :item_type,
                    reference_id = :reference_id,
                    url = :url,
                    target = :target,
                    icon = :icon,
                    image_id = :image_id,
                    css_class = :css_class,
                    css_id = :css_id,
                    sort_order = :sort_order,
                    mega_menu = :mega_menu,
                    status = :status,
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = :id
                  AND menu_id = :menu_id
            ");

            $updateStmt->execute([
                ':parent_id'    => $databaseParentId,
                ':title'        => $title,
                ':slug'         => $slug !== '' ? $slug : null,
                ':item_type'    => $itemType,
                ':reference_id' => $databaseReferenceId,
                ':url'          => $url !== '' ? $url : null,
                ':target'       => $target,
                ':icon'         => $icon !== '' ? $icon : null,
                ':image_id'     => $databaseImageId,
                ':css_class'    => $cssClass !== '' ? $cssClass : null,
                ':css_id'       => $cssId !== '' ? $cssId : null,
                ':sort_order'   => $sortOrder,
                ':mega_menu'    => $megaMenu,
                ':status'       => $status,
                ':id'           => $itemId,
                ':menu_id'      => $menuId
            ]);

            $_SESSION['submenu_success'] =
                'Menu item updated successfully.';

            redirectTo(
                'submenu.php?menu_id=' . $menuId
            );
        }

        /* =================================================
           DELETE MENU ITEM
        ================================================= */

        if ($action === 'delete_item') {

            $itemId = postInt('item_id');
            $menuId = postInt('menu_id');

            if ($itemId <= 0 || $menuId <= 0) {
                throw new RuntimeException(
                    'Invalid menu item.'
                );
            }

            /*
             * Delete children first.
             */
            $childrenStmt = $pdo->prepare("
                SELECT id
                FROM menu_items
                WHERE parent_id = ?
                  AND menu_id = ?
            ");

            $childrenStmt->execute([
                $itemId,
                $menuId
            ]);

            $childIds = $childrenStmt->fetchAll(
                PDO::FETCH_COLUMN
            );

            if (!empty($childIds)) {

                $childDelete = $pdo->prepare("
                    DELETE FROM menu_items
                    WHERE id = ?
                      AND menu_id = ?
                ");

                foreach ($childIds as $childId) {
                    $childDelete->execute([
                        (int)$childId,
                        $menuId
                    ]);
                }
            }

            $deleteStmt = $pdo->prepare("
                DELETE FROM menu_items
                WHERE id = ?
                  AND menu_id = ?
            ");

            $deleteStmt->execute([
                $itemId,
                $menuId
            ]);

            $_SESSION['submenu_success'] =
                'Menu item deleted successfully.';

            redirectTo(
                'submenu.php?menu_id=' . $menuId
            );
        }

        /* =================================================
           TOGGLE STATUS
        ================================================= */

        if ($action === 'toggle_status') {

            $itemId = postInt('item_id');
            $menuId = postInt('menu_id');

            $stmt = $pdo->prepare("
                UPDATE menu_items
                SET
                    status = IF(status = 1, 0, 1),
                    updated_at = CURRENT_TIMESTAMP
                WHERE id = ?
                  AND menu_id = ?
            ");

            $stmt->execute([
                $itemId,
                $menuId
            ]);

            $_SESSION['submenu_success'] =
                'Menu item status updated.';

            redirectTo(
                'submenu.php?menu_id=' . $menuId
            );
        }

    } catch (Throwable $e) {

        error_log(
            'Pure Chemical submenu.php error: ' .
            $e->getMessage()
        );

        $_SESSION['submenu_error'] =
            $e->getMessage();

        $redirectMenu =
            postInt('menu_id', $selectedMenuId);

        redirectTo(
            'submenu.php?menu_id=' . $redirectMenu
        );
    }
}

/* -------------------------------------------------------
   Fetch Menu Items
------------------------------------------------------- */

$items = [];

if ($selectedMenuId > 0) {

    $itemsStmt = $pdo->prepare("
        SELECT
            mi.id,
            mi.menu_id,
            mi.parent_id,
            mi.title,
            mi.slug,
            mi.item_type,
            mi.reference_id,
            mi.url,
            mi.target,
            mi.icon,
            mi.image_id,
            mi.css_class,
            mi.css_id,
            mi.sort_order,
            mi.mega_menu,
            mi.status,
            mi.created_at,
            mi.updated_at,
            p.title AS parent_title
        FROM menu_items mi
        LEFT JOIN menu_items p
            ON p.id = mi.parent_id
        WHERE mi.menu_id = ?
        ORDER BY
            CASE
                WHEN mi.parent_id IS NULL THEN 0
                ELSE 1
            END,
            mi.parent_id ASC,
            mi.sort_order ASC,
            mi.id ASC
    ");

    $itemsStmt->execute([
        $selectedMenuId
    ]);

    $items = $itemsStmt->fetchAll();
}

/* -------------------------------------------------------
   Build hierarchy
------------------------------------------------------- */

$topLevelItems = [];
$childrenMap = [];

foreach ($items as $item) {

    $parentId = $item['parent_id'] !== null
        ? (int)$item['parent_id']
        : 0;

    if ($parentId === 0) {
        $topLevelItems[] = $item;
    } else {
        $childrenMap[$parentId][] = $item;
    }
}

/* -------------------------------------------------------
   Parent options
------------------------------------------------------- */

$parentOptions = [];

foreach ($items as $item) {

    $parentId = $item['parent_id'] !== null
        ? (int)$item['parent_id']
        : 0;

    if ($parentId === 0) {
        $parentOptions[] = $item;
    }
}

/* -------------------------------------------------------
   Media
------------------------------------------------------- */

$mediaItems = [];

try {

    $mediaStmt = $pdo->query("
        SELECT
            id,
            title,
            file_name,
            file_path
        FROM media
        ORDER BY id DESC
        LIMIT 200
    ");

    $mediaItems = $mediaStmt->fetchAll();

} catch (Throwable $e) {
    $mediaItems = [];
}

/* -------------------------------------------------------
   Edit Item
------------------------------------------------------- */

$editItemId = getInt('edit', 0);
$editItem = null;

if ($editItemId > 0 && $selectedMenuId > 0) {

    $editStmt = $pdo->prepare("
        SELECT *
        FROM menu_items
        WHERE id = ?
          AND menu_id = ?
        LIMIT 1
    ");

    $editStmt->execute([
        $editItemId,
        $selectedMenuId
    ]);

    $editItem = $editStmt->fetch();
}

/* -------------------------------------------------------
   Page
------------------------------------------------------- */

$page_title = 'Submenu Management';
$active_menu = 'submenu';

require_once __DIR__ . '/header.php';

?>

<style>
:root {
    --pc-primary: #0f766e;
    --pc-primary-dark: #115e59;
    --pc-primary-soft: #ecfdf5;
    --pc-accent: #14b8a6;
    --pc-bg: #f5f7fb;
    --pc-card: #ffffff;
    --pc-border: #e5e7eb;
    --pc-text: #172033;
    --pc-muted: #6b7280;
    --pc-danger: #dc2626;
    --pc-warning: #d97706;
    --pc-success: #059669;
    --pc-shadow: 0 15px 45px rgba(15, 23, 42, .07);
}

.submenu-page {
    background: var(--pc-bg);
    min-height: calc(100vh - 70px);
    padding: 28px;
}

.submenu-container {
    max-width: 1500px;
    margin: 0 auto;
}

.submenu-hero {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;
    margin-bottom: 24px;
}

.hero-title {
    display: flex;
    align-items: center;
    gap: 14px;
}

.hero-icon {
    width: 52px;
    height: 52px;
    border-radius: 16px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    background: linear-gradient(
        135deg,
        var(--pc-primary),
        var(--pc-accent)
    );
    box-shadow: 0 12px 25px rgba(20, 184, 166, .25);
    font-size: 20px;
}

.hero-title h1 {
    margin: 0;
    font-size: 27px;
    color: var(--pc-text);
    font-weight: 800;
    letter-spacing: -.4px;
}

.hero-title p {
    margin: 5px 0 0;
    color: var(--pc-muted);
    font-size: 14px;
}

.menu-selector {
    background: var(--pc-card);
    border: 1px solid var(--pc-border);
    box-shadow: var(--pc-shadow);
    padding: 10px;
    border-radius: 15px;
    min-width: 280px;
}

.menu-selector select {
    width: 100%;
    border: 0;
    outline: none;
    background: transparent;
    padding: 8px 10px;
    font-size: 14px;
    font-weight: 700;
    color: var(--pc-text);
}

.alert {
    border-radius: 14px;
    padding: 14px 17px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 11px;
    font-size: 14px;
    font-weight: 600;
}

.alert-success {
    background: #ecfdf5;
    border: 1px solid #a7f3d0;
    color: #047857;
}

.alert-danger {
    background: #fef2f2;
    border: 1px solid #fecaca;
    color: #b91c1c;
}

.layout-grid {
    display: grid;
    grid-template-columns: minmax(0, 1.35fr) minmax(390px, .65fr);
    gap: 22px;
    align-items: start;
}

.card {
    background: var(--pc-card);
    border: 1px solid var(--pc-border);
    border-radius: 20px;
    box-shadow: var(--pc-shadow);
    overflow: hidden;
}

.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: 800;
}

.card-title span {
    display: block;
    color: var(--pc-muted);
    font-size: 12px;
    margin-top: 2px;
}

.card-body {
    padding: 20px;
}

.stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-bottom: 18px;
}

.mini-stat {
    border: 1px solid var(--pc-border);
    border-radius: 15px;
    padding: 14px;
    background: #fbfcfe;
}

.mini-stat .label {
    font-size: 11px;
    color: var(--pc-muted);
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .5px;
}

.mini-stat .value {
    margin-top: 4px;
    font-size: 23px;
    font-weight: 800;
    color: var(--pc-text);
}

.tree {
    display: flex;
    flex-direction: column;
    gap: 9px;
}

.tree-item {
    border: 1px solid var(--pc-border);
    border-radius: 14px;
    background: #fff;
    transition: .2s ease;
}

.tree-item:hover {
    border-color: #cbd5e1;
    box-shadow: 0 8px 25px rgba(15, 23, 42, .05);
}

.tree-main {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 13px 14px;
}

.drag-handle {
    color: #94a3b8;
    cursor: grab;
}

.menu-item-icon {
    width: 38px;
    height: 38px;
    border-radius: 11px;
    background: #f0fdfa;
    color: var(--pc-primary);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.item-content {
    flex: 1;
    min-width: 0;
}

.item-title {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}

.item-title strong {
    font-size: 14px;
    color: var(--pc-text);
}

.item-meta {
    display: flex;
    gap: 7px;
    flex-wrap: wrap;
    margin-top: 4px;
}

.badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 4px 8px;
    border-radius: 999px;
    font-size: 10px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: .35px;
}

.badge-type {
    background: #f1f5f9;
    color: #475569;
}

.badge-active {
    background: #ecfdf5;
    color: #047857;
}

.badge-inactive {
    background: #fef2f2;
    color: #b91c1c;
}

.badge-mega {
    background: #eff6ff;
    color: #1d4ed8;
}

.item-actions {
    display: flex;
    align-items: center;
    gap: 5px;
}

.icon-btn {
    width: 34px;
    height: 34px;
    border: 1px solid var(--pc-border);
    border-radius: 10px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    color: #64748b;
    cursor: pointer;
    text-decoration: none;
    transition: .2s ease;
}

.icon-btn:hover {
    color: var(--pc-primary);
    border-color: #99f6e4;
    background: #f0fdfa;
}

.icon-btn.danger:hover {
    color: var(--pc-danger);
    border-color: #fecaca;
    background: #fef2f2;
}

.children {
    margin: 0 12px 12px 54px;
    padding-left: 14px;
    border-left: 2px solid #ccfbf1;
    display: flex;
    flex-direction: column;
    gap: 7px;
}

.child-item {
    border: 1px solid #edf0f4;
    border-radius: 12px;
    background: #fafafa;
}

.child-item .tree-main {
    padding: 10px 11px;
}

.child-item .menu-item-icon {
    width: 32px;
    height: 32px;
    border-radius: 9px;
    font-size: 12px;
}

.empty-state {
    text-align: center;
    padding: 48px 20px;
    color: var(--pc-muted);
}

.empty-state i {
    font-size: 36px;
    color: #cbd5e1;
    margin-bottom: 12px;
}

.empty-state h3 {
    color: var(--pc-text);
    margin: 0 0 6px;
}

.form-card {
    position: sticky;
    top: 20px;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 14px;
}

.form-group {
    margin-bottom: 14px;
}

.form-group.full {
    grid-column: 1 / -1;
}

.form-label {
    display: block;
    margin-bottom: 7px;
    font-size: 12px;
    font-weight: 800;
    color: #334155;
}

.form-label .required {
    color: #dc2626;
}

.form-control {
    width: 100%;
    border: 1px solid #dbe1e8;
    background: #fff;
    border-radius: 11px;
    padding: 11px 12px;
    color: var(--pc-text);
    font-size: 13px;
    outline: none;
    transition: .2s ease;
    box-sizing: border-box;
}

.form-control:focus {
    border-color: #5eead4;
    box-shadow: 0 0 0 4px rgba(20, 184, 166, .10);
}

textarea.form-control {
    min-height: 90px;
    resize: vertical;
}

.form-help {
    margin-top: 5px;
    font-size: 11px;
    color: #94a3b8;
}

.checkbox-row {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.check-box {
    display: flex;
    align-items: center;
    gap: 7px;
    border: 1px solid var(--pc-border);
    padding: 9px 11px;
    border-radius: 10px;
    background: #fafafa;
    font-size: 12px;
    font-weight: 700;
    color: #475569;
}

.check-box input {
    accent-color: var(--pc-primary);
}

.form-actions {
    display: flex;
    gap: 9px;
    margin-top: 18px;
}

.btn {
    border: 0;
    border-radius: 11px;
    padding: 11px 15px;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 7px;
    transition: .2s ease;
}

.btn-primary {
    color: #fff;
    background: linear-gradient(
        135deg,
        var(--pc-primary),
        var(--pc-accent)
    );
    box-shadow: 0 8px 18px rgba(20, 184, 166, .22);
}

.btn-primary:hover {
    transform: translateY(-1px);
}

.btn-light {
    color: #475569;
    background: #f8fafc;
    border: 1px solid var(--pc-border);
}

.btn-danger {
    color: #b91c1c;
    background: #fef2f2;
    border: 1px solid #fecaca;
}

.selected-menu-info {
    margin-bottom: 17px;
    padding: 13px;
    border-radius: 13px;
    background: linear-gradient(
        135deg,
        #f0fdfa,
        #f8fafc
    );
    border: 1px solid #ccfbf1;
}

.selected-menu-info strong {
    display: block;
    color: var(--pc-text);
    font-size: 14px;
}

.selected-menu-info span {
    display: block;
    color: var(--pc-muted);
    font-size: 11px;
    margin-top: 3px;
}

@media (max-width: 1100px) {
    .layout-grid {
        grid-template-columns: 1fr;
    }

    .form-card {
        position: static;
    }
}

@media (max-width: 700px) {
    .submenu-page {
        padding: 16px;
    }

    .submenu-hero {
        flex-direction: column;
    }

    .menu-selector {
        width: 100%;
        min-width: 0;
    }

    .stats-row {
        grid-template-columns: 1fr;
    }

    .form-grid {
        grid-template-columns: 1fr;
    }

    .form-group.full {
        grid-column: auto;
    }

    .tree-main {
        align-items: flex-start;
    }

    .item-actions {
        flex-wrap: wrap;
    }

    .children {
        margin-left: 25px;
    }
}
</style>

<div class="submenu-page">
    <div class="submenu-container">

        <!-- HERO -->
        <div class="submenu-hero">

            <div class="hero-title">
                <div class="hero-icon">
                    <i class="fa-solid fa-sitemap"></i>
                </div>

                <div>
                    <h1>Submenu Management</h1>
                    <p>
                        Manage parent menus, submenus and child menu items
                        from one place.
                    </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>

        <!-- ALERTS -->
        <?php if ($successMessage): ?>
            <div class="alert alert-success">
                <i class="fa-solid fa-circle-check"></i>
                <?= h($successMessage) ?>
            </div>
        <?php endif; ?>

        <?php if ($errorMessage): ?>
            <div class="alert alert-danger">
                <i class="fa-solid fa-circle-exclamation"></i>
                <?= h($errorMessage) ?>
            </div>
        <?php endif; ?>

        <?php if (!$selectedMenu): ?>

            <div class="card">
                <div class="empty-state">
                    <i class="fa-solid fa-bars"></i>
                    <h3>No menu found</h3>
                    <p>
                        Create a menu first from Menu Management.
                    </p>
                </div>
            </div>

        <?php else: ?>

            <div class="layout-grid">

                <!-- LEFT -->
                <div>

                    <div class="card">

                        <div class="card-header">

                            <div class="card-title">
                                <div class="card-title-icon">
                                    <i class="fa-solid fa-list-tree"></i>
                                </div>

                                <div>
                                    <h2>
                                        <?= h($selectedMenu['name']) ?>
                                    </h2>

                                    <span>
                                        <?= h($selectedMenu['location']) ?>
                                        ·
                                        <?= h($selectedMenu['slug']) ?>
                                    </span>
                                </div>
                            </div>

                            <a
                                href="submenu.php?menu_id=<?= $selectedMenuId ?>"
                                class="btn btn-light"
                            >
                                <i class="fa-solid fa-rotate"></i>
                                Refresh
                            </a>

                        </div>

                        <div class="card-body">

                            <?php
                            $totalItems = count($items);
                            $activeItems = 0;
                            $megaItems = 0;
                            $submenuCount = 0;

                            foreach ($items as $item) {

                                if ((int)$item['status'] === 1) {
                                    $activeItems++;
                                }

                                if ((int)$item['mega_menu'] === 1) {
                                    $megaItems++;
                                }

                                if ($item['parent_id'] !== null) {
                                    $submenuCount++;
                                }
                            }
                            ?>

                            <div class="stats-row">

                                <div class="mini-stat">
                                    <div class="label">
                                        Total Items
                                    </div>
                                    <div class="value">
                                        <?= $totalItems ?>
                                    </div>
                                </div>

                                <div class="mini-stat">
                                    <div class="label">
                                        Active
                                    </div>
                                    <div class="value">
                                        <?= $activeItems ?>
                                    </div>
                                </div>

                                <div class="mini-stat">
                                    <div class="label">
                                        Submenus
                                    </div>
                                    <div class="value">
                                        <?= $submenuCount ?>
                                    </div>
                                </div>

                            </div>

                            <?php if (empty($topLevelItems)): ?>

                                <div class="empty-state">

                                    <i class="fa-solid fa-folder-tree"></i>

                                    <h3>
                                        No menu items yet
                                    </h3>

                                    <p>
                                        Add your first parent menu item
                                        using the form.
                                    </p>

                                </div>

                            <?php else: ?>

                                <div class="tree">

                                    <?php foreach ($topLevelItems as $item): ?>

                                        <div class="tree-item">

                                            <div class="tree-main">

                                                <div class="drag-handle">
                                                    <i class="fa-solid fa-grip-vertical"></i>
                                                </div>

                                                <div class="menu-item-icon">
                                                    <?php if (!empty($item['icon'])): ?>
                                                        <i class="<?= h($item['icon']) ?>"></i>
                                                    <?php else: ?>
                                                        <i class="fa-solid fa-bars"></i>
                                                    <?php endif; ?>
                                                </div>

                                                <div class="item-content">

                                                    <div class="item-title">

                                                        <strong>
                                                            <?= h($item['title']) ?>
                                                        </strong>

                                                        <?php if ((int)$item['mega_menu'] === 1): ?>
                                                            <span class="badge badge-mega">
                                                                Mega
                                                            </span>
                                                        <?php endif; ?>

                                                    </div>

                                                    <div class="item-meta">

                                                        <span class="badge badge-type">
                                                            <?= h($item['item_type']) ?>
                                                        </span>

                                                        <?php if ((int)$item['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">
                                                            Order:
                                                            <?= (int)$item['sort_order'] ?>
                                                        </span>

                                                    </div>

                                                </div>

                                                <div class="item-actions">

                                                    <a
                                                        href="submenu.php?menu_id=<?= $selectedMenuId ?>&edit=<?= (int)$item['id'] ?>"
                                                        class="icon-btn"
                                                        title="Edit"
                                                    >
                                                        <i class="fa-solid fa-pen"></i>
                                                    </a>

                                                    <form
                                                        method="post"
                                                        style="display:inline"
                                                    >
                                                        <?= csrfInput() ?>

                                                        <input
                                                            type="hidden"
                                                            name="action"
                                                            value="toggle_status"
                                                        >

                                                        <input
                                                            type="hidden"
                                                            name="item_id"
                                                            value="<?= (int)$item['id'] ?>"
                                                        >

                                                        <input
                                                            type="hidden"
                                                            name="menu_id"
                                                            value="<?= $selectedMenuId ?>"
                                                        >

                                                        <button
                                                            type="submit"
                                                            class="icon-btn"
                                                            title="Toggle status"
                                                        >
                                                            <?php if ((int)$item['status'] === 1): ?>
                                                                <i class="fa-solid fa-eye-slash"></i>
                                                            <?php else: ?>
                                                                <i class="fa-solid fa-eye"></i>
                                                            <?php endif; ?>
                                                        </button>
                                                    </form>

                                                    <form
                                                        method="post"
                                                        style="display:inline"
                                                        onsubmit="return confirm('Delete this menu item and its direct children?');"
                                                    >
                                                        <?= csrfInput() ?>

                                                        <input
                                                            type="hidden"
                                                            name="action"
                                                            value="delete_item"
                                                        >

                                                        <input
                                                            type="hidden"
                                                            name="item_id"
                                                            value="<?= (int)$item['id'] ?>"
                                                        >

                                                        <input
                                                            type="hidden"
                                                            name="menu_id"
                                                            value="<?= $selectedMenuId ?>"
                                                        >

                                                        <button
                                                            type="submit"
                                                            class="icon-btn danger"
                                                            title="Delete"
                                                        >
                                                            <i class="fa-solid fa-trash"></i>
                                                        </button>

                                                    </form>

                                                </div>

                                            </div>

                                            <?php if (!empty($childrenMap[(int)$item['id']])): ?>

                                                <div class="children">

                                                    <?php foreach ($childrenMap[(int)$item['id']] as $child): ?>

                                                        <div class="child-item">

                                                            <div class="tree-main">

                                                                <div class="menu-item-icon">
                                                                    <?php if (!empty($child['icon'])): ?>
                                                                        <i class="<?= h($child['icon']) ?>"></i>
                                                                    <?php else: ?>
                                                                        <i class="fa-solid fa-angle-right"></i>
                                                                    <?php endif; ?>
                                                                </div>

                                                                <div class="item-content">

                                                                    <div class="item-title">
                                                                        <strong>
                                                                            <?= h($child['title']) ?>
                                                                        </strong>

                                                                        <?php if ((int)$child['mega_menu'] === 1): ?>
                                                                            <span class="badge badge-mega">
                                                                                Mega
                                                                            </span>
                                                                        <?php endif; ?>
                                                                    </div>

                                                                    <div class="item-meta">

                                                                        <span class="badge badge-type">
                                                                            <?= h($child['item_type']) ?>
                                                                        </span>

                                                                        <?php if ((int)$child['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">
                                                                            Order:
                                                                            <?= (int)$child['sort_order'] ?>
                                                                        </span>

                                                                    </div>

                                                                </div>

                                                                <div class="item-actions">

                                                                    <a
                                                                        href="submenu.php?menu_id=<?= $selectedMenuId ?>&edit=<?= (int)$child['id'] ?>"
                                                                        class="icon-btn"
                                                                        title="Edit"
                                                                    >
                                                                        <i class="fa-solid fa-pen"></i>
                                                                    </a>

                                                                    <form
                                                                        method="post"
                                                                        style="display:inline"
                                                                    >
                                                                        <?= csrfInput() ?>

                                                                        <input
                                                                            type="hidden"
                                                                            name="action"
                                                                            value="toggle_status"
                                                                        >

                                                                        <input
                                                                            type="hidden"
                                                                            name="item_id"
                                                                            value="<?= (int)$child['id'] ?>"
                                                                        >

                                                                        <input
                                                                            type="hidden"
                                                                            name="menu_id"
                                                                            value="<?= $selectedMenuId ?>"
                                                                        >

                                                                        <button
                                                                            type="submit"
                                                                            class="icon-btn"
                                                                            title="Toggle status"
                                                                        >
                                                                            <?php if ((int)$child['status'] === 1): ?>
                                                                                <i class="fa-solid fa-eye-slash"></i>
                                                                            <?php else: ?>
                                                                                <i class="fa-solid fa-eye"></i>
                                                                            <?php endif; ?>
                                                                        </button>

                                                                    </form>

                                                                    <form
                                                                        method="post"
                                                                        style="display:inline"
                                                                        onsubmit="return confirm('Delete this submenu?');"
                                                                    >
                                                                        <?= csrfInput() ?>

                                                                        <input
                                                                            type="hidden"
                                                                            name="action"
                                                                            value="delete_item"
                                                                        >

                                                                        <input
                                                                            type="hidden"
                                                                            name="item_id"
                                                                            value="<?= (int)$child['id'] ?>"
                                                                        >

                                                                        <input
                                                                            type="hidden"
                                                                            name="menu_id"
                                                                            value="<?= $selectedMenuId ?>"
                                                                        >

                                                                        <button
                                                                            type="submit"
                                                                            class="icon-btn danger"
                                                                            title="Delete"
                                                                        >
                                                                            <i class="fa-solid fa-trash"></i>
                                                                        </button>

                                                                    </form>

                                                                </div>

                                                            </div>

                                                        </div>

                                                    <?php endforeach; ?>

                                                </div>

                                            <?php endif; ?>

                                        </div>

                                    <?php endforeach; ?>

                                </div>

                            <?php endif; ?>

                        </div>

                    </div>

                </div>

                <!-- RIGHT -->
                <div>

                    <div class="card form-card">

                        <div class="card-header">

                            <div class="card-title">

                                <div class="card-title-icon">
                                    <i class="fa-solid fa-pen-to-square"></i>
                                </div>

                                <div>
                                    <h2>
                                        <?= $editItem
                                            ? 'Edit Menu Item'
                                            : 'Add Menu Item'
                                        ?>
                                    </h2>

                                    <span>
                                        Create parent, submenu or child
                                        navigation item.
                                    </span>
                                </div>

                            </div>

                        </div>

                        <div class="card-body">

                            <div class="selected-menu-info">

                                <strong>
                                    <?= h($selectedMenu['name']) ?>
                                </strong>

                                <span>
                                    Location:
                                    <?= h($selectedMenu['location']) ?>
                                </span>

                            </div>

                            <form
                                method="post"
                                autocomplete="off"
                            >

                                <?= csrfInput() ?>

                                <input
                                    type="hidden"
                                    name="action"
                                    value="<?= $editItem
                                        ? 'update_item'
                                        : 'add_item'
                                    ?>"
                                >

                                <?php if ($editItem): ?>

                                    <input
                                        type="hidden"
                                        name="item_id"
                                        value="<?= (int)$editItem['id'] ?>"
                                    >

                                <?php endif; ?>

                                <input
                                    type="hidden"
                                    name="menu_id"
                                    value="<?= $selectedMenuId ?>"
                                >

                                <div class="form-grid">

                                    <!-- PARENT -->
                                    <div class="form-group full">

                                        <label class="form-label">
                                            Parent Menu
                                        </label>

                                        <select
                                            name="parent_id"
                                            class="form-control"
                                        >

                                            <option value="0">
                                                — Top Level / Main Menu —
                                            </option>

                                            <?php foreach ($parentOptions as $parent): ?>

                                                <?php
                                                $parentValue =
                                                    (int)$parent['id'];

                                                $selectedParent =
                                                    $editItem &&
                                                    (int)$editItem['parent_id'] ===
                                                    $parentValue;
                                                ?>

                                                <?php
                                                if (
                                                    $editItem &&
                                                    (int)$editItem['id'] ===
                                                    $parentValue
                                                ) {
                                                    continue;
                                                }
                                                ?>

                                                <option
                                                    value="<?= $parentValue ?>"
                                                    <?= $selectedParent
                                                        ? 'selected'
                                                        : ''
                                                    ?>
                                                >
                                                    └─
                                                    <?= h($parent['title']) ?>
                                                </option>

                                            <?php endforeach; ?>

                                        </select>

                                        <div class="form-help">
                                            Select a parent to create a submenu.
                                            Leave top-level for a main menu item.
                                        </div>

                                    </div>

                                    <!-- TITLE -->
                                    <div class="form-group full">

                                        <label class="form-label">
                                            Title
                                            <span class="required">*</span>
                                        </label>

                                        <input
                                            type="text"
                                            name="title"
                                            class="form-control"
                                            required
                                            maxlength="255"
                                            placeholder="e.g. Products"
                                            value="<?= h(
                                                $editItem['title'] ?? ''
                                            ) ?>"
                                        >

                                    </div>

                                    <!-- SLUG -->
                                    <div class="form-group">

                                        <label class="form-label">
                                            Slug
                                        </label>

                                        <input
                                            type="text"
                                            name="slug"
                                            class="form-control"
                                            maxlength="255"
                                            placeholder="products"
                                            value="<?= h(
                                                $editItem['slug'] ?? ''
                                            ) ?>"
                                        >

                                    </div>

                                    <!-- TYPE -->
                                    <div class="form-group">

                                        <label class="form-label">
                                            Item Type
                                            <span class="required">*</span>
                                        </label>

                                        <select
                                            name="item_type"
                                            class="form-control"
                                            id="itemType"
                                            required
                                        >

                                            <?php
                                            $currentType =
                                                $editItem['item_type']
                                                ?? 'page';
                                            ?>

                                            <option
                                                value="page"
                                                <?= $currentType === 'page'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Page
                                            </option>

                                            <option
                                                value="url"
                                                <?= $currentType === 'url'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Custom URL
                                            </option>

                                            <option
                                                value="category"
                                                <?= $currentType === 'category'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Category
                                            </option>

                                            <option
                                                value="product"
                                                <?= $currentType === 'product'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Product
                                            </option>

                                            <option
                                                value="industry"
                                                <?= $currentType === 'industry'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Industry
                                            </option>

                                            <option
                                                value="service"
                                                <?= $currentType === 'service'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Service
                                            </option>

                                            <option
                                                value="brand"
                                                <?= $currentType === 'brand'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Brand
                                            </option>

                                        </select>

                                    </div>

                                    <!-- REFERENCE -->
                                    <div
                                        class="form-group"
                                        id="referenceGroup"
                                    >

                                        <label class="form-label">
                                            Reference ID
                                        </label>

                                        <input
                                            type="number"
                                            name="reference_id"
                                            class="form-control"
                                            min="1"
                                            placeholder="Entity ID"
                                            value="<?= h(
                                                isset($editItem['reference_id'])
                                                    ? (string)$editItem['reference_id']
                                                    : ''
                                            ) ?>"
                                        >

                                        <div class="form-help">
                                            ID of Page, Product, Category,
                                            Industry, Service or Brand.
                                        </div>

                                    </div>

                                    <!-- URL -->
                                    <div
                                        class="form-group full"
                                        id="urlGroup"
                                    >

                                        <label class="form-label">
                                            URL
                                        </label>

                                        <input
                                            type="text"
                                            name="url"
                                            class="form-control"
                                            maxlength="1000"
                                            placeholder="/products or https://example.com"
                                            value="<?= h(
                                                $editItem['url'] ?? ''
                                            ) ?>"
                                        >

                                    </div>

                                    <!-- TARGET -->
                                    <div class="form-group">

                                        <label class="form-label">
                                            Target
                                        </label>

                                        <?php
                                        $currentTarget =
                                            $editItem['target']
                                            ?? '_self';
                                        ?>

                                        <select
                                            name="target"
                                            class="form-control"
                                        >

                                            <option
                                                value="_self"
                                                <?= $currentTarget === '_self'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Same Window
                                            </option>

                                            <option
                                                value="_blank"
                                                <?= $currentTarget === '_blank'
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                New Window
                                            </option>

                                        </select>

                                    </div>

                                    <!-- ICON -->
                                    <div class="form-group">

                                        <label class="form-label">
                                            Icon Class
                                        </label>

                                        <input
                                            type="text"
                                            name="icon"
                                            class="form-control"
                                            maxlength="150"
                                            placeholder="fa-solid fa-box"
                                            value="<?= h(
                                                $editItem['icon'] ?? ''
                                            ) ?>"
                                        >

                                    </div>

                                    <!-- IMAGE -->
                                    <div class="form-group full">

                                        <label class="form-label">
                                            Menu Image
                                        </label>

                                        <select
                                            name="image_id"
                                            class="form-control"
                                        >

                                            <option value="0">
                                                — No Image —
                                            </option>

                                            <?php foreach ($mediaItems as $media): ?>

                                                <?php
                                                $mediaId =
                                                    (int)$media['id'];

                                                $selectedImage =
                                                    $editItem &&
                                                    (int)$editItem['image_id'] ===
                                                    $mediaId;
                                                ?>

                                                <option
                                                    value="<?= $mediaId ?>"
                                                    <?= $selectedImage
                                                        ? 'selected'
                                                        : ''
                                                    ?>
                                                >
                                                    <?= h(
                                                        $media['title']
                                                        ?: $media['file_name']
                                                    ) ?>
                                                </option>

                                            <?php endforeach; ?>

                                        </select>

                                        <div class="form-help">
                                            Uses existing media records.
                                            No duplicate media table is created.
                                        </div>

                                    </div>

                                    <!-- CSS CLASS -->
                                    <div class="form-group">

                                        <label class="form-label">
                                            CSS Class
                                        </label>

                                        <input
                                            type="text"
                                            name="css_class"
                                            class="form-control"
                                            maxlength="255"
                                            placeholder="featured-menu"
                                            value="<?= h(
                                                $editItem['css_class'] ?? ''
                                            ) ?>"
                                        >

                                    </div>

                                    <!-- CSS ID -->
                                    <div class="form-group">

                                        <label class="form-label">
                                            CSS ID
                                        </label>

                                        <input
                                            type="text"
                                            name="css_id"
                                            class="form-control"
                                            maxlength="255"
                                            placeholder="products-menu"
                                            value="<?= h(
                                                $editItem['css_id'] ?? ''
                                            ) ?>"
                                        >

                                    </div>

                                    <!-- SORT -->
                                    <div class="form-group">

                                        <label class="form-label">
                                            Sort Order
                                        </label>

                                        <input
                                            type="number"
                                            name="sort_order"
                                            class="form-control"
                                            value="<?= h(
                                                isset($editItem['sort_order'])
                                                    ? (string)$editItem['sort_order']
                                                    : '0'
                                            ) ?>"
                                        >

                                    </div>

                                    <!-- STATUS -->
                                    <div class="form-group">

                                        <label class="form-label">
                                            Status
                                        </label>

                                        <select
                                            name="status"
                                            class="form-control"
                                        >

                                            <?php
                                            $currentStatus =
                                                isset($editItem['status'])
                                                    ? (int)$editItem['status']
                                                    : 1;
                                            ?>

                                            <option
                                                value="1"
                                                <?= $currentStatus === 1
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Active
                                            </option>

                                            <option
                                                value="0"
                                                <?= $currentStatus === 0
                                                    ? 'selected'
                                                    : ''
                                                ?>
                                            >
                                                Inactive
                                            </option>

                                        </select>

                                    </div>

                                    <!-- OPTIONS -->
                                    <div class="form-group full">

                                        <label class="form-label">
                                            Menu Options
                                        </label>

                                        <div class="checkbox-row">

                                            <label class="check-box">

                                                <input
                                                    type="checkbox"
                                                    name="mega_menu"
                                                    value="1"
                                                    <?= (
                                                        $editItem &&
                                                        (int)$editItem['mega_menu'] === 1
                                                    )
                                                        ? 'checked'
                                                        : ''
                                                    ?>
                                                >

                                                Mega Menu

                                            </label>

                                        </div>

                                    </div>

                                </div>

                                <div class="form-actions">

                                    <button
                                        type="submit"
                                        class="btn btn-primary"
                                    >
                                        <i class="fa-solid fa-floppy-disk"></i>

                                        <?= $editItem
                                            ? 'Update Menu Item'
                                            : 'Create Menu Item'
                                        ?>
                                    </button>

                                    <?php if ($editItem): ?>

                                        <a
                                            href="submenu.php?menu_id=<?= $selectedMenuId ?>"
                                            class="btn btn-light"
                                        >
                                            Cancel
                                        </a>

                                    <?php endif; ?>

                                </div>

                            </form>

                        </div>

                    </div>

                </div>

            </div>

        <?php endif; ?>

    </div>
</div>

<script>
(function () {

    const itemType = document.getElementById('itemType');
    const referenceGroup =
        document.getElementById('referenceGroup');
    const urlGroup =
        document.getElementById('urlGroup');

    if (!itemType) {
        return;
    }

    function updateFields() {

        const type = itemType.value;

        if (type === 'url') {

            if (referenceGroup) {
                referenceGroup.style.display = 'none';
            }

            if (urlGroup) {
                urlGroup.style.display = 'block';
            }

        } else {

            if (referenceGroup) {
                referenceGroup.style.display = 'block';
            }

            if (urlGroup) {
                urlGroup.style.display = 'block';
            }
        }
    }

    itemType.addEventListener(
        'change',
        updateFields
    );

    updateFields();

})();
</script>

<?php
require_once __DIR__ . '/footer.php';
?>