<?php
/**
 * ============================================================
 * PURE CHEMICAL ADMIN
 * Menu Management
 * File: admin/menus.php
 * ============================================================
 *
 * Existing Tables Used:
 *
 * menus
 * menu_items
 *
 * NO NEW TABLE
 * NO DUPLICATE DATA
 * ============================================================
 */

declare(strict_types=1);

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';


/*
|--------------------------------------------------------------------------
| Authentication
|--------------------------------------------------------------------------
*/

if (function_exists('requireAdmin')) {
    requireAdmin();
}


/*
|--------------------------------------------------------------------------
| CSRF
|--------------------------------------------------------------------------
*/

if (function_exists('csrf_verify')) {
    // Verification is performed only for POST requests below.
}


/*
|--------------------------------------------------------------------------
| Helpers
|--------------------------------------------------------------------------
*/

function menu_e(?string $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}


function menu_redirect(string $url): never
{
    header('Location: ' . $url);
    exit;
}


function menu_slug(string $value): string
{
    $value = trim($value);

    if ($value === '') {
        return '';
    }

    $value = strtolower($value);

    $value = preg_replace('/[^a-z0-9]+/i', '-', $value);
    $value = trim((string)$value, '-');

    return $value;
}


/*
|--------------------------------------------------------------------------
| 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, '/') . '/';


/*
|--------------------------------------------------------------------------
| Page Variables
|--------------------------------------------------------------------------
*/

$page_title = 'Menu Management';
$active_menu = 'menus';


/*
|--------------------------------------------------------------------------
| Flash Message
|--------------------------------------------------------------------------
*/

$successMessage = $_SESSION['menu_success'] ?? '';
$errorMessage   = $_SESSION['menu_error'] ?? '';

unset(
    $_SESSION['menu_success'],
    $_SESSION['menu_error']
);


/*
|--------------------------------------------------------------------------
| Selected Menu
|--------------------------------------------------------------------------
*/

$selectedMenuId = isset($_GET['menu_id'])
    ? (int)$_GET['menu_id']
    : 0;


/*
|--------------------------------------------------------------------------
| Handle POST Actions
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $action = $_POST['action'] ?? '';


    /*
    |--------------------------------------------------------------------------
    | CSRF
    |--------------------------------------------------------------------------
    */

    if (function_exists('csrf_verify')) {

        $csrfToken =
            $_POST['csrf_token']
            ?? $_POST['_token']
            ?? '';

        try {

            csrf_verify($csrfToken);

        } catch (Throwable $e) {

            $_SESSION['menu_error'] =
                'Security verification failed. Please try again.';

            menu_redirect(
                $adminBase . 'menus.php'
            );
        }
    }


    /*
    |--------------------------------------------------------------------------
    | CREATE MENU
    |--------------------------------------------------------------------------
    */

    if ($action === 'create_menu') {

        $name = trim(
            (string)($_POST['name'] ?? '')
        );

        $slug = trim(
            (string)($_POST['slug'] ?? '')
        );

        $location = trim(
            (string)($_POST['location'] ?? '')
        );

        $description = trim(
            (string)($_POST['description'] ?? '')
        );

        $status = isset($_POST['status'])
            ? (int)$_POST['status']
            : 1;


        if ($name === '') {

            $_SESSION['menu_error'] =
                'Menu name is required.';

            menu_redirect(
                $adminBase . 'menus.php'
            );
        }


        if ($slug === '') {
            $slug = menu_slug($name);
        } else {
            $slug = menu_slug($slug);
        }


        /*
        |--------------------------------------------------------------------------
        | Check Duplicate Slug
        |--------------------------------------------------------------------------
        */

        $stmt = $pdo->prepare(
            "SELECT id
             FROM menus
             WHERE slug = ?
             LIMIT 1"
        );

        $stmt->execute([$slug]);

        if ($stmt->fetch()) {

            $_SESSION['menu_error'] =
                'A menu with this slug already exists.';

            menu_redirect(
                $adminBase . 'menus.php'
            );
        }


        /*
        |--------------------------------------------------------------------------
        | Insert
        |--------------------------------------------------------------------------
        */

        $stmt = $pdo->prepare(
            "INSERT INTO menus
            (
                name,
                slug,
                location,
                description,
                status,
                created_at,
                updated_at
            )
            VALUES
            (
                ?,
                ?,
                ?,
                ?,
                ?,
                NOW(),
                NOW()
            )"
        );

        $stmt->execute([
            $name,
            $slug,
            $location !== '' ? $location : null,
            $description !== '' ? $description : null,
            $status
        ]);


        $_SESSION['menu_success'] =
            'Menu created successfully.';

        menu_redirect(
            $adminBase . 'menus.php'
        );
    }


    /*
    |--------------------------------------------------------------------------
    | UPDATE MENU
    |--------------------------------------------------------------------------
    */

    if ($action === 'update_menu') {

        $menuId = (int)(
            $_POST['menu_id'] ?? 0
        );

        $name = trim(
            (string)($_POST['name'] ?? '')
        );

        $slug = trim(
            (string)($_POST['slug'] ?? '')
        );

        $location = trim(
            (string)($_POST['location'] ?? '')
        );

        $description = trim(
            (string)($_POST['description'] ?? '')
        );

        $status = isset($_POST['status'])
            ? (int)$_POST['status']
            : 1;


        if ($menuId <= 0 || $name === '') {

            $_SESSION['menu_error'] =
                'Invalid menu information.';

            menu_redirect(
                $adminBase . 'menus.php'
            );
        }


        if ($slug === '') {
            $slug = menu_slug($name);
        } else {
            $slug = menu_slug($slug);
        }


        /*
        |--------------------------------------------------------------------------
        | Duplicate Slug Check
        |--------------------------------------------------------------------------
        */

        $stmt = $pdo->prepare(
            "SELECT id
             FROM menus
             WHERE slug = ?
             AND id != ?
             LIMIT 1"
        );

        $stmt->execute([
            $slug,
            $menuId
        ]);

        if ($stmt->fetch()) {

            $_SESSION['menu_error'] =
                'Another menu already uses this slug.';

            menu_redirect(
                $adminBase . 'menus.php?edit=' . $menuId
            );
        }


        /*
        |--------------------------------------------------------------------------
        | Update
        |--------------------------------------------------------------------------
        */

        $stmt = $pdo->prepare(
            "UPDATE menus
             SET
                name = ?,
                slug = ?,
                location = ?,
                description = ?,
                status = ?,
                updated_at = NOW()
             WHERE id = ?"
        );

        $stmt->execute([
            $name,
            $slug,
            $location !== '' ? $location : null,
            $description !== '' ? $description : null,
            $status,
            $menuId
        ]);


        $_SESSION['menu_success'] =
            'Menu updated successfully.';

        menu_redirect(
            $adminBase . 'menus.php'
        );
    }


    /*
    |--------------------------------------------------------------------------
    | DELETE MENU
    |--------------------------------------------------------------------------
    */

    if ($action === 'delete_menu') {

        $menuId = (int)(
            $_POST['menu_id'] ?? 0
        );


        if ($menuId <= 0) {

            $_SESSION['menu_error'] =
                'Invalid menu selected.';

            menu_redirect(
                $adminBase . 'menus.php'
            );
        }


        try {

            $pdo->beginTransaction();


            /*
            | Delete child menu items first.
            */

            $stmt = $pdo->prepare(
                "DELETE FROM menu_items
                 WHERE menu_id = ?"
            );

            $stmt->execute([
                $menuId
            ]);


            /*
            | Delete menu.
            */

            $stmt = $pdo->prepare(
                "DELETE FROM menus
                 WHERE id = ?"
            );

            $stmt->execute([
                $menuId
            ]);


            $pdo->commit();


            $_SESSION['menu_success'] =
                'Menu deleted successfully.';

        } catch (Throwable $e) {

            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            error_log(
                'Menu Delete Error: ' .
                $e->getMessage()
            );

            $_SESSION['menu_error'] =
                'Unable to delete this menu.';
        }


        menu_redirect(
            $adminBase . 'menus.php'
        );
    }


    /*
    |--------------------------------------------------------------------------
    | TOGGLE STATUS
    |--------------------------------------------------------------------------
    */

    if ($action === 'toggle_status') {

        $menuId = (int)(
            $_POST['menu_id'] ?? 0
        );


        if ($menuId > 0) {

            $stmt = $pdo->prepare(
                "UPDATE menus
                 SET
                    status =
                        CASE
                            WHEN status = 1 THEN 0
                            ELSE 1
                        END,
                    updated_at = NOW()
                 WHERE id = ?"
            );

            $stmt->execute([
                $menuId
            ]);


            $_SESSION['menu_success'] =
                'Menu status updated successfully.';
        }


        menu_redirect(
            $adminBase . 'menus.php'
        );
    }


    /*
    |--------------------------------------------------------------------------
    | ADD MENU ITEM
    |--------------------------------------------------------------------------
    */

    if ($action === 'create_item') {

        $menuId = (int)(
            $_POST['menu_id'] ?? 0
        );

        $parentId = (int)(
            $_POST['parent_id'] ?? 0
        );

        $title = trim(
            (string)($_POST['title'] ?? '')
        );

        $url = trim(
            (string)($_POST['url'] ?? '')
        );

        $target = trim(
            (string)($_POST['target'] ?? '_self')
        );

        $icon = trim(
            (string)($_POST['icon'] ?? '')
        );

        $sortOrder = (int)(
            $_POST['sort_order'] ?? 0
        );

        $status = isset($_POST['item_status'])
            ? (int)$_POST['item_status']
            : 1;


        if ($menuId <= 0 || $title === '') {

            $_SESSION['menu_error'] =
                'Menu and item title are required.';

            menu_redirect(
                $adminBase . 'menus.php?menu_id=' .
                $menuId
            );
        }


        /*
        |--------------------------------------------------------------------------
        | Verify Parent Belongs To Same Menu
        |--------------------------------------------------------------------------
        */

        if ($parentId > 0) {

            $stmt = $pdo->prepare(
                "SELECT id
                 FROM menu_items
                 WHERE id = ?
                 AND menu_id = ?
                 LIMIT 1"
            );

            $stmt->execute([
                $parentId,
                $menuId
            ]);

            if (!$stmt->fetch()) {

                $parentId = 0;
            }
        }


        /*
        |--------------------------------------------------------------------------
        | Insert Menu Item
        |--------------------------------------------------------------------------
        */

        $stmt = $pdo->prepare(
            "INSERT INTO menu_items
            (
                menu_id,
                parent_id,
                title,
                url,
                target,
                icon,
                sort_order,
                status
            )
            VALUES
            (
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?,
                ?
            )"
        );

        $stmt->execute([
            $menuId,
            $parentId > 0 ? $parentId : null,
            $title,
            $url !== '' ? $url : null,
            $target !== '' ? $target : '_self',
            $icon !== '' ? $icon : null,
            $sortOrder,
            $status
        ]);


        $_SESSION['menu_success'] =
            'Menu item added successfully.';

        menu_redirect(
            $adminBase . 'menus.php?menu_id=' .
            $menuId
        );
    }


    /*
    |--------------------------------------------------------------------------
    | DELETE MENU ITEM
    |--------------------------------------------------------------------------
    */

    if ($action === 'delete_item') {

        $itemId = (int)(
            $_POST['item_id'] ?? 0
        );

        $menuId = (int)(
            $_POST['menu_id'] ?? 0
        );


        if ($itemId > 0) {

            /*
            | First remove children.
            */

            $stmt = $pdo->prepare(
                "DELETE FROM menu_items
                 WHERE parent_id = ?"
            );

            $stmt->execute([
                $itemId
            ]);


            /*
            | Then remove item.
            */

            $stmt = $pdo->prepare(
                "DELETE FROM menu_items
                 WHERE id = ?"
            );

            $stmt->execute([
                $itemId
            ]);


            $_SESSION['menu_success'] =
                'Menu item deleted successfully.';
        }


        menu_redirect(
            $adminBase . 'menus.php?menu_id=' .
            $menuId
        );
    }
}


/*
|--------------------------------------------------------------------------
| Fetch Menus
|--------------------------------------------------------------------------
*/

$menus = [];

$stmt = $pdo->query(
    "SELECT
        id,
        name,
        slug,
        location,
        description,
        status,
        created_at,
        updated_at
     FROM menus
     ORDER BY id ASC"
);

$menus = $stmt->fetchAll();


/*
|--------------------------------------------------------------------------
| Selected Menu
|--------------------------------------------------------------------------
*/

if ($selectedMenuId <= 0 && !empty($menus)) {

    $selectedMenuId = (int)$menus[0]['id'];
}


/*
|--------------------------------------------------------------------------
| Selected Menu Data
|--------------------------------------------------------------------------
*/

$selectedMenu = null;

foreach ($menus as $menu) {

    if ((int)$menu['id'] === $selectedMenuId) {

        $selectedMenu = $menu;

        break;
    }
}


/*
|--------------------------------------------------------------------------
| Edit Menu
|--------------------------------------------------------------------------
*/

$editMenuId = isset($_GET['edit'])
    ? (int)$_GET['edit']
    : 0;

$editMenu = null;

if ($editMenuId > 0) {

    $stmt = $pdo->prepare(
        "SELECT
            id,
            name,
            slug,
            location,
            description,
            status
         FROM menus
         WHERE id = ?
         LIMIT 1"
    );

    $stmt->execute([
        $editMenuId
    ]);

    $editMenu = $stmt->fetch() ?: null;
}


/*
|--------------------------------------------------------------------------
| Fetch Menu Items
|--------------------------------------------------------------------------
*/

$menuItems = [];

if ($selectedMenuId > 0) {

    $stmt = $pdo->prepare(
        "SELECT
            id,
            menu_id,
            parent_id,
            title,
            url,
            target,
            icon,
            sort_order,
            status
         FROM menu_items
         WHERE menu_id = ?
         ORDER BY
            parent_id ASC,
            sort_order ASC,
            id ASC"
    );

    $stmt->execute([
        $selectedMenuId
    ]);

    $menuItems = $stmt->fetchAll();
}


/*
|--------------------------------------------------------------------------
| Parent Items
|--------------------------------------------------------------------------
*/

$parentItems = [];

foreach ($menuItems as $item) {

    $parentId = $item['parent_id'] ?? null;

    if (
        $parentId === null ||
        (int)$parentId === 0
    ) {

        $parentItems[] = $item;
    }
}


/*
|--------------------------------------------------------------------------
| Child Count
|--------------------------------------------------------------------------
*/

$childCounts = [];

foreach ($menuItems as $item) {

    $parentId = $item['parent_id'] ?? null;

    if (
        $parentId !== null &&
        (int)$parentId > 0
    ) {

        $parentId = (int)$parentId;

        if (!isset($childCounts[$parentId])) {
            $childCounts[$parentId] = 0;
        }

        $childCounts[$parentId]++;
    }
}


/*
|--------------------------------------------------------------------------
| Include Header
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/header.php';

?>

<style>

/* =========================================================
   MENU PAGE
========================================================= */

.pc-menu-page {
    padding: 24px;
}


.pc-menu-header {

    display: flex;

    align-items: flex-start;

    justify-content: space-between;

    gap: 20px;

    margin-bottom: 24px;
}


.pc-menu-heading h1 {

    margin: 0;

    color: #172033;

    font-size: 26px;

    font-weight: 800;

    letter-spacing: -.6px;
}


.pc-menu-heading p {

    margin: 7px 0 0;

    color: #7b8798;

    font-size: 13px;
}


.pc-menu-header-actions {

    display: flex;

    gap: 9px;

    flex-wrap: wrap;
}


/* =========================================================
   BUTTON
========================================================= */

.pc-btn {

    min-height: 40px;

    padding: 0 15px;

    display: inline-flex;

    align-items: center;

    justify-content: center;

    gap: 8px;

    border: 0;

    border-radius: 10px;

    text-decoration: none;

    cursor: pointer;

    font-family: inherit;

    font-size: 12px;

    font-weight: 700;

    transition:
        transform .2s ease,
        box-shadow .2s ease,
        background .2s ease;
}


.pc-btn:hover {
    transform: translateY(-1px);
}


.pc-btn-primary {

    color: #fff;

    background:
        linear-gradient(
            135deg,
            #0f766e,
            #0d9488
        );

    box-shadow:
        0 8px 20px rgba(15, 118, 110, .15);
}


.pc-btn-light {

    color: #475569;

    background: #f1f5f9;
}


.pc-btn-danger {

    color: #dc2626;

    background: #fff1f2;
}


/* =========================================================
   ALERT
========================================================= */

.pc-menu-alert {

    padding: 13px 15px;

    border-radius: 11px;

    margin-bottom: 18px;

    display: flex;

    align-items: center;

    gap: 9px;

    font-size: 12px;

    font-weight: 650;
}


.pc-menu-alert.success {

    color: #047857;

    background: #ecfdf5;

    border: 1px solid #d1fae5;
}


.pc-menu-alert.error {

    color: #b91c1c;

    background: #fef2f2;

    border: 1px solid #fee2e2;
}


/* =========================================================
   LAYOUT
========================================================= */

.pc-menu-layout {

    display: grid;

    grid-template-columns: 300px minmax(0, 1fr);

    gap: 20px;

    align-items: start;
}


/* =========================================================
   CARD
========================================================= */

.pc-card {

    background: #fff;

    border: 1px solid #e7edf3;

    border-radius: 16px;

    box-shadow:
        0 8px 30px rgba(15, 23, 42, .035);

    overflow: hidden;
}


.pc-card-header {

    min-height: 60px;

    padding: 0 17px;

    display: flex;

    align-items: center;

    justify-content: space-between;

    gap: 10px;

    border-bottom: 1px solid #edf1f5;
}


.pc-card-title {

    color: #172033;

    font-size: 13px;

    font-weight: 800;
}


.pc-card-subtitle {

    color: #94a0ae;

    font-size: 10px;

    margin-top: 2px;
}


/* =========================================================
   MENU LIST
========================================================= */

.pc-menu-list {

    padding: 8px;
}


.pc-menu-list-item {

    margin: 3px 0;
}


.pc-menu-list-link {

    display: block;

    padding: 11px;

    border-radius: 11px;

    text-decoration: none;

    transition: background .2s ease;
}


.pc-menu-list-link:hover {

    background: #f7fafb;
}


.pc-menu-list-link.active {

    background: #ecfdf5;

    box-shadow:
        inset 3px 0 0 #0f766e;
}


.pc-menu-list-top {

    display: flex;

    align-items: center;

    gap: 9px;
}


.pc-menu-list-icon {

    width: 32px;
    height: 32px;

    display: flex;

    align-items: center;
    justify-content: center;

    border-radius: 9px;

    color: #0f766e;

    background: #f0fdfa;

    flex-shrink: 0;
}


.pc-menu-list-name {

    min-width: 0;

    flex: 1;
}


.pc-menu-list-name strong {

    display: block;

    color: #334155;

    font-size: 12px;

    font-weight: 750;
}


.pc-menu-list-name span {

    display: block;

    color: #9aa5b3;

    font-size: 9px;

    margin-top: 2px;
}


.pc-status {

    padding: 4px 7px;

    border-radius: 6px;

    font-size: 8px;

    font-weight: 800;
}


.pc-status.active {

    color: #047857;

    background: #ecfdf5;
}


.pc-status.inactive {

    color: #b91c1c;

    background: #fef2f2;
}


/* =========================================================
   EMPTY
========================================================= */

.pc-empty {

    padding: 50px 25px;

    text-align: center;

    color: #94a0ae;
}


.pc-empty i {

    display: block;

    font-size: 34px;

    margin-bottom: 12px;

    color: #cbd5e1;
}


.pc-empty strong {

    display: block;

    color: #64748b;

    font-size: 13px;

    margin-bottom: 5px;
}


.pc-empty span {

    font-size: 11px;
}


/* =========================================================
   MENU DETAILS
========================================================= */

.pc-menu-overview {

    padding: 17px;

    display: grid;

    grid-template-columns:
        minmax(0, 1fr)
        auto;

    gap: 15px;

    align-items: center;

    border-bottom: 1px solid #edf1f5;
}


.pc-menu-overview h2 {

    margin: 0;

    color: #172033;

    font-size: 18px;

    font-weight: 800;
}


.pc-menu-overview p {

    margin: 5px 0 0;

    color: #8a96a6;

    font-size: 11px;
}


.pc-menu-meta {

    display: flex;

    gap: 7px;

    flex-wrap: wrap;
}


.pc-meta-pill {

    padding: 6px 9px;

    color: #64748b;

    background: #f8fafc;

    border: 1px solid #edf1f5;

    border-radius: 7px;

    font-size: 9px;

    font-weight: 700;
}


/* =========================================================
   ITEMS
========================================================= */

.pc-items {

    padding: 8px;
}


.pc-item-row {

    min-height: 58px;

    display: flex;

    align-items: center;

    gap: 10px;

    padding: 8px 10px;

    border-bottom: 1px solid #f0f3f6;
}


.pc-item-row:last-child {
    border-bottom: 0;
}


.pc-item-drag {

    width: 28px;

    color: #c0c9d3;

    text-align: center;

    font-size: 11px;
}


.pc-item-icon {

    width: 34px;
    height: 34px;

    border-radius: 9px;

    background: #f8fafc;

    color: #64748b;

    display: flex;

    align-items: center;
    justify-content: center;

    flex-shrink: 0;
}


.pc-item-info {

    flex: 1;

    min-width: 0;
}


.pc-item-title {

    color: #334155;

    font-size: 12px;

    font-weight: 750;
}


.pc-item-url {

    margin-top: 3px;

    color: #9aa5b3;

    font-size: 9px;

    white-space: nowrap;

    overflow: hidden;

    text-overflow: ellipsis;
}


.pc-item-level {

    padding: 4px 7px;

    border-radius: 6px;

    background: #f1f5f9;

    color: #64748b;

    font-size: 8px;

    font-weight: 800;
}


.pc-item-actions {

    display: flex;

    align-items: center;

    gap: 4px;
}


.pc-icon-btn {

    width: 32px;
    height: 32px;

    display: inline-flex;

    align-items: center;
    justify-content: center;

    border: 0;

    border-radius: 8px;

    cursor: pointer;

    text-decoration: none;

    background: #f8fafc;

    color: #64748b;
}


.pc-icon-btn:hover {

    background: #ecfdf5;

    color: #0f766e;
}


.pc-icon-btn.danger:hover {

    background: #fff1f2;

    color: #dc2626;
}


/* Separate, clearly labelled Header and Footer menu forms */
.pc-separate-menu-form {
    margin-bottom: 18px;
    scroll-margin-top: 24px;
}
.pc-separate-menu-form .pc-card-title {
    display: flex;
    align-items: center;
    gap: 9px;
}
.pc-separate-menu-form .pc-card-title i {
    color: #2563eb;
}

/* =========================================================
   FORMS
========================================================= */

.pc-form-wrap {

    padding: 18px;
}


.pc-form-grid {

    display: grid;

    grid-template-columns:
        repeat(2, minmax(0, 1fr));

    gap: 14px;
}


.pc-form-group {

    display: flex;

    flex-direction: column;

    gap: 6px;
}


.pc-form-group.full {
    grid-column: 1 / -1;
}


.pc-form-label {

    color: #475569;

    font-size: 10px;

    font-weight: 750;
}


.pc-form-input,
.pc-form-select,
.pc-form-textarea {

    width: 100%;

    border: 1px solid #dfe6ed;

    border-radius: 9px;

    background: #fff;

    color: #334155;

    font-family: inherit;

    font-size: 11px;

    outline: none;

    transition:
        border-color .2s ease,
        box-shadow .2s ease;
}


.pc-form-input,
.pc-form-select {

    height: 40px;

    padding: 0 11px;
}


.pc-form-textarea {

    min-height: 90px;

    padding: 10px 11px;

    resize: vertical;
}


.pc-form-input:focus,
.pc-form-select:focus,
.pc-form-textarea:focus {

    border-color: #14b8a6;

    box-shadow:
        0 0 0 3px rgba(20, 184, 166, .09);
}


.pc-form-help {

    color: #9aa5b3;

    font-size: 9px;

    line-height: 1.4;
}


.pc-form-actions {

    display: flex;

    align-items: center;

    justify-content: flex-end;

    gap: 8px;

    margin-top: 17px;

    padding-top: 15px;

    border-top: 1px solid #edf1f5;
}


/* =========================================================
   HOW-TO GUIDANCE
========================================================= */
.pc-howto {
    margin: 0 0 20px;
    padding: 17px 18px;
    border: 1px solid #ccefe8;
    border-radius: 14px;
    background: linear-gradient(135deg, #f0fdfa, #ffffff);
}
.pc-howto-title {
    display: flex;
    align-items: center;
    gap: 9px;
    margin: 0 0 12px;
    color: #115e59;
    font-size: 13px;
    font-weight: 800;
}
.pc-howto-steps {
    display: grid;
    grid-template-columns: repeat(3, minmax(0, 1fr));
    gap: 12px;
}
.pc-howto-step {
    display: flex;
    align-items: flex-start;
    gap: 9px;
    color: #526174;
    font-size: 11px;
    line-height: 1.55;
}
.pc-howto-number {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex: 0 0 24px;
    width: 24px;
    height: 24px;
    border-radius: 8px;
    color: #0f766e;
    background: #ccfbf1;
    font-size: 10px;
    font-weight: 800;
}
.pc-howto-step strong {
    display: block;
    margin-bottom: 2px;
    color: #263548;
    font-size: 11px;
}
.pc-section-help {
    margin: 0 0 15px;
    padding: 10px 12px;
    border-radius: 9px;
    background: #f8fafc;
    color: #64748b;
    font-size: 10px;
    line-height: 1.6;
}
.pc-form-help {
    display: block;
}
@media (max-width: 700px) {
    .pc-howto-steps { grid-template-columns: 1fr; }
}

/* =========================================================
   RESPONSIVE
========================================================= */

@media (max-width: 1100px) {

    .pc-menu-layout {

        grid-template-columns: 250px minmax(0, 1fr);
    }

}


@media (max-width: 900px) {

    .pc-menu-layout {

        grid-template-columns: 1fr;
    }

}


@media (max-width: 650px) {

    .pc-menu-page {

        padding: 15px;
    }


    .pc-menu-header {

        flex-direction: column;
    }


    .pc-menu-header-actions {

        width: 100%;
    }


    .pc-menu-header-actions .pc-btn {

        flex: 1;
    }


    .pc-form-grid {

        grid-template-columns: 1fr;
    }


    .pc-form-group.full {

        grid-column: auto;
    }


    .pc-menu-overview {

        grid-template-columns: 1fr;
    }


    .pc-item-level {

        display: none;
    }

}

</style>


<div class="pc-menu-page">

    <!-- =====================================================
         PAGE HEADER
    ====================================================== -->

    <div class="pc-menu-header">

        <div class="pc-menu-heading">

            <h1>Menu Management</h1>

            <p>
                Manage website menus and their main, sub and child items.
            </p>

        </div>


        <div class="pc-menu-header-actions">

            <button type="button" class="pc-btn pc-btn-primary" onclick="scrollToMenuForm('headerMenuCreateForm')">
                <i class="fa-solid fa-plus"></i> Add Header Menu
            </button>

            <button type="button" class="pc-btn pc-btn-primary" onclick="scrollToMenuForm('footerMenuCreateForm')">
                <i class="fa-solid fa-plus"></i> Add Footer Menu
            </button>

        </div>

    </div>

    <section class="pc-howto" aria-label="How to manage website menus">
        <div class="pc-howto-title">
            <i class="fa-solid fa-circle-info"></i>
            How to add website menus and navigation links
        </div>
        <div class="pc-howto-steps">
            <div class="pc-howto-step">
                <span class="pc-howto-number">1</span>
                <div><strong>Create a Menu</strong>
                    Click “Create Menu”. For example, create “Main Navigation” for the website header or “Footer Menu” for links at the bottom of the website.
                </div>
            </div>
            <div class="pc-howto-step">
                <span class="pc-howto-number">2</span>
                <div><strong>Select the Menu</strong>
                    Choose the menu from the “Website Menus” list on the left. New links will be saved inside the menu selected there.
                </div>
            </div>
            <div class="pc-howto-step">
                <span class="pc-howto-number">3</span>
                <div><strong>Add Menu Items</strong>
                    Enter a link title such as “Products” and its URL such as “/products”. Choose “Main / Top Level” for a main link, or select a parent to create a submenu.
                </div>
            </div>
        </div>
    </section>


    <!-- =====================================================
         FLASH
    ====================================================== -->

    <?php if ($successMessage !== ''): ?>

        <div class="pc-menu-alert success">

            <i class="fa-solid fa-circle-check"></i>

            <span>
                <?= menu_e($successMessage); ?>
            </span>

        </div>

    <?php endif; ?>


    <?php if ($errorMessage !== ''): ?>

        <div class="pc-menu-alert error">

            <i class="fa-solid fa-circle-exclamation"></i>

            <span>
                <?= menu_e($errorMessage); ?>
            </span>

        </div>

    <?php endif; ?>


    <!-- =====================================================
         SEPARATE HEADER AND FOOTER MENU FORMS
    ====================================================== -->

    <?php foreach ([
        ['id' => 'headerMenuCreateForm', 'location' => 'header', 'heading' => 'ADD HEADER MENU', 'subtitle' => 'This form creates a menu intended for the website header.', 'default_name' => 'Main Navigation', 'default_slug' => 'main-navigation'],
        ['id' => 'footerMenuCreateForm', 'location' => 'footer', 'heading' => 'ADD FOOTER MENU', 'subtitle' => 'This form creates a menu intended for the website footer.', 'default_name' => 'Footer Menu', 'default_slug' => 'footer-menu'],
    ] as $menuForm): ?>
        <div class="pc-card pc-separate-menu-form" id="<?= menu_e($menuForm['id']); ?>">
            <div class="pc-card-header">
                <div>
                    <div class="pc-card-title">
                        <i class="fa-solid <?= $menuForm['location'] === 'header' ? 'fa-window-maximize' : 'fa-window-minimize'; ?>"></i>
                        <?= menu_e($menuForm['heading']); ?>
                    </div>
                    <div class="pc-card-subtitle"><?= menu_e($menuForm['subtitle']); ?></div>
                </div>
                <span class="pc-meta-pill"><?= strtoupper(menu_e($menuForm['location'])); ?> LOCATION</span>
            </div>
            <div class="pc-form-wrap">
                <div class="pc-section-help">
                    <strong><?= $menuForm['location'] === 'header' ? 'Header Menu:' : 'Footer Menu:'; ?></strong>
                    <?= $menuForm['location'] === 'header' ? 'Use this form for links shown in the top website navigation.' : 'Use this form for links shown in the bottom/footer area of the website.'; ?>
                    The location is set automatically, so you do not need to guess which area this menu belongs to.
                </div>
                <form method="post" action="">
                    <?php if (function_exists('csrf_field')): ?><?= csrf_field(); ?><?php endif; ?>
                    <input type="hidden" name="action" value="create_menu">
                    <input type="hidden" name="location" value="<?= menu_e($menuForm['location']); ?>">
                    <input type="hidden" name="status" value="1">
                    <div class="pc-form-grid">
                        <div class="pc-form-group">
                            <label class="pc-form-label">Menu Name *</label>
                            <input type="text" name="name" class="pc-form-input" required value="" placeholder="<?= menu_e($menuForm['default_name']); ?>">
                            <span class="pc-form-help">This name identifies the menu inside the admin panel.</span>
                        </div>
                        <div class="pc-form-group">
                            <label class="pc-form-label">Slug</label>
                            <input type="text" name="slug" class="pc-form-input" value="" placeholder="<?= menu_e($menuForm['default_slug']); ?>">
                            <span class="pc-form-help">Unique short identifier. You can keep the suggested value.</span>
                        </div>
                        <div class="pc-form-group full">
                            <label class="pc-form-label">Description</label>
                            <textarea name="description" class="pc-form-textarea" placeholder="Describe where this menu is used..."></textarea>
                        </div>
                    </div>
                    <div class="pc-form-actions">
                        <button type="reset" class="pc-btn pc-btn-light">Reset Form</button>
                        <button type="submit" class="pc-btn pc-btn-primary"><i class="fa-solid fa-check"></i> Save <?= $menuForm['location'] === 'header' ? 'Header' : 'Footer'; ?> Menu</button>
                    </div>
                </form>
            </div>
        </div>
    <?php endforeach; ?>

    <!-- =====================================================
         EDIT MENU FORM (shown only while editing an existing menu)
    ====================================================== -->

    <div
        class="pc-card"
        id="menuFormCard"
        style="<?= $editMenu ? '' : 'display:none;'; ?>"
    >

        <div class="pc-card-header">

            <div>

                <div class="pc-card-title">

                    <?= $editMenu
                        ? 'Edit Menu'
                        : 'Create New Menu'; ?>

                </div>

                <div class="pc-card-subtitle">
                    <?= $editMenu
                        ? 'Update existing menu information.'
                        : 'Create a reusable website menu.'; ?>
                </div>

            </div>

            <button
                type="button"
                class="pc-icon-btn"
                onclick="closeMenuCreateForm()"
            >
                <i class="fa-solid fa-xmark"></i>
            </button>

        </div>


        <div class="pc-form-wrap">

            <div class="pc-section-help">
                <strong>What is a Menu?</strong> A menu is a group of website navigation links. Create one menu for each placement, for example “Main Navigation” for the header and “Footer Menu” for the footer. After saving, select it from the left panel to add its links.
            </div>

            <form
                method="post"
                action=""
            >

                <?php if (function_exists('csrf_field')): ?>

                    <?= csrf_field(); ?>

                <?php endif; ?>


                <input
                    type="hidden"
                    name="action"
                    value="<?= $editMenu
                        ? 'update_menu'
                        : 'create_menu'; ?>"
                >


                <?php if ($editMenu): ?>

                    <input
                        type="hidden"
                        name="menu_id"
                        value="<?= (int)$editMenu['id']; ?>"
                    >

                <?php endif; ?>


                <div class="pc-form-grid">

                    <div class="pc-form-group">

                        <label class="pc-form-label">
                            Menu Name *
                        </label>

                        <input
                            type="text"
                            name="name"
                            class="pc-form-input"
                            required
                            value="<?= menu_e(
                                $editMenu['name'] ?? ''
                            ); ?>"
                            placeholder="Main Navigation"
                        >
                        <span class="pc-form-help">A clear internal name for this group of links, e.g. Main Navigation or Footer Menu.</span>

                    </div>


                    <div class="pc-form-group">

                        <label class="pc-form-label">
                            Slug
                        </label>

                        <input
                            type="text"
                            name="slug"
                            class="pc-form-input"
                            value="<?= menu_e(
                                $editMenu['slug'] ?? ''
                            ); ?>"
                            placeholder="main-navigation"
                        >

                        <span class="pc-form-help">
                            Short URL-friendly identifier. Leave empty to generate it from the Menu Name.
                        </span>

                    </div>


                    <div class="pc-form-group">

                        <label class="pc-form-label">
                            Location
                        </label>

                        <input
                            type="text"
                            name="location"
                            class="pc-form-input"
                            value="<?= menu_e(
                                $editMenu['location'] ?? ''
                            ); ?>"
                            placeholder="header"
                        >

                        <span class="pc-form-help">
                            Where the website should use this menu, e.g. header or footer. This is a label; the website template must use the same location.
                        </span>

                    </div>


                    <div class="pc-form-group">

                        <label class="pc-form-label">
                            Status
                        </label>

                        <select
                            name="status"
                            class="pc-form-select"
                        >

                            <option
                                value="1"
                                <?= isset($editMenu['status'])
                                    && (int)$editMenu['status'] === 1
                                    ? 'selected'
                                    : ''; ?>
                            >
                                Active
                            </option>

                            <option
                                value="0"
                                <?= isset($editMenu['status'])
                                    && (int)$editMenu['status'] === 0
                                    ? 'selected'
                                    : ''; ?>
                            >
                                Inactive
                            </option>

                        </select>

                    </div>


                    <div class="pc-form-group full">

                        <label class="pc-form-label">
                            Description
                        </label>

                        <textarea
                            name="description"
                            class="pc-form-textarea"
                            placeholder="Optional menu description..."
                        ><?= menu_e(
                            $editMenu['description'] ?? ''
                        ); ?></textarea>
                        <span class="pc-form-help">Optional note for admins about where or why this menu is used.</span>

                    </div>

                </div>


                <div class="pc-form-actions">

                    <button
                        type="button"
                        class="pc-btn pc-btn-light"
                        onclick="closeMenuCreateForm()"
                    >
                        Cancel
                    </button>

                    <button
                        type="submit"
                        class="pc-btn pc-btn-primary"
                    >

                        <i class="fa-solid fa-check"></i>

                        <?= $editMenu
                            ? 'Update Menu'
                            : 'Create Menu'; ?>

                    </button>

                </div>

            </form>

        </div>

    </div>


    <!-- =====================================================
         MAIN LAYOUT
    ====================================================== -->

    <div class="pc-menu-layout">

        <!-- =================================================
             LEFT: MENUS
        ================================================== -->

        <div class="pc-card">

            <div class="pc-card-header">

                <div>

                    <div class="pc-card-title">
                        Website Menus
                    </div>

                    <div class="pc-card-subtitle">
                        <?= count($menus); ?> menu(s)
                    </div>

                </div>

            </div>


            <?php if (empty($menus)): ?>

                <div class="pc-empty">

                    <i class="fa-regular fa-folder-open"></i>

                    <strong>No menus found</strong>

                    <span>
                        Create your first menu to get started.
                    </span>

                </div>

            <?php else: ?>

                <div class="pc-menu-list">

                    <?php foreach ($menus as $menu): ?>

                        <div class="pc-menu-list-item">

                            <a
                                href="<?= menu_e(
                                    $adminBase .
                                    'menus.php?menu_id=' .
                                    (int)$menu['id']
                                ); ?>"
                                class="pc-menu-list-link
                                <?= (int)$menu['id'] === $selectedMenuId
                                    ? 'active'
                                    : ''; ?>"
                            >

                                <div class="pc-menu-list-top">

                                    <div class="pc-menu-list-icon">

                                        <i class="fa-solid fa-bars"></i>

                                    </div>


                                    <div class="pc-menu-list-name">

                                        <strong>
                                            <?= menu_e(
                                                $menu['name']
                                            ); ?>
                                        </strong>

                                        <span>
                                            <?= menu_e(
                                                $menu['location']
                                                ?: $menu['slug']
                                            ); ?>
                                        </span>

                                    </div>


                                    <span
                                        class="pc-status
                                        <?= (int)$menu['status'] === 1
                                            ? 'active'
                                            : 'inactive'; ?>"
                                    >
                                        <?= (int)$menu['status'] === 1
                                            ? 'ACTIVE'
                                            : 'INACTIVE'; ?>
                                    </span>

                                </div>

                            </a>

                        </div>

                    <?php endforeach; ?>

                </div>

            <?php endif; ?>

        </div>


        <!-- =================================================
             RIGHT: SELECTED MENU
        ================================================== -->

        <div class="pc-card">

            <?php if (!$selectedMenu): ?>

                <div class="pc-empty">

                    <i class="fa-solid fa-bars-staggered"></i>

                    <strong>Select a menu</strong>

                    <span>
                        Select a menu from the left panel.
                    </span>

                </div>

            <?php else: ?>


                <!-- -----------------------------------------
                     MENU OVERVIEW
                ------------------------------------------ -->

                <div class="pc-menu-overview">

                    <div>

                        <h2>
                            <?= menu_e(
                                $selectedMenu['name']
                            ); ?>
                        </h2>

                        <p>
                            <?= menu_e(
                                $selectedMenu['description']
                                ?: 'Manage menu items for this menu.'
                            ); ?>
                        </p>

                    </div>


                    <div class="pc-menu-meta">

                        <span class="pc-meta-pill">
                            Slug:
                            <?= menu_e(
                                $selectedMenu['slug']
                            ); ?>
                        </span>

                        <span class="pc-meta-pill">
                            Location:
                            <?= menu_e(
                                $selectedMenu['location']
                                ?: 'Not set'
                            ); ?>
                        </span>

                        <a
                            href="<?= menu_e(
                                $adminBase .
                                'menus.php?edit=' .
                                (int)$selectedMenu['id']
                            ); ?>"
                            class="pc-icon-btn"
                            title="Edit Menu"
                        >
                            <i class="fa-solid fa-pen"></i>
                        </a>


                        <form
                            method="post"
                            style="display:inline;"
                            onsubmit="return confirm('Are you sure you want to change menu status?');"
                        >

                            <?php if (function_exists('csrf_field')): ?>

                                <?= csrf_field(); ?>

                            <?php endif; ?>

                            <input
                                type="hidden"
                                name="action"
                                value="toggle_status"
                            >

                            <input
                                type="hidden"
                                name="menu_id"
                                value="<?= (int)$selectedMenu['id']; ?>"
                            >

                            <button
                                type="submit"
                                class="pc-icon-btn"
                                title="Toggle Status"
                            >
                                <i class="fa-solid fa-toggle-on"></i>
                            </button>

                        </form>


                        <form
                            method="post"
                            style="display:inline;"
                            onsubmit="return confirm('Delete this menu and all its menu items? This action cannot be undone.');"
                        >

                            <?php if (function_exists('csrf_field')): ?>

                                <?= csrf_field(); ?>

                            <?php endif; ?>

                            <input
                                type="hidden"
                                name="action"
                                value="delete_menu"
                            >

                            <input
                                type="hidden"
                                name="menu_id"
                                value="<?= (int)$selectedMenu['id']; ?>"
                            >

                            <button
                                type="submit"
                                class="pc-icon-btn danger"
                                title="Delete Menu"
                            >
                                <i class="fa-solid fa-trash"></i>
                            </button>

                        </form>

                    </div>

                </div>


                <!-- -----------------------------------------
                     ADD ITEM
                ------------------------------------------ -->

                <div
                    class="pc-form-wrap"
                    style="border-bottom:1px solid #edf1f5;"
                >

                    <div class="pc-section-help">
                        <strong>What is a Menu Item?</strong> Each item is one clickable link in the selected menu. Example: “Products” → “/products”. To create a dropdown/submenu, choose its parent item; leave “Main / Top Level” selected for a top-level link. Check that the correct menu name is shown above before adding items.
                    </div>

                    <form method="post">

                        <?php if (function_exists('csrf_field')): ?>

                            <?= csrf_field(); ?>

                        <?php endif; ?>


                        <input
                            type="hidden"
                            name="action"
                            value="create_item"
                        >

                        <input
                            type="hidden"
                            name="menu_id"
                            value="<?= (int)$selectedMenu['id']; ?>"
                        >


                        <div class="pc-form-grid">

                            <div class="pc-form-group">

                                <label class="pc-form-label">
                                    Item Title *
                                </label>

                                <input
                                    type="text"
                                    name="title"
                                    class="pc-form-input"
                                    required
                                    placeholder="Products"
                                >
                                <span class="pc-form-help">The text visitors will see in the navigation, e.g. Products, About Us, Contact.</span>

                            </div>


                            <div class="pc-form-group">

                                <label class="pc-form-label">
                                    Parent Item
                                </label>

                                <select
                                    name="parent_id"
                                    class="pc-form-select"
                                >

                                    <option value="0">
                                        Main / Top Level
                                    </option>

                                    <?php foreach ($parentItems as $parent): ?>

                                        <option
                                            value="<?= (int)$parent['id']; ?>"
                                        >
                                            └─ <?= menu_e(
                                                $parent['title']
                                            ); ?>
                                        </option>

                                    <?php endforeach; ?>

                                </select>
                                <span class="pc-form-help">Choose an existing main item to place this link inside its dropdown. Choose “Main / Top Level” for a main navigation link.</span>

                            </div>


                            <div class="pc-form-group">

                                <label class="pc-form-label">
                                    URL
                                </label>

                                <input
                                    type="text"
                                    name="url"
                                    class="pc-form-input"
                                    placeholder="/products"
                                >
                                <span class="pc-form-help">Page path or URL to open when clicked. Examples: /products, /about-us, or https://example.com.</span>

                            </div>


                            <div class="pc-form-group">

                                <label class="pc-form-label">
                                    Target
                                </label>

                                <select
                                    name="target"
                                    class="pc-form-select"
                                >

                                    <option value="_self">
                                        Same Window
                                    </option>

                                    <option value="_blank">
                                        New Window
                                    </option>

                                </select>
                                <span class="pc-form-help">Same Window keeps visitors on this tab; New Window opens the link in a new tab.</span>

                            </div>


                            <div class="pc-form-group">

                                <label class="pc-form-label">
                                    Icon
                                </label>

                                <input
                                    type="text"
                                    name="icon"
                                    class="pc-form-input"
                                    placeholder="fa-solid fa-flask"
                                >
                                <span class="pc-form-help">Optional Font Awesome class, e.g. fa-solid fa-flask. Leave empty to show the default link icon.</span>

                            </div>


                            <div class="pc-form-group">

                                <label class="pc-form-label">
                                    Sort Order
                                </label>

                                <input
                                    type="number"
                                    name="sort_order"
                                    class="pc-form-input"
                                    value="0"
                                    min="0"
                                >
                                <span class="pc-form-help">Controls display order; smaller numbers appear first (0, 1, 2…).</span>

                            </div>


                            <div class="pc-form-group">

                                <label class="pc-form-label">
                                    Status
                                </label>

                                <select
                                    name="item_status"
                                    class="pc-form-select"
                                >

                                    <option value="1">
                                        Active
                                    </option>

                                    <option value="0">
                                        Inactive
                                    </option>

                                </select>
                                <span class="pc-form-help">Active items can be shown on the website; inactive items are kept in the database but marked off.</span>

                            </div>

                        </div>


                        <div class="pc-form-actions">

                            <button
                                type="submit"
                                class="pc-btn pc-btn-primary"
                            >
                                <i class="fa-solid fa-plus"></i>
                                Add Menu Item
                            </button>

                        </div>

                    </form>

                </div>


                <!-- -----------------------------------------
                     ITEMS LIST
                ------------------------------------------ -->

                <div class="pc-card-header">

                    <div>

                        <div class="pc-card-title">
                            Menu Items
                        </div>

                        <div class="pc-card-subtitle">
                            Main, sub and child navigation items
                        </div>

                    </div>

                    <span class="pc-meta-pill">
                        <?= count($menuItems); ?> Items
                    </span>

                </div>


                <?php if (empty($menuItems)): ?>

                    <div class="pc-empty">

                        <i class="fa-solid fa-list"></i>

                        <strong>No menu items yet</strong>

                        <span>
                            Add your first navigation item above.
                        </span>

                    </div>

                <?php else: ?>

                    <div class="pc-items">

                        <?php foreach ($menuItems as $item): ?>

                            <?php
                            $isChild =
                                isset($item['parent_id'])
                                && $item['parent_id'] !== null
                                && (int)$item['parent_id'] > 0;

                            $childCount =
                                $childCounts[(int)$item['id']]
                                ?? 0;
                            ?>


                            <div
                                class="pc-item-row"
                                style="<?= $isChild
                                    ? 'padding-left:42px; background:#fcfdfd;'
                                    : ''; ?>"
                            >

                                <div class="pc-item-drag">

                                    <i class="fa-solid fa-grip-vertical"></i>

                                </div>


                                <div class="pc-item-icon">

                                    <?php if (!empty($item['icon'])): ?>

                                        <i
                                            class="<?= menu_e(
                                                $item['icon']
                                            ); ?>"
                                        ></i>

                                    <?php else: ?>

                                        <i class="fa-solid fa-link"></i>

                                    <?php endif; ?>

                                </div>


                                <div class="pc-item-info">

                                    <div class="pc-item-title">

                                        <?= menu_e(
                                            $item['title']
                                        ); ?>

                                        <?php if ($childCount > 0): ?>

                                            <span
                                                style="
                                                    color:#0f766e;
                                                    font-size:9px;
                                                    margin-left:5px;
                                                "
                                            >
                                                <?= $childCount; ?>
                                                child
                                                <?= $childCount > 1
                                                    ? 'items'
                                                    : 'item'; ?>
                                            </span>

                                        <?php endif; ?>

                                    </div>


                                    <div class="pc-item-url">

                                        <?= menu_e(
                                            $item['url']
                                            ?: '#'
                                        ); ?>

                                    </div>

                                </div>


                                <span class="pc-item-level">

                                    <?= $isChild
                                        ? 'SUB / CHILD'
                                        : 'MAIN'; ?>

                                </span>


                                <span
                                    class="pc-status
                                    <?= (int)$item['status'] === 1
                                        ? 'active'
                                        : 'inactive'; ?>"
                                >
                                    <?= (int)$item['status'] === 1
                                        ? 'ON'
                                        : 'OFF'; ?>
                                </span>


                                <div class="pc-item-actions">

                                    <button
                                        type="button"
                                        class="pc-icon-btn"
                                        title="Edit"
                                        onclick="alert('Item editing module will be added in the next step.');"
                                    >
                                        <i class="fa-solid fa-pen"></i>
                                    </button>


                                    <form
                                        method="post"
                                        style="display:inline;"
                                        onsubmit="return confirm('Delete this menu item?');"
                                    >

                                        <?php if (function_exists('csrf_field')): ?>

                                            <?= csrf_field(); ?>

                                        <?php endif; ?>

                                        <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="<?= (int)$selectedMenu['id']; ?>"
                                        >

                                        <button
                                            type="submit"
                                            class="pc-icon-btn danger"
                                            title="Delete"
                                        >
                                            <i class="fa-solid fa-trash"></i>
                                        </button>

                                    </form>

                                </div>

                            </div>

                        <?php endforeach; ?>

                    </div>

                <?php endif; ?>

            <?php endif; ?>

        </div>

    </div>

</div>


<script>

function scrollToMenuForm(formId) {
    const card = document.getElementById(formId);
    if (!card) return;
    card.scrollIntoView({ behavior: 'smooth', block: 'start' });
    const firstInput = card.querySelector('input[name="name"]');
    if (firstInput) firstInput.focus({ preventScroll: true });
}

function openMenuCreateForm() {

    const card =
        document.getElementById(
            'menuFormCard'
        );

    if (!card) {
        return;
    }

    card.style.display = 'block';

    card.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
    });

}


function closeMenuCreateForm() {

    const card =
        document.getElementById(
            'menuFormCard'
        );

    if (!card) {
        return;
    }

    card.style.display = 'none';

}


/*
|--------------------------------------------------------------------------
| Auto Slug
|--------------------------------------------------------------------------
*/

document.addEventListener(
    'DOMContentLoaded',
    function () {

        const nameInput =
            document.querySelector(
                'input[name="name"]'
            );

        const slugInput =
            document.querySelector(
                'input[name="slug"]'
            );


        if (
            nameInput &&
            slugInput &&
            !slugInput.value
        ) {

            nameInput.addEventListener(
                'input',
                function () {

                    if (
                        slugInput.dataset.manual === '1'
                    ) {
                        return;
                    }


                    slugInput.value =
                        nameInput.value
                            .toLowerCase()
                            .replace(
                                /[^a-z0-9]+/g,
                                '-'
                            )
                            .replace(
                                /^-+|-+$/g,
                                ''
                            );

                }
            );


            slugInput.addEventListener(
                'input',
                function () {

                    slugInput.dataset.manual = '1';

                }
            );

        }

    }
);

</script>


<?php
/*
|--------------------------------------------------------------------------
| Footer
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/footer.php';
?>