<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection not available.");
}
$conn->set_charset("utf8mb4");

if (!function_exists('e')) {
    function e($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

$permissionTable = "Zabbar_Admin_Permission";
$sessionTimeout = 1200;

if (
    empty($_SESSION['auth_logged_in']) ||
    empty($_SESSION['auth_last_activity']) ||
    (time() - (int)$_SESSION['auth_last_activity']) > $sessionTimeout
) {
    session_unset();
    session_destroy();
    header("Location: admin_login.php");
    exit;
}
$_SESSION['auth_last_activity'] = time();

$role = (string)($_SESSION['auth_role'] ?? '');
$username = (string)($_SESSION['auth_username'] ?? '');
$password = (string)($_SESSION['auth_password'] ?? '');
$isAdmin = ($role === 'admin');

if (!function_exists('hasPermission')) {
    function hasPermission(?array $row, array $columns): bool {
        if (!$row) return false;
        foreach ($columns as $col) {
            if (!array_key_exists($col, $row)) continue;
            $val = $row[$col];
            if ($val === 'Yes' || $val === 'yes' || $val === '1' || $val === 1 || $val === true) return true;
        }
        return false;
    }

    function hasMatchDataPermission(?array $row): bool {
        if (!$row || empty($row['match_data'])) return false;
        $data = json_decode($row['match_data'], true);
        if (!is_array($data)) return false;
        foreach ($data as $perms) {
            if (is_array($perms)) {
                foreach ($perms as $permVal) {
                    if (in_array($permVal, ['Yes', 'yes', 1, '1'], true)) return true;
                }
            }
        }
        return false;
    }

    function getIcon(string $filename): string {
        $icons = [
            'index.php' => 'fa-house',
            'addtnx.php' => 'fa-file-invoice-dollar',
            'product_orders.php' => 'fa-cart-shopping',
            'UserInfo.php' => 'fa-users',
            'moneyhistory.php' => 'fa-wallet',
            'withdrawal_history.php' => 'fa-money-bill-transfer',
            'refound_history.php' => 'fa-rotate-left',
            'zabbarnotification.php' => 'fa-bell',
            'announcements.php' => 'fa-bullhorn',
            'Settings.php' => 'fa-gear',
            'image_slider.php' => 'fa-images',
            'DailogSlider.php' => 'fa-message',
            'deposit_bonus.php' => 'fa-hand-holding-heart',
            'category.php' => 'fa-layer-group',
            'shop_product.php' => 'fa-store',
            'topup_list.php' => 'fa-list-check',
            'topup_order.php' => 'fa-cart-plus',
            'gift_requests.php' => 'fa-gift',
            'create_match.php' => 'fa-gamepad',
            'schedule_match.php' => 'fa-calendar-days'
        ];

        $iconClass = $icons[$filename] ?? 'fa-circle-dot';
        return '<i class="fa-solid ' . $iconClass . '"></i>';
    }
}

$permissionRow = null;
if (!$isAdmin) {
    $stmt = $conn->prepare("SELECT * FROM `$permissionTable` WHERE username = ? AND password = ? LIMIT 1");
    if ($stmt) {
        $stmt->bind_param("ss", $username, $password);
        $stmt->execute();
        $res = $stmt->get_result();
        $permissionRow = $res ? $res->fetch_assoc() : null;
        $stmt->close();
    }
}

$modules = [
    ['file' => 'index.php', 'label' => 'Dashboard'],
    ['file' => 'addtnx.php', 'label' => 'Add Transaction', 'mode' => 'admin_only'],
    ['file' => 'product_orders.php', 'label' => 'Product Orders', 'mode' => 'admin_only'],
    ['file' => 'UserInfo.php', 'label' => 'User Info', 'permissions' => ['members_read', 'members_edit', 'members_delete']],
    ['file' => 'moneyhistory.php', 'label' => 'Addmoney History', 'permissions' => ['addmoney_history_read', 'addmoney_history_edit', 'addmoney_history_delete']],
    ['file' => 'withdrawal_history.php', 'label' => 'Withdrawal History', 'permissions' => ['withdrawal_history_read', 'withdrawal_history_edit', 'withdrawal_history_delete']],
    ['file' => 'refound_history.php', 'label' => 'Refund Management', 'permissions' => ['refund_history_read', 'refund_history_delete', 'refund_send']],
    ['file' => 'zabbarnotification.php', 'label' => 'Notification Panel', 'permissions' => ['notification_send']],
    ['file' => 'announcements.php', 'label' => 'Announcements', 'permissions' => ['app_settings_edit']],
    ['file' => 'Settings.php', 'label' => 'App Settings', 'permissions' => ['app_settings_read', 'app_settings_edit']],
    ['file' => 'image_slider.php', 'label' => 'Image Slider', 'permissions' => ['slider_read', 'slider_edit', 'slider_delete']],
    ['file' => 'DailogSlider.php', 'label' => 'Dialog Slider', 'permissions' => ['dialog_slider_read', 'dialog_slider_edit', 'dialog_slider_delete']],
    ['file' => 'deposit_bonus.php', 'label' => 'Deposit Bonus', 'permissions' => ['deposit_bonus_read', 'deposit_bonus_edit', 'deposit_bonus_delete']],
    ['file' => 'category.php', 'label' => 'Category', 'permissions' => ['category_add', 'category_edit', 'category_delete']],
    ['file' => 'shop_product.php', 'label' => 'Shop Product', 'permissions' => ['Shop_Product_Read', 'Shop_Product_Edit', 'Shop_Product_Delete']],
    ['file' => 'topup_list.php', 'label' => 'Topup List', 'permissions' => ['Shop_TopUP_Read', 'Shop_TopUP_Edit', 'Shop_TopUP_Delete']],
    ['file' => 'topup_order.php', 'label' => 'Topup Order', 'permissions' => ['Shop_TopUP_Read', 'Shop_TopUP_Edit', 'Shop_TopUP_Delete']],
    ['file' => 'gift_requests.php', 'label' => 'Gift Requests', 'permissions' => ['Geft_Read', 'Geft_Edit', 'Geft_Delete']],
    ['file' => 'create_match.php', 'label' => 'Create Match', 'check_match_data' => true],
    ['file' => 'schedule_match.php', 'label' => 'Schedule Match', 'check_match_data' => true]
];

$visibleModules = [];
foreach ($modules as $module) {
    if ($isAdmin) {
        $visibleModules[] = $module;
    } elseif (($module['mode'] ?? '') !== 'admin_only') {
        if ($module['file'] === 'index.php') {
            $visibleModules[] = $module;
        } elseif (!empty($module['check_match_data']) && hasMatchDataPermission($permissionRow)) {
            $visibleModules[] = $module;
        } elseif (!empty($module['permissions']) && hasPermission($permissionRow, $module['permissions'])) {
            $visibleModules[] = $module;
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en" data-theme="light">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Admin Panel</title>

    <script>
        (function () {
            try {
                const saved = localStorage.getItem('theme');
                const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
                const theme = saved ? saved : (prefersDark ? 'dark' : 'light');
                document.documentElement.setAttribute('data-theme', theme);
            } catch (e) {
                document.documentElement.setAttribute('data-theme', 'light');
            }
        })();
    </script>

    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        :root {
            --ap-sidebar-width: 260px;
            --ap-bg: #f4f7fe;
            --ap-card: #ffffff;
            --ap-card-2: #f8fbff;
            --ap-primary: #4318ff;
            --ap-primary-soft: #eef2ff;
            --ap-text: #0f172a;
            --ap-text-soft: #475569;
            --ap-muted: #94a3b8;
            --ap-border: #e0e5f2;
            --ap-shadow: 0 4px 20px rgba(15, 23, 42, 0.05);
            --ap-hover: #eef2ff;
            --ap-active: #e0e7ff;
            --ap-icon: #64748b;
        }

        html[data-theme="dark"] {
            --ap-bg: #0b1220;
            --ap-card: #111827;
            --ap-card-2: #1f2937;
            --ap-primary: #8b5cf6;
            --ap-primary-soft: #1a2540;
            --ap-text: #f3f4f6;
            --ap-text-soft: #cbd5e1;
            --ap-muted: #94a3b8;
            --ap-border: #374151;
            --ap-shadow: 0 4px 20px rgba(0, 0, 0, 0.35);
            --ap-hover: #1f2a3d;
            --ap-active: #374151;
            --ap-icon: #cbd5e1;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        /* 
           Scroll Fixes:
           html & body 100% height allowed. only hidden on X-axis. 
        */
        html, body {
            min-height: 100%;
            overflow-x: hidden; 
        }

        body {
            background-color: var(--ap-bg);
            color: var(--ap-text);
            font-family: 'Plus Jakarta Sans', sans-serif;
            -webkit-font-smoothing: antialiased;
        }

        /* Mobile Top Header */
        .ap-mobile-header {
            display: none;
            background: var(--ap-card);
            padding: 0 20px;
            height: 65px;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid var(--ap-border);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
            box-shadow: var(--ap-shadow);
        }

        .ap-mobile-header h2 {
            font-size: 18px;
            font-weight: 800;
            color: var(--ap-text);
            margin: 0;
        }

        .ap-menu-btn {
            background: transparent;
            border: none;
            font-size: 22px;
            color: var(--ap-text);
            cursor: pointer;
            padding: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .ap-spacer {
            width: 32px;
        }

        /* Sidebar Overlay */
        .ap-sidebar-overlay {
            display: none;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1001;
            opacity: 0;
            transition: opacity 0.3s ease;
            backdrop-filter: blur(2px);
        }

        /* Sidebar - Used top:0 & bottom:0 instead of 100vh to fix mobile scroll */
        .ap-sidebar {
            width: var(--ap-sidebar-width);
            background: var(--ap-card);
            position: fixed;
            left: 0;
            top: 0;
            bottom: 0; 
            border-right: 1px solid var(--ap-border);
            z-index: 1002;
            display: flex;
            flex-direction: column;
            box-shadow: var(--ap-shadow);
            transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .ap-sidebar-top {
            padding: 20px 16px;
            border-bottom: 1px solid var(--ap-border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 10px;
            min-height: 80px;
        }

        .ap-brand h2 {
            font-size: 18px;
            color: var(--ap-text);
            font-weight: 800;
            margin: 0;
        }

        .ap-brand .ap-sub {
            margin-top: 4px;
            font-size: 12px;
            color: var(--ap-muted);
        }

        .ap-theme-toggle {
            border: 1px solid var(--ap-border);
            background: var(--ap-card-2);
            color: var(--ap-text);
            width: 40px;
            height: 40px;
            border-radius: 12px;
            cursor: pointer;
            display: grid;
            place-items: center;
            transition: 0.2s ease;
            outline: none;
        }

        .ap-theme-toggle:hover {
            background: var(--ap-hover);
        }

        .ap-sidebar-menu {
            flex: 1;
            padding: 15px 12px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 6px;
        }

        .ap-sidebar-menu::-webkit-scrollbar {
            width: 5px;
        }
        .ap-sidebar-menu::-webkit-scrollbar-thumb {
            background: var(--ap-border);
            border-radius: 10px;
        }
        .ap-sidebar-menu::-webkit-scrollbar-track {
            background: transparent;
        }

        .ap-menu-item {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 12px 14px;
            color: var(--ap-text-soft);
            text-decoration: none;
            border-radius: 10px;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.2s ease;
        }

        .ap-menu-item i {
            width: 20px;
            text-align: center;
            font-size: 16px;
            color: var(--ap-icon);
            transition: color 0.2s ease;
        }

        .ap-menu-item:hover {
            background: var(--ap-hover);
            color: var(--ap-text);
        }

        .ap-menu-item.active {
            background: var(--ap-active);
            color: var(--ap-primary);
        }

        .ap-menu-item.active i {
            color: var(--ap-primary);
        }

        /* 
           Main Content Area
           width removed and overflow-x auto added so tables don't break scroll 
        */
        .ap-main-content {
            margin-left: var(--ap-sidebar-width);
            padding: 24px;
            min-height: 100vh;
            transition: margin-left 0.3s ease;
            overflow-x: auto; /* Important: Prevents large tables from breaking body scroll */
        }

        /* Mobile Adjustments */
        @media (max-width: 991px) {
            .ap-mobile-header {
                display: flex;
            }

            .ap-sidebar {
                transform: translateX(-100%);
            }

            .ap-sidebar.show {
                transform: translateX(0);
            }

            .ap-sidebar-overlay.show {
                display: block;
                opacity: 1;
            }

            .ap-main-content {
                margin-left: 0;
                padding: 85px 15px 24px 15px; /* Added extra space for mobile header */
            }
        }
    </style>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            // Theme Script
            const root = document.documentElement;
            const btn = document.getElementById('themeToggle');
            const icon = document.getElementById('themeIcon');

            function setIcon(theme) {
                if (!icon) return;
                icon.className = theme === 'dark' ? 'fa-solid fa-sun' : 'fa-solid fa-moon';
            }

            let current = root.getAttribute('data-theme') || 'light';
            setIcon(current);

            if (btn) {
                btn.addEventListener('click', function () {
                    current = (root.getAttribute('data-theme') === 'dark') ? 'light' : 'dark';
                    localStorage.setItem('theme', current);
                    root.setAttribute('data-theme', current);
                    setIcon(current);
                });
            }

            // Mobile Sidebar Script
            const sidebar = document.getElementById('sidebar');
            const overlay = document.getElementById('sidebarOverlay');
            const menuBtn = document.getElementById('mobileMenuBtn');

            function openSidebar() {
                if(sidebar) sidebar.classList.add('show');
                if(overlay) overlay.classList.add('show');
                // Lock background scroll when sidebar is open
                document.body.style.overflow = 'hidden'; 
            }

            function closeSidebar() {
                if(sidebar) sidebar.classList.remove('show');
                if(overlay) overlay.classList.remove('show');
                // Restore background scroll
                document.body.style.overflow = ''; 
            }

            if(menuBtn) {
                menuBtn.addEventListener('click', openSidebar);
            }

            if(overlay) {
                overlay.addEventListener('click', closeSidebar);
            }
        });
    </script>
</head>
<body>

    <!-- Mobile Header -->
    <div class="ap-mobile-header">
        <button class="ap-menu-btn" id="mobileMenuBtn">
            <i class="fa-solid fa-bars"></i>
        </button>
        <h2>Admin Panel</h2>
        <div class="ap-spacer"></div>
    </div>

    <!-- Mobile Sidebar Overlay -->
    <div class="ap-sidebar-overlay" id="sidebarOverlay"></div>

    <!-- Sidebar -->
    <div class="ap-sidebar" id="sidebar">
        <div class="ap-sidebar-top">
            <div class="ap-brand">
                <h2>Admin Panel</h2>
                <div class="ap-sub">Light / Dark theme</div>
            </div>
            <button class="ap-theme-toggle" id="themeToggle" type="button" aria-label="Toggle theme">
                <i class="fa-solid fa-moon" id="themeIcon"></i>
            </button>
        </div>

        <div class="ap-sidebar-menu">
            <?php $currentPage = basename($_SERVER['PHP_SELF']); ?>
            <?php foreach ($visibleModules as $module): ?>
                <?php $isActive = ($currentPage === $module['file']) ? 'active' : ''; ?>
                <a href="<?= e($module['file']) ?>" class="ap-menu-item <?= $isActive ?>">
                    <?= getIcon((string)$module['file']) ?>
                    <span><?= e($module['label']) ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Main Content Starts Here -->
    <div class="ap-main-content">