<?php

declare(strict_types=1);

/** @var string $title */
/** @var string $content */
/** @var array $config */
/** @var array $nav */
/** @var array $user */

?><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= e($title . ' - ' . Settings::get('app_name', $config['app']['name'] ?? 'App')) ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="icon" type="image/png" href="/pest/assets/img/logo.png">
    <style>
        :root {
            --ui-border: #e2e8f0;
            --ui-border-hover: #cbd5e1;
            --ui-focus: #2563eb;
            --ui-bg: #ffffff;
            --ui-muted: #f8fafc;
            --ui-text: #0f172a;
            --ui-text-muted: #475569;
        }

        body {
            color: var(--ui-text);
        }

        input[type="text"],
        input[type="email"],
        input[type="password"],
        input[type="number"],
        input[type="search"],
        input[type="tel"],
        input[type="url"],
        input[type="date"],
        input[type="time"],
        textarea,
        select {
            background: var(--ui-bg) !important;
            border-color: var(--ui-border) !important;
            border-radius: 9999px !important;
            padding: 0.6rem 1rem !important;
            font-size: 0.875rem;
            line-height: 1.25rem;
            outline: none;
            transition: box-shadow 150ms ease, border-color 150ms ease;
        }

        textarea {
            border-radius: 1.25rem !important;
            min-height: 110px;
        }

        input[type="text"]:hover,
        input[type="email"]:hover,
        input[type="password"]:hover,
        input[type="number"]:hover,
        input[type="search"]:hover,
        input[type="tel"]:hover,
        input[type="url"]:hover,
        input[type="date"]:hover,
        input[type="time"]:hover,
        textarea:hover,
        select:hover {
            border-color: var(--ui-border-hover) !important;
        }

        input[type="text"]:focus,
        input[type="email"]:focus,
        input[type="password"]:focus,
        input[type="number"]:focus,
        input[type="search"]:focus,
        input[type="tel"]:focus,
        input[type="url"]:focus,
        input[type="date"]:focus,
        input[type="time"]:focus,
        textarea:focus,
        select:focus {
            border-color: var(--ui-focus) !important;
            box-shadow: 0 0 0 4px rgba(37, 99, 235, 0.16) !important;
        }

        input[type="checkbox"],
        input[type="radio"] {
            accent-color: var(--ui-focus);
        }

        button,
        input[type="submit"],
        input[type="button"],
        a.button {
            border-radius: 9999px;
        }
    </style>
</head>
<body class="bg-slate-50 text-slate-900">
    <div class="min-h-screen">
        <header class="border-b bg-white">
            <div class="mx-auto max-w-7xl px-4 py-0 flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="h-16 w-16 overflow-hidden rounded-xl bg-white border border-slate-200 flex items-center justify-center">
                        <img class="h-16 w-16 object-contain block" src="/pest/assets/img/logo.png" alt="<?= e((string)($config['app']['name'] ?? 'Logo')) ?>">
                    </div>
                    <div>
                        <div class="font-semibold leading-tight"><?= e(Settings::get('app_name', $config['app']['name'] ?? 'App')) ?></div>
                        <div class="text-xs text-slate-500 leading-tight"><?= e((string)($user['user_type'] ?? '')) ?> Dashboard</div>
                    </div>
                </div>
                <div class="flex items-center gap-3">
                    <button id="btnSidebarOpen" class="inline-flex items-center justify-center rounded-lg border px-3 py-2 text-sm hover:bg-slate-50 lg:hidden" type="button" aria-controls="sidebar" aria-expanded="false">
                        Menu
                    </button>
                    <div class="text-right hidden sm:block">
                        <div class="text-sm font-medium leading-tight"><?= e((string)($user['full_name'] ?? '')) ?></div>
                        <div class="text-xs text-slate-500 leading-tight"><?= e((string)($user['email'] ?? '')) ?></div>
                    </div>
                    <a class="inline-flex items-center justify-center rounded-lg border px-3 py-2 text-sm hover:bg-slate-50" href="/pest/public/logout.php">Logout</a>
                </div>
            </div>
        </header>

        <div class="mx-auto max-w-7xl px-4 py-6">
            <div id="sidebarOverlay" class="fixed inset-0 bg-slate-900/40 opacity-0 pointer-events-none transition-opacity duration-200 lg:hidden" aria-hidden="true"></div>

            <div class="grid grid-cols-1 gap-6 lg:grid-cols-[260px_1fr]">
                <aside id="sidebar" class="rounded-xl border bg-white p-3 h-fit fixed left-0 top-0 z-50 h-full w-72 -translate-x-full transition-transform duration-200 ease-out lg:static lg:z-auto lg:h-fit lg:w-auto lg:translate-x-0" aria-label="Sidebar">
                    <div class="flex items-center justify-between px-2 py-2 lg:hidden">
                        <div class="text-sm font-semibold text-slate-900">Menu</div>
                        <button id="btnSidebarClose" class="rounded-lg border px-3 py-2 text-sm hover:bg-slate-50" type="button" aria-controls="sidebar" aria-expanded="true">Close</button>
                    </div>
                    <nav class="space-y-1">
                        <?php
                            $userType = (string)($user['user_type'] ?? '');
                            $navItems = $nav;
                            if ($userType === 'admin') {
                                $adminOrder = ['Overview', 'Customers', 'Staff', 'Staff Locations', 'Services', 'Completed Tasks', 'To Do Tasks', 'Task Assignment', 'Reports', 'Complaints', 'Users', 'Settings'];

                                $adminDefaults = [
                                    'Overview' => ['label' => 'Overview', 'href' => Constants::APP_ROOT . '/admin/index.php', 'active' => false],
                                    'Customers' => ['label' => 'Customers', 'href' => Constants::APP_ROOT . '/admin/customers.php', 'active' => false],
                                    'Staff' => ['label' => 'Staff', 'href' => Constants::APP_ROOT . '/admin/staff.php', 'active' => false],
                                    'Staff Locations' => ['label' => 'Staff Locations', 'href' => Constants::APP_ROOT . '/admin/staff_locations.php', 'active' => false],
                                    'Services' => ['label' => 'Services', 'href' => Constants::APP_ROOT . '/admin/services.php', 'active' => false],
                                    'Completed Tasks' => ['label' => 'Completed Tasks', 'href' => Constants::APP_ROOT . '/admin/task_assignment.php?view=completed', 'active' => false],
                                    'To Do Tasks' => ['label' => 'To Do Tasks', 'href' => Constants::APP_ROOT . '/admin/todo_tasks.php', 'active' => false],
                                    'Task Assignment' => ['label' => 'Task Assignment', 'href' => Constants::APP_ROOT . '/admin/task_assignment.php', 'active' => false],
                                    'Reports' => ['label' => 'Reports', 'href' => Constants::APP_ROOT . '/admin/reports.php', 'active' => false],
                                    'Complaints' => ['label' => 'Complaints', 'href' => Constants::APP_ROOT . '/admin/complaints.php', 'active' => false],
                                    'Users' => ['label' => 'Users', 'href' => Constants::APP_ROOT . '/admin/users.php', 'active' => false],
                                    'Settings' => ['label' => 'Settings', 'href' => Constants::APP_ROOT . '/admin/settings.php', 'active' => false],
                                ];

                                $adminMap = [];
                                foreach ($navItems as $it) {
                                    $lbl = (string)($it['label'] ?? '');
                                    if ($lbl === '') {
                                        continue;
                                    }
                                    if (!isset($adminMap[$lbl])) {
                                        $adminMap[$lbl] = $it;
                                        continue;
                                    }
                                    $adminMap[$lbl]['active'] = (!empty($adminMap[$lbl]['active']) || !empty($it['active']));
                                }

                                $ordered = [];
                                foreach ($adminOrder as $lbl) {
                                    $base = $adminDefaults[$lbl] ?? ['label' => $lbl, 'href' => '#', 'active' => false];
                                    if (isset($adminMap[$lbl])) {
                                        $merged = $base;
                                        if (isset($adminMap[$lbl]['href'])) {
                                            $merged['href'] = $adminMap[$lbl]['href'];
                                        }
                                        $merged['active'] = !empty($adminMap[$lbl]['active']);
                                        $ordered[] = $merged;
                                    } else {
                                        $ordered[] = $base;
                                    }
                                }

                                $navItems = $ordered;
                            }

                            if ($userType === 'customer') {
                                $order = ['Overview', 'My Services', 'IPM Map', 'Gap Analysis Report', 'Trend Analysis Report', 'My Requests', 'Request Service', 'Complaints', 'Service Reports', 'Payments'];
                                $rank = array_flip($order);
                                usort($navItems, static function (array $a, array $b) use ($rank): int {
                                    $la = (string)($a['label'] ?? '');
                                    $lb = (string)($b['label'] ?? '');

                                    $na = $la;
                                    $nb = $lb;
                                    if ($na === 'Request Services') {
                                        $na = 'Request Service';
                                    }
                                    if ($nb === 'Request Services') {
                                        $nb = 'Request Service';
                                    }
                                    if ($na === 'Complaint') {
                                        $na = 'Complaints';
                                    }
                                    if ($nb === 'Complaint') {
                                        $nb = 'Complaints';
                                    }

                                    $ra = $rank[$na] ?? 999;
                                    $rb = $rank[$nb] ?? 999;
                                    if ($ra !== $rb) {
                                        return $ra <=> $rb;
                                    }
                                    return 0;
                                });
                            }
                        ?>

                        <?php foreach ($navItems as $item): ?>
                            <?php
                                $href = $item['href'];
                                $label = $item['label'];
                                $active = !empty($item['active']);
                                $userType = (string)($user['user_type'] ?? '');

                                if ($userType === 'admin' && $label === 'Payments') {
                                    continue;
                                }

                                if ($userType === 'customer' && $label === 'Payments') {
                                    continue;
                                }

                                if ($userType === 'customer' && $label === 'Service Reports') {
                                    continue;
                                }
                            ?>
                            <a class="group block rounded-lg px-3 py-2 text-sm transition-all duration-200 ease-out <?= $active ? 'bg-blue-600 text-white shadow-sm' : 'text-slate-700 hover:bg-blue-50 hover:text-blue-700 hover:translate-x-0.5' ?>" href="<?= e($href) ?>">
                                <?= e($label) ?>
                            </a>
                        <?php endforeach; ?>
                    </nav>
                </aside>

                <main class="space-y-6 pb-20 lg:pb-0">
                    <?= $content ?>
                </main>
            </div>
        </div>
    </div>

    <?php
        $userType = (string)($user['user_type'] ?? '');
        $bottomNav = [];

        if ($userType === 'admin') {
            $bottomNav = [
                ['label' => 'Overview', 'href' => '/pest/public/admin/index.php', 'icon' => 'home'],
                ['label' => 'Customers', 'href' => '/pest/public/admin/customers.php', 'icon' => 'users'],
                ['label' => 'Tasks', 'href' => '/pest/public/admin/task_assignment.php', 'icon' => 'clipboard'],
            ];
        } elseif ($userType === 'staff') {
            $bottomNav = [
                ['label' => 'Tasks', 'href' => '/pest/public/staff/index.php', 'icon' => 'clipboard'],
                ['label' => 'Upload', 'href' => '/pest/public/staff/upload_images.php', 'icon' => 'upload'],
                ['label' => 'Location', 'href' => '/pest/public/staff/location.php', 'icon' => 'pin'],
                ['label' => 'History', 'href' => '/pest/public/staff/history.php', 'icon' => 'clock'],
            ];
        } else {
            $bottomNav = [
                ['label' => 'Requests', 'href' => '/pest/public/customer/index.php', 'icon' => 'list'],
                ['label' => 'My Services', 'href' => '/pest/public/customer/my_services.php', 'icon' => 'clipboard'],
                ['label' => 'New', 'href' => '/pest/public/customer/request_service.php', 'icon' => 'plus'],
                ['label' => 'Help', 'href' => '/pest/public/customer/complaints.php', 'icon' => 'chat'],
            ];
        }

        $curPath = (string)parse_url((string)($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);

        $icons = [
            'home' => '<path d="M3 10.5L12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1v-9.5z" />',
            'users' => '<path d="M16 11a4 4 0 1 0-8 0 4 4 0 0 0 8 0z" /><path d="M4 21a8 8 0 0 1 16 0" />',
            'clipboard' => '<path d="M9 4h6a2 2 0 0 1 2 2v1h1a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1V6a2 2 0 0 1 2-2z" /><path d="M9 6h6" />',
            'cash' => '<path d="M4 7h16v10H4V7z" /><path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z" /><path d="M4 10h2M18 14h2" />',
            'upload' => '<path d="M12 3v12" /><path d="M7 8l5-5 5 5" /><path d="M5 21h14" />',
            'pin' => '<path d="M12 21s7-4.5 7-11a7 7 0 1 0-14 0c0 6.5 7 11 7 11z" /><path d="M12 10.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5z" />',
            'clock' => '<path d="M12 22a10 10 0 1 0-10-10 10 10 0 0 0 10 10z" /><path d="M12 6v6l4 2" />',
            'list' => '<path d="M8 6h13" /><path d="M8 12h13" /><path d="M8 18h13" /><path d="M3 6h.01" /><path d="M3 12h.01" /><path d="M3 18h.01" />',
            'plus' => '<path d="M12 5v14" /><path d="M5 12h14" />',
            'chat' => '<path d="M21 15a4 4 0 0 1-4 4H8l-5 3V7a4 4 0 0 1 4-4h10a4 4 0 0 1 4 4z" />',
        ];
    ?>

    <nav class="fixed bottom-0 left-0 right-0 z-40 border-t bg-white/95 backdrop-blur lg:hidden" aria-label="Bottom Navigation">
        <div class="mx-auto max-w-7xl px-2">
            <div class="grid grid-cols-4">
                <?php foreach ($bottomNav as $b): ?>
                    <?php
                        $isActive = ($curPath === $b['href']);
                        $iconKey = $b['icon'];
                        $iconPath = $icons[$iconKey] ?? '';
                    ?>
                    <a class="flex flex-col items-center justify-center gap-1 py-2 text-[11px] font-medium transition-all duration-200 <?= $isActive ? 'text-blue-700' : 'text-slate-600 hover:text-blue-700' ?>" href="<?= e($b['href']) ?>">
                        <svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                            <?= $iconPath ?>
                        </svg>
                        <span><?= e($b['label']) ?></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>
    </nav>

    <script>
        (function () {
            var sidebar = document.getElementById('sidebar');
            var overlay = document.getElementById('sidebarOverlay');
            var btnOpen = document.getElementById('btnSidebarOpen');
            var btnClose = document.getElementById('btnSidebarClose');

            function openSidebar() {
                if (!sidebar || !overlay) return;
                sidebar.classList.remove('-translate-x-full');
                overlay.classList.remove('opacity-0', 'pointer-events-none');
                btnOpen && btnOpen.setAttribute('aria-expanded', 'true');
            }

            function closeSidebar() {
                if (!sidebar || !overlay) return;
                sidebar.classList.add('-translate-x-full');
                overlay.classList.add('opacity-0', 'pointer-events-none');
                btnOpen && btnOpen.setAttribute('aria-expanded', 'false');
            }

            btnOpen && btnOpen.addEventListener('click', openSidebar);
            btnClose && btnClose.addEventListener('click', closeSidebar);
            overlay && overlay.addEventListener('click', closeSidebar);

            window.addEventListener('keydown', function (e) {
                if (e.key === 'Escape') closeSidebar();
            });

            window.addEventListener('resize', function () {
                if (window.innerWidth >= 1024) {
                    overlay && overlay.classList.add('opacity-0', 'pointer-events-none');
                }
            });
        })();
    </script>
</body>
</html>
