<?php
declare(strict_types=1);

/**
 * Pure Chemical Admin
 *
 * File:
 * admin/menu_status.php
 *
 * Purpose:
 * Manage Active / Inactive status of menu items.
 *
 * Existing table used:
 * - menus
 * - menu_items
 *
 * No new table required.
 */

require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/csrf.php';

requireAdmin();


/*
|--------------------------------------------------------------------------
| AJAX / POST Actions
|--------------------------------------------------------------------------
*/

if (
    $_SERVER['REQUEST_METHOD'] === 'POST'
) {

    requireCsrf();

    $action = trim(
        (string) ($_POST['action'] ?? '')
    );


    /*
    |--------------------------------------------------------------------------
    | Single Status Update
    |--------------------------------------------------------------------------
    */

    if ($action === 'update_status') {

        $itemId = (int) (
            $_POST['item_id'] ?? 0
        );

        $status = (int) (
            $_POST['status'] ?? 0
        );

        if ($itemId <= 0) {
            jsonError(
                'Invalid menu item.',
                422
            );
        }

        if (!in_array($status, [0, 1], true)) {
            jsonError(
                'Invalid status value.',
                422
            );
        }


        $check = $pdo->prepare("
            SELECT id
            FROM menu_items
            WHERE id = :id
            LIMIT 1
        ");

        $check->execute([
            ':id' => $itemId,
        ]);

        if (!$check->fetch()) {
            jsonError(
                'Menu item not found.',
                404
            );
        }


        $stmt = $pdo->prepare("
            UPDATE menu_items
            SET
                status = :status,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = :id
            LIMIT 1
        ");

        $stmt->execute([
            ':status' => $status,
            ':id'     => $itemId,
        ]);


        jsonSuccess(
            $status === 1
                ? 'Menu item activated successfully.'
                : 'Menu item deactivated successfully.',
            [
                'item_id' => $itemId,
                'status'  => $status,
            ]
        );
    }


    /*
    |--------------------------------------------------------------------------
    | Bulk Status Update
    |--------------------------------------------------------------------------
    */

    if ($action === 'bulk_status') {

        $status = (int) (
            $_POST['status'] ?? 0
        );

        $itemIds = $_POST['item_ids'] ?? [];

        if (!in_array($status, [0, 1], true)) {
            jsonError(
                'Invalid status value.',
                422
            );
        }

        if (!is_array($itemIds)) {
            jsonError(
                'Invalid menu item selection.',
                422
            );
        }


        $cleanIds = [];

        foreach ($itemIds as $id) {

            $id = (int) $id;

            if ($id > 0) {
                $cleanIds[] = $id;
            }
        }

        $cleanIds = array_values(
            array_unique($cleanIds)
        );


        if (!$cleanIds) {
            jsonError(
                'Please select at least one menu item.',
                422
            );
        }


        $placeholders = [];

        $params = [
            ':status' => $status,
        ];


        foreach ($cleanIds as $index => $id) {

            $key = ':id_' . $index;

            $placeholders[] = $key;

            $params[$key] = $id;
        }


        $sql = "
            UPDATE menu_items
            SET
                status = :status,
                updated_at = CURRENT_TIMESTAMP
            WHERE id IN (
                " . implode(', ', $placeholders) . "
            )
        ";


        $stmt = $pdo->prepare($sql);

        $stmt->execute($params);


        jsonSuccess(
            $status === 1
                ? count($cleanIds) .
                    ' menu item(s) activated successfully.'
                : count($cleanIds) .
                    ' menu item(s) deactivated successfully.',
            [
                'updated' => count($cleanIds),
                'status'  => $status,
            ]
        );
    }


    /*
    |--------------------------------------------------------------------------
    | Invalid Action
    |--------------------------------------------------------------------------
    */

    jsonError(
        'Invalid request.',
        400
    );
}


/*
|--------------------------------------------------------------------------
| Filters
|--------------------------------------------------------------------------
*/

$menuId = (int) (
    $_GET['menu_id'] ?? 0
);

$statusFilter = $_GET['status'] ?? '';

$search = trim(
    (string) (
        $_GET['search'] ?? ''
    )
);


/*
|--------------------------------------------------------------------------
| Menus
|--------------------------------------------------------------------------
*/

$menuStmt = $pdo->query("
    SELECT
        id,
        name,
        slug,
        location,
        status
    FROM menus
    ORDER BY
        CASE
            WHEN location = 'header' THEN 1
            WHEN location = 'footer' THEN 2
            ELSE 3
        END,
        name ASC
");

$menus = $menuStmt->fetchAll(
    PDO::FETCH_ASSOC
);


/*
|--------------------------------------------------------------------------
| Menu Items
|--------------------------------------------------------------------------
*/

$sql = "
    SELECT
        mi.id,
        mi.menu_id,
        mi.parent_id,
        mi.title,
        mi.slug,
        mi.item_type,
        mi.url,
        mi.target,
        mi.icon,
        mi.image_id,
        mi.sort_order,
        mi.status,
        mi.created_at,
        mi.updated_at,

        m.name AS menu_name,
        m.location AS menu_location

    FROM menu_items mi

    INNER JOIN menus m
        ON m.id = mi.menu_id

    WHERE 1 = 1
";

$params = [];


if ($menuId > 0) {

    $sql .= "
        AND mi.menu_id = :menu_id
    ";

    $params[':menu_id'] = $menuId;
}


if (
    $statusFilter !== ''
    && in_array(
        (string) $statusFilter,
        ['0', '1'],
        true
    )
) {

    $sql .= "
        AND mi.status = :status
    ";

    $params[':status'] =
        (int) $statusFilter;
}


if ($search !== '') {

    $sql .= "
        AND (
            mi.title LIKE :search
            OR mi.slug LIKE :search
            OR mi.url LIKE :search
        )
    ";

    $params[':search'] =
        '%' . $search . '%';
}


$sql .= "
    ORDER BY
        mi.menu_id ASC,
        mi.parent_id IS NOT NULL ASC,
        mi.parent_id ASC,
        mi.sort_order ASC,
        mi.id ASC
";


$stmt = $pdo->prepare($sql);

$stmt->execute($params);

$items = $stmt->fetchAll(
    PDO::FETCH_ASSOC
);


/*
|--------------------------------------------------------------------------
| Statistics
|--------------------------------------------------------------------------
*/

$statsStmt = $pdo->query("
    SELECT
        COUNT(*) AS total,
        SUM(status = 1) AS active,
        SUM(status = 0) AS inactive
    FROM menu_items
");

$stats = $statsStmt->fetch(
    PDO::FETCH_ASSOC
) ?: [
    'total' => 0,
    'active' => 0,
    'inactive' => 0,
];

$totalItems = (int) (
    $stats['total'] ?? 0
);

$activeItems = (int) (
    $stats['active'] ?? 0
);

$inactiveItems = (int) (
    $stats['inactive'] ?? 0
);


$page_title = 'Menu Status';
$active_menu = 'menu_status';

require_once __DIR__ . '/header.php';

?>

<style>

:root {
    --ms-primary: #2563eb;
    --ms-primary-dark: #1d4ed8;
    --ms-success: #059669;
    --ms-danger: #dc2626;
    --ms-warning: #d97706;
    --ms-bg: #f6f8fc;
    --ms-card: #ffffff;
    --ms-border: #e5eaf2;
    --ms-text: #172033;
    --ms-muted: #667085;
    --ms-shadow:
        0 18px 45px rgba(15, 23, 42, .07);
}

.menu-status-page {
    min-height: calc(100vh - 80px);
    padding: 27px;
    background: var(--ms-bg);
}

.ms-container {
    max-width: 1500px;
    margin: 0 auto;
}


/*
|--------------------------------------------------------------------------
| Header
|--------------------------------------------------------------------------
*/

.ms-page-header {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    gap: 20px;
    margin-bottom: 23px;
}

.ms-heading {
    display: flex;
    align-items: flex-start;
    gap: 14px;
}

.ms-heading-icon {
    width: 51px;
    height: 51px;
    display: grid;
    place-items: center;
    border-radius: 15px;
    color: #fff;
    background:
        linear-gradient(
            135deg,
            #2563eb,
            #7c3aed
        );
    box-shadow:
        0 12px 26px rgba(37, 99, 235, .20);
    font-size: 21px;
}

.ms-heading h1 {
    margin: 0 0 5px;
    color: var(--ms-text);
    font-size: 27px;
    font-weight: 850;
    letter-spacing: -.7px;
}

.ms-heading p {
    margin: 0;
    color: var(--ms-muted);
    font-size: 14px;
}


/*
|--------------------------------------------------------------------------
| Stats
|--------------------------------------------------------------------------
*/

.ms-stats {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.ms-stat {
    min-width: 125px;
    padding: 12px 15px;
    border: 1px solid var(--ms-border);
    border-radius: 13px;
    background: #fff;
}

.ms-stat strong {
    display: block;
    color: var(--ms-text);
    font-size: 19px;
    font-weight: 850;
}

.ms-stat span {
    display: block;
    margin-top: 2px;
    color: var(--ms-muted);
    font-size: 10px;
    font-weight: 800;
    text-transform: uppercase;
    letter-spacing: .45px;
}

.ms-stat.active strong {
    color: var(--ms-success);
}

.ms-stat.inactive strong {
    color: var(--ms-danger);
}


/*
|--------------------------------------------------------------------------
| Toolbar
|--------------------------------------------------------------------------
*/

.ms-toolbar {
    display: grid;
    grid-template-columns:
        minmax(180px, .65fr)
        minmax(180px, .45fr)
        minmax(220px, 1fr)
        auto;
    gap: 11px;
    padding: 15px;
    margin-bottom: 18px;
    border: 1px solid var(--ms-border);
    border-radius: 17px;
    background: #fff;
    box-shadow: var(--ms-shadow);
}

.ms-input,
.ms-select {
    width: 100%;
    height: 45px;
    padding: 0 13px;
    border: 1px solid #dce2eb;
    border-radius: 10px;
    outline: none;
    background: #fbfcfe;
    color: var(--ms-text);
    font-size: 13px;
    transition: .2s ease;
}

.ms-input:focus,
.ms-select:focus {
    border-color: var(--ms-primary);
    box-shadow:
        0 0 0 4px rgba(37,99,235,.08);
}

.ms-btn {
    height: 45px;
    border: 0;
    border-radius: 10px;
    padding: 0 18px;
    cursor: pointer;
    font-size: 13px;
    font-weight: 800;
    transition: .18s ease;
}

.ms-btn-primary {
    color: #fff;
    background: var(--ms-primary);
}

.ms-btn-primary:hover {
    background: var(--ms-primary-dark);
    transform: translateY(-1px);
}


/*
|--------------------------------------------------------------------------
| Bulk Toolbar
|--------------------------------------------------------------------------
*/

.ms-bulkbar {
    display: none;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 12px 15px;
    margin-bottom: 14px;
    border: 1px solid #bfdbfe;
    border-radius: 14px;
    background: #eff6ff;
}

.ms-bulkbar.show {
    display: flex;
}

.ms-selected-count {
    color: #1e40af;
    font-size: 13px;
    font-weight: 800;
}

.ms-bulk-actions {
    display: flex;
    gap: 8px;
}

.ms-bulk-btn {
    height: 35px;
    padding: 0 12px;
    border: 1px solid;
    border-radius: 8px;
    cursor: pointer;
    font-size: 11px;
    font-weight: 800;
}

.ms-bulk-active {
    color: #047857;
    border-color: #a7f3d0;
    background: #ecfdf5;
}

.ms-bulk-inactive {
    color: #b42318;
    border-color: #fecaca;
    background: #fef2f2;
}


/*
|--------------------------------------------------------------------------
| Card
|--------------------------------------------------------------------------
*/

.ms-card {
    overflow: hidden;
    border: 1px solid var(--ms-border);
    border-radius: 18px;
    background: #fff;
    box-shadow: var(--ms-shadow);
}

.ms-card-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 15px;
    padding: 18px 21px;
    border-bottom: 1px solid var(--ms-border);
}

.ms-card-head h2 {
    margin: 0;
    color: var(--ms-text);
    font-size: 16px;
    font-weight: 850;
}

.ms-card-head span {
    color: var(--ms-muted);
    font-size: 12px;
}


/*
|--------------------------------------------------------------------------
| Table
|--------------------------------------------------------------------------
*/

.ms-table-wrap {
    width: 100%;
    overflow-x: auto;
}

.ms-table {
    width: 100%;
    min-width: 980px;
    border-collapse: collapse;
}

.ms-table th {
    padding: 13px 17px;
    text-align: left;
    color: #667085;
    background: #fafbfc;
    border-bottom: 1px solid var(--ms-border);
    font-size: 10px;
    font-weight: 850;
    text-transform: uppercase;
    letter-spacing: .5px;
}

.ms-table td {
    padding: 14px 17px;
    color: var(--ms-text);
    border-bottom: 1px solid #edf0f5;
    vertical-align: middle;
    font-size: 13px;
}

.ms-table tbody tr {
    transition: .16s ease;
}

.ms-table tbody tr:hover {
    background: #fafcff;
}

.ms-table tbody tr.row-inactive {
    background: #fffafa;
}


/*
|--------------------------------------------------------------------------
| Checkbox
|--------------------------------------------------------------------------
*/

.ms-check {
    width: 17px;
    height: 17px;
    cursor: pointer;
    accent-color: var(--ms-primary);
}


/*
|--------------------------------------------------------------------------
| Menu Item
|--------------------------------------------------------------------------
*/

.ms-item {
    display: flex;
    align-items: center;
    gap: 11px;
}

.ms-item-icon {
    width: 38px;
    height: 38px;
    flex: 0 0 38px;
    display: grid;
    place-items: center;
    border-radius: 10px;
    color: #2563eb;
    background: #eff6ff;
}

.ms-item-name {
    color: var(--ms-text);
    font-weight: 800;
}

.ms-item-meta {
    margin-top: 3px;
    color: var(--ms-muted);
    font-size: 10px;
}


/*
|--------------------------------------------------------------------------
| Status Pill
|--------------------------------------------------------------------------
*/

.ms-status {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 10px;
    border-radius: 999px;
    font-size: 11px;
    font-weight: 800;
}

.ms-status.active {
    color: #047857;
    background: #ecfdf5;
}

.ms-status.inactive {
    color: #b42318;
    background: #fef2f2;
}

.ms-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: currentColor;
}


/*
|--------------------------------------------------------------------------
| Toggle
|--------------------------------------------------------------------------
*/

.ms-toggle {
    position: relative;
    width: 48px;
    height: 27px;
    border: 0;
    padding: 0;
    border-radius: 99px;
    cursor: pointer;
    background: #d0d5dd;
    transition: .22s ease;
}

.ms-toggle::after {
    content: "";
    position: absolute;
    top: 4px;
    left: 4px;
    width: 19px;
    height: 19px;
    border-radius: 50%;
    background: #fff;
    box-shadow:
        0 2px 5px rgba(0,0,0,.18);
    transition: .22s ease;
}

.ms-toggle.active {
    background: var(--ms-success);
}

.ms-toggle.active::after {
    transform: translateX(21px);
}

.ms-toggle:disabled {
    cursor: wait;
    opacity: .55;
}


/*
|--------------------------------------------------------------------------
| Empty
|--------------------------------------------------------------------------
*/

.ms-empty {
    padding: 65px 25px;
    text-align: center;
}

.ms-empty-icon {
    width: 58px;
    height: 58px;
    margin: 0 auto 13px;
    display: grid;
    place-items: center;
    border-radius: 17px;
    background: #f1f5f9;
    color: #64748b;
    font-size: 23px;
}

.ms-empty h3 {
    margin: 0 0 6px;
    font-size: 16px;
}

.ms-empty p {
    margin: 0;
    color: var(--ms-muted);
    font-size: 13px;
}


/*
|--------------------------------------------------------------------------
| Toast
|--------------------------------------------------------------------------
*/

.ms-toast {
    position: fixed;
    right: 22px;
    bottom: 22px;
    z-index: 10000;
    min-width: 260px;
    max-width: 400px;
    padding: 14px 16px;
    border: 1px solid #dce2eb;
    border-radius: 12px;
    background: #fff;
    color: var(--ms-text);
    box-shadow:
        0 18px 45px rgba(15,23,42,.16);
    transform: translateY(25px);
    opacity: 0;
    pointer-events: none;
    transition: .25s ease;
    font-size: 13px;
    font-weight: 750;
}

.ms-toast.show {
    transform: translateY(0);
    opacity: 1;
}

.ms-toast.success {
    border-left: 4px solid var(--ms-success);
}

.ms-toast.error {
    border-left: 4px solid var(--ms-danger);
}


/*
|--------------------------------------------------------------------------
| Responsive
|--------------------------------------------------------------------------
*/

@media (max-width: 1050px) {

    .ms-toolbar {
        grid-template-columns: 1fr 1fr;
    }

    .ms-toolbar .ms-btn {
        width: 100%;
    }
}

@media (max-width: 850px) {

    .menu-status-page {
        padding: 20px 15px;
    }

    .ms-page-header {
        align-items: flex-start;
        flex-direction: column;
    }

    .ms-stats {
        width: 100%;
    }

    .ms-stat {
        flex: 1;
    }
}

@media (max-width: 600px) {

    .menu-status-page {
        padding: 14px 10px;
    }

    .ms-heading h1 {
        font-size: 22px;
    }

    .ms-heading-icon {
        width: 44px;
        height: 44px;
    }

    .ms-toolbar {
        grid-template-columns: 1fr;
    }

    .ms-stats {
        display: grid;
        grid-template-columns: 1fr 1fr;
    }

    .ms-stat {
        min-width: 0;
    }

    .ms-bulkbar {
        align-items: flex-start;
        flex-direction: column;
    }

    .ms-bulk-actions {
        width: 100%;
    }

    .ms-bulk-btn {
        flex: 1;
    }
}

</style>


<div class="menu-status-page">

    <div class="ms-container">


        <!-- PAGE HEADER -->

        <div class="ms-page-header">

            <div class="ms-heading">

                <div class="ms-heading-icon">
                    <i class="fa-solid fa-toggle-on"></i>
                </div>

                <div>

                    <h1>
                        Menu Status
                    </h1>

                    <p>
                        Control which menu items are active or inactive on the website.
                    </p>

                </div>

            </div>


            <div class="ms-stats">

                <div class="ms-stat">
                    <strong>
                        <?= $totalItems ?>
                    </strong>
                    <span>Total Items</span>
                </div>

                <div class="ms-stat active">
                    <strong>
                        <?= $activeItems ?>
                    </strong>
                    <span>Active</span>
                </div>

                <div class="ms-stat inactive">
                    <strong>
                        <?= $inactiveItems ?>
                    </strong>
                    <span>Inactive</span>
                </div>

            </div>

        </div>


        <!-- FILTER -->

        <form
            method="GET"
            class="ms-toolbar"
        >

            <select
                name="menu_id"
                class="ms-select"
            >

                <option value="0">
                    All Menus
                </option>

                <?php foreach ($menus as $menu): ?>

                    <option
                        value="<?= (int) $menu['id'] ?>"
                        <?= selected(
                            $menuId,
                            $menu['id']
                        ) ?>
                    >
                        <?= e($menu['name']) ?>
                        — <?= e($menu['location']) ?>
                    </option>

                <?php endforeach; ?>

            </select>


            <select
                name="status"
                class="ms-select"
            >

                <option value="">
                    All Status
                </option>

                <option
                    value="1"
                    <?= selected(
                        $statusFilter,
                        '1'
                    ) ?>
                >
                    Active
                </option>

                <option
                    value="0"
                    <?= selected(
                        $statusFilter,
                        '0'
                    ) ?>
                >
                    Inactive
                </option>

            </select>


            <input
                type="search"
                name="search"
                class="ms-input"
                value="<?= e($search) ?>"
                placeholder="Search menu item..."
            >


            <button
                type="submit"
                class="ms-btn ms-btn-primary"
            >
                <i class="fa-solid fa-filter"></i>
                &nbsp; Filter
            </button>

        </form>


        <!-- BULK BAR -->

        <div
            class="ms-bulkbar"
            id="bulkBar"
        >

            <div class="ms-selected-count">

                <span id="selectedCount">
                    0
                </span>

                item(s) selected

            </div>


            <div class="ms-bulk-actions">

                <button
                    type="button"
                    class="ms-bulk-btn ms-bulk-active"
                    onclick="bulkUpdate(1)"
                >
                    <i class="fa-solid fa-check"></i>
                    Activate
                </button>


                <button
                    type="button"
                    class="ms-bulk-btn ms-bulk-inactive"
                    onclick="bulkUpdate(0)"
                >
                    <i class="fa-solid fa-ban"></i>
                    Deactivate
                </button>

            </div>

        </div>


        <!-- MAIN CARD -->

        <div class="ms-card">

            <div class="ms-card-head">

                <h2>
                    Menu Item Status
                </h2>

                <span>
                    <?= count($items) ?> item(s)
                </span>

            </div>


            <?php if (!$items): ?>

                <div class="ms-empty">

                    <div class="ms-empty-icon">
                        <i class="fa-solid fa-list"></i>
                    </div>

                    <h3>
                        No menu items found
                    </h3>

                    <p>
                        Try changing your filters or create menu items first.
                    </p>

                </div>

            <?php else: ?>

                <div class="ms-table-wrap">

                    <table class="ms-table">

                        <thead>

                            <tr>

                                <th style="width:45px;">

                                    <input
                                        type="checkbox"
                                        class="ms-check"
                                        id="selectAll"
                                        title="Select all"
                                    >

                                </th>

                                <th>
                                    Menu Item
                                </th>

                                <th>
                                    Menu
                                </th>

                                <th>
                                    Type
                                </th>

                                <th>
                                    Status
                                </th>

                                <th>
                                    Toggle
                                </th>

                            </tr>

                        </thead>


                        <tbody>

                        <?php foreach ($items as $item): ?>

                            <?php

                            $isActive =
                                (int) $item['status'] === 1;

                            ?>

                            <tr
                                id="row-<?= (int) $item['id'] ?>"
                                class="<?= !$isActive
                                    ? 'row-inactive'
                                    : ''
                                ?>"
                            >

                                <td>

                                    <input
                                        type="checkbox"
                                        class="ms-check item-check"
                                        value="<?= (int) $item['id'] ?>"
                                    >

                                </td>


                                <td>

                                    <div class="ms-item">

                                        <div class="ms-item-icon">

                                            <i class="fa-solid fa-link"></i>

                                        </div>

                                        <div>

                                            <div class="ms-item-name">

                                                <?= e(
                                                    $item['title']
                                                ) ?>

                                            </div>

                                            <div class="ms-item-meta">

                                                ID #<?= (int) $item['id'] ?>

                                                <?php if (
                                                    !empty(
                                                        $item['slug']
                                                    )
                                                ): ?>

                                                    ·
                                                    <?= e(
                                                        $item['slug']
                                                    ) ?>

                                                <?php endif; ?>

                                            </div>

                                        </div>

                                    </div>

                                </td>


                                <td>

                                    <strong>
                                        <?= e(
                                            $item['menu_name']
                                        ) ?>
                                    </strong>

                                    <div class="ms-item-meta">
                                        <?= e(
                                            $item['menu_location']
                                        ) ?>
                                    </div>

                                </td>


                                <td>

                                    <span>
                                        <?= e(
                                            $item['item_type']
                                        ) ?>
                                    </span>

                                </td>


                                <td>

                                    <span
                                        class="ms-status <?= $isActive
                                            ? 'active'
                                            : 'inactive'
                                        ?>"
                                        id="status-<?= (int) $item['id'] ?>"
                                    >

                                        <span class="ms-dot"></span>

                                        <span class="status-text">

                                            <?= $isActive
                                                ? 'Active'
                                                : 'Inactive'
                                            ?>

                                        </span>

                                    </span>

                                </td>


                                <td>

                                    <button
                                        type="button"
                                        class="ms-toggle <?= $isActive
                                            ? 'active'
                                            : ''
                                        ?>"
                                        id="toggle-<?= (int) $item['id'] ?>"
                                        aria-label="Toggle status"
                                        onclick="toggleStatus(
                                            <?= (int) $item['id'] ?>,
                                            <?= $isActive ? 0 : 1 ?>
                                        )"
                                    ></button>

                                </td>

                            </tr>

                        <?php endforeach; ?>

                        </tbody>

                    </table>

                </div>

            <?php endif; ?>

        </div>

    </div>

</div>


<div
    class="ms-toast"
    id="msToast"
></div>


<script>

const CSRF_TOKEN =
    <?= csrf_token_json() ?>;


/*
|--------------------------------------------------------------------------
| Toast
|--------------------------------------------------------------------------
*/

function showToast(
    message,
    type = 'success'
) {

    const toast =
        document.getElementById('msToast');

    toast.textContent =
        message;

    toast.className =
        'ms-toast show ' + type;

    clearTimeout(
        window.__statusToast
    );

    window.__statusToast =
        setTimeout(() => {

            toast.classList.remove(
                'show'
            );

        }, 3200);
}


/*
|--------------------------------------------------------------------------
| Single Toggle
|--------------------------------------------------------------------------
*/

async function toggleStatus(
    itemId,
    newStatus
) {

    const button =
        document.getElementById(
            'toggle-' + itemId
        );

    if (!button) {
        return;
    }

    button.disabled = true;


    const formData =
        new FormData();

    formData.append(
        'action',
        'update_status'
    );

    formData.append(
        'item_id',
        itemId
    );

    formData.append(
        'status',
        newStatus
    );

    formData.append(
        'csrf_token',
        CSRF_TOKEN
    );


    try {

        const response =
            await fetch(
                'menu_status.php',
                {
                    method: 'POST',
                    body: formData,
                    credentials: 'same-origin'
                }
            );


        const data =
            await response.json();


        if (!data.success) {

            throw new Error(
                data.message
                || 'Unable to update status.'
            );
        }


        updateRowUI(
            itemId,
            newStatus
        );


        showToast(
            data.message
            || 'Status updated successfully.',
            'success'
        );


    } catch (error) {

        showToast(
            error.message
            || 'Something went wrong.',
            'error'
        );

    } finally {

        button.disabled = false;
    }
}


/*
|--------------------------------------------------------------------------
| Update Row UI
|--------------------------------------------------------------------------
*/

function updateRowUI(
    itemId,
    status
) {

    const row =
        document.getElementById(
            'row-' + itemId
        );

    const button =
        document.getElementById(
            'toggle-' + itemId
        );

    const badge =
        document.getElementById(
            'status-' + itemId
        );


    if (!row || !button || !badge) {
        return;
    }


    const isActive =
        Number(status) === 1;


    /*
     * Row
     */
    row.classList.toggle(
        'row-inactive',
        !isActive
    );


    /*
     * Toggle
     */
    button.classList.toggle(
        'active',
        isActive
    );

    button.setAttribute(
        'onclick',
        `toggleStatus(${itemId}, ${isActive ? 0 : 1})`
    );


    /*
     * Badge
     */
    badge.className =
        'ms-status ' +
        (
            isActive
                ? 'active'
                : 'inactive'
        );


    badge.innerHTML = `
        <span class="ms-dot"></span>
        <span class="status-text">
            ${isActive ? 'Active' : 'Inactive'}
        </span>
    `;
}


/*
|--------------------------------------------------------------------------
| Select All
|--------------------------------------------------------------------------
*/

const selectAll =
    document.getElementById(
        'selectAll'
    );


if (selectAll) {

    selectAll.addEventListener(
        'change',
        function() {

            document
                .querySelectorAll('.item-check')
                .forEach(check => {

                    check.checked =
                        this.checked;

                });

            updateBulkBar();
        }
    );
}


/*
|--------------------------------------------------------------------------
| Individual Checkbox
|--------------------------------------------------------------------------
*/

document
    .querySelectorAll('.item-check')
    .forEach(check => {

        check.addEventListener(
            'change',
            updateBulkBar
        );

    });


/*
|--------------------------------------------------------------------------
| Bulk Bar
|--------------------------------------------------------------------------
*/

function updateBulkBar() {

    const checks =
        Array.from(
            document.querySelectorAll(
                '.item-check:checked'
            )
        );

    const bar =
        document.getElementById(
            'bulkBar'
        );

    const count =
        document.getElementById(
            'selectedCount'
        );


    count.textContent =
        checks.length;


    bar.classList.toggle(
        'show',
        checks.length > 0
    );


    const all =
        document.querySelectorAll(
            '.item-check'
        );


    if (
        selectAll
        && all.length
    ) {

        selectAll.checked =
            checks.length === all.length;

        selectAll.indeterminate =
            checks.length > 0
            && checks.length < all.length;
    }
}


/*
|--------------------------------------------------------------------------
| Bulk Update
|--------------------------------------------------------------------------
*/

async function bulkUpdate(
    newStatus
) {

    const selected =
        Array.from(
            document.querySelectorAll(
                '.item-check:checked'
            )
        ).map(
            checkbox =>
                checkbox.value
        );


    if (!selected.length) {

        showToast(
            'Please select at least one menu item.',
            'error'
        );

        return;
    }


    const actionText =
        newStatus === 1
            ? 'activate'
            : 'deactivate';


    if (
        !confirm(
            `Are you sure you want to ${actionText} ${selected.length} menu item(s)?`
        )
    ) {
        return;
    }


    const formData =
        new FormData();

    formData.append(
        'action',
        'bulk_status'
    );

    formData.append(
        'status',
        newStatus
    );

    formData.append(
        'csrf_token',
        CSRF_TOKEN
    );


    selected.forEach(id => {

        formData.append(
            'item_ids[]',
            id
        );

    });


    try {

        const response =
            await fetch(
                'menu_status.php',
                {
                    method: 'POST',
                    body: formData,
                    credentials: 'same-origin'
                }
            );


        const data =
            await response.json();


        if (!data.success) {

            throw new Error(
                data.message
                || 'Bulk update failed.'
            );
        }


        selected.forEach(id => {

            updateRowUI(
                Number(id),
                newStatus
            );

        });


        document
            .querySelectorAll('.item-check')
            .forEach(
                checkbox => {
                    checkbox.checked = false;
                }
            );


        if (selectAll) {
            selectAll.checked = false;
            selectAll.indeterminate = false;
        }


        updateBulkBar();


        showToast(
            data.message
            || 'Status updated successfully.',
            'success'
        );


    } catch (error) {

        showToast(
            error.message
            || 'Something went wrong.',
            'error'
        );
    }
}

</script>


<?php

require_once __DIR__ . '/footer.php';

?>