<?php
require_once "config.php";

session_set_cookie_params([
    'lifetime' => 0,
    'path' => '/',
    'httponly' => true,
    'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
    'samesite' => 'Lax'
]);

session_start();
date_default_timezone_set("Asia/Dhaka");

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

$conn->set_charset("utf8mb4");

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

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

function session_alive(int $timeout): bool {
    if (empty($_SESSION['auth_logged_in']) || empty($_SESSION['auth_last_activity'])) {
        return false;
    }

    if ((time() - (int)$_SESSION['auth_last_activity']) > $timeout) {
        $_SESSION = [];
        session_destroy();
        return false;
    }

    $_SESSION['auth_last_activity'] = time();
    return true;
}

function fetch_row_by_credentials(mysqli $conn, string $table, string $username, string $password): ?array {
    $stmt = $conn->prepare("SELECT * FROM `$table` WHERE username = ? AND password = ? LIMIT 1");
    if (!$stmt) {
        return null;
    }

    $stmt->bind_param("ss", $username, $password);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res ? ($res->fetch_assoc() ?: null) : null;
    $stmt->close();

    return $row;
}

// ==========================================
// Admin Password Update Logic
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_admin_credentials') {
    if (!empty($_SESSION['auth_role']) && $_SESSION['auth_role'] === 'admin') {
        $current_user = $_SESSION['auth_username'];
        $new_user = trim($_POST['new_username'] ?? '');
        $old_pass = trim($_POST['old_password'] ?? '');
        $new_pass = trim($_POST['new_password'] ?? '');

        // Verify Old Password
        $verifyStmt = $conn->prepare("SELECT id FROM `$adminTable` WHERE username = ? AND password = ? LIMIT 1");
        $verifyStmt->bind_param("ss", $current_user, $old_pass);
        $verifyStmt->execute();
        $verifyRes = $verifyStmt->get_result();

        if ($verifyRes && $verifyRes->num_rows > 0) {
            // Update Database
            $updateStmt = $conn->prepare("UPDATE `$adminTable` SET username = ?, password = ? WHERE username = ?");
            $updateStmt->bind_param("sss", $new_user, $new_pass, $current_user);
            
            if ($updateStmt->execute()) {
                // Update Session so user doesn't get logged out
                $_SESSION['auth_username'] = $new_user;
                $_SESSION['auth_password'] = $new_pass;
                
                $_SESSION['flash_msg'] = "Credentials updated successfully!";
                $_SESSION['flash_type'] = "success";
            } else {
                $_SESSION['flash_msg'] = "Failed to update. Username might already exist.";
                $_SESSION['flash_type'] = "error";
            }
            $updateStmt->close();
        } else {
            $_SESSION['flash_msg'] = "Old password is incorrect!";
            $_SESSION['flash_type'] = "error";
        }
        $verifyStmt->close();
        
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}
// ==========================================

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 ($permVal === 'Yes' || $permVal === 'yes' || $permVal === 1 || $permVal === '1') {
                    return true;
                }
            }
        }
    }

    return false;
}

function getIcon(string $name): string {
    $n = strtolower($name);

    if (strpos($n, 'member') !== false || strpos($n, 'user') !== false) {
        return '<svg fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19.128a9.38 9.38 0 0 0 2.625.372 9.337 9.337 0 0 0 4.121-.952 4.125 4.125 0 0 0-7.533-2.493M15 19.128v-.003c0-1.113-.285-2.16-.786-3.07M15 19.128v.106A12.318 12.318 0 0 1 8.624 21c-2.331 0-4.512-.645-6.374-1.766l-.001-.109a6.375 6.375 0 0 1 11.964-3.07M12 6.375a3.375 3.375 0 1 1-6.75 0 3.375 3.375 0 0 1 6.75 0Zm8.25 2.25a2.625 2.625 0 1 1-5.25 0 2.625 2.625 0 0 1 5.25 0Z" /></svg>';
    }

    if (strpos($n, 'money') !== false || strpos($n, 'deposit') !== false || strpos($n, 'topup') !== false || strpos($n, 'bonus') !== false || strpos($n, 'refund') !== false || strpos($n, 'geft') !== false) {
        return '<svg fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M2.25 18.75a60.07 60.07 0 0 1 15.797 2.101c.727.198 1.453-.342 1.453-1.096V18.75M3.75 4.5h16.5M5.25 7.5h13.5m-12 9h10.5l1.05-10.5H4.2l1.05 10.5Zm1.5-6h7.5" /></svg>';
    }

    if (strpos($n, 'withdrawal') !== false) {
        return '<svg fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M7.5 7.5h.75m0 0h.75m-.75 0v.75m0 0v.75m0-1.5h1.5m-2.25 3.525 3.5-3.5 3.5 3.5m-7 4.95 3.5-3.5 3.5 3.5M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z" /></svg>';
    }

    if (strpos($n, 'notification') !== false || strpos($n, 'noti') !== false || strpos($n, 'announcement') !== false) {
        return '<svg fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M14.857 17.082a23.848 23.848 0 0 0 5.454-1.31A8.967 8.967 0 0 1 18 9.75V9A6 6 0 0 0 6 9v.75a8.967 8.967 0 0 1-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 0 1-5.714 0m5.714 0a3 3 0 1 1-5.714 0" /></svg>';
    }

    if (strpos($n, 'settings') !== false || strpos($n, 'rules') !== false || strpos($n, 'category') !== false) {
        return '<svg fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 0 0 2.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 0 0 1.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 0 0-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 0 0-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 0 0-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 0 0-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 0 0 1.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" /><path stroke-linecap="round" stroke-linejoin="round" d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0z" /></svg>';
    }

    if (strpos($n, 'slider') !== false) {
        return '<svg fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z" /></svg>';
    }

    if (strpos($n, 'match') !== false) {
        return '<svg fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M14.25 9.75L16.5 12l-2.25 2.25m-4.5 0L7.5 12l2.25-2.25M6 20.25h12A2.25 2.25 0 0 0 20.25 18V6A2.25 2.25 0 0 0 18 3.75H6A2.25 2.25 0 0 0 3.75 6v12A2.25 2.25 0 0 0 6 20.25Z" /></svg>';
    }

    return '<svg fill="none" viewBox="0 0 24 24" stroke-width="2" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h3.75M9 15h3.75M9 18h3.75m3 .75H18a2.25 2.25 0 0 0 2.25-2.25V6.108c0-1.135-.845-2.098-1.976-2.192a48.424 48.424 0 0 0-1.123-.08m-5.801 0c-.065.21-.1.433-.1.664 0 .414.336.75.75.75h4.5a.75.75 0 0 0 .75-.75 2.25 2.25 0 0 0-.1-.664m-5.8 0A2.251 2.251 0 0 1 13.5 2.25H15c1.03 0 1.9.693 2.166 1.638m-7.377 2.24a4.5 4.5 0 1 1 9 0M4.5 6.525v10.31A2.25 2.25 0 0 0 6.75 19.1h3.375" /></svg>';
}

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

function moduleIsVisible(array $module, bool $isAdmin, ?array $permissionRow): bool {
    if ($isAdmin) {
        return true;
    }

    if (($module['mode'] ?? '') === 'admin_only') {
        return false;
    }

    if (!empty($module['check_match_data']) && $module['check_match_data'] === true) {
        return hasMatchDataPermission($permissionRow);
    }

    if (!empty($module['permissions']) && is_array($module['permissions'])) {
        return hasPermission($permissionRow, $module['permissions']);
    }

    return false;
}

if (!session_alive($sessionTimeout)) {
    header("Location: admin_login.php");
    exit;
}

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

$isAdmin = ($role === 'admin');
$adminRow = null;
$permissionRow = null;

if ($isAdmin) {
    $adminRow = fetch_row_by_credentials($conn, $adminTable, $username, $password);
    if (!$adminRow) {
        session_unset();
        session_destroy();
        header("Location: admin_login.php");
        exit;
    }
} elseif ($role === 'permission') {
    $permissionRow = fetch_row_by_credentials($conn, $permissionTable, $username, $password);
    if (!$permissionRow) {
        session_unset();
        session_destroy();
        header("Location: admin_login.php");
        exit;
    }
} else {
    session_unset();
    session_destroy();
    header("Location: admin_login.php");
    exit;
}

$modules = buildModules();
$visibleModules = [];

foreach ($modules as $module) {
    if (moduleIsVisible($module, $isAdmin, $permissionRow)) {
        $visibleModules[] = $module;
    }
}

$initial = strtoupper(substr($username, 0, 1));
if ($initial === '') {
    $initial = 'A';
}

// Flash Message Handling
$flash_msg = $_SESSION['flash_msg'] ?? null;
$flash_type = $_SESSION['flash_type'] ?? 'success';
unset($_SESSION['flash_msg'], $_SESSION['flash_type']);

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Control Center</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg-body: #f4f7fe;
            --bg-card: #ffffff;
            --text-main: #2b3674;
            --text-muted: #a3aed1;
            --primary: #4318ff;
            --primary-light: #e9e3ff;
            --accent: #00b5ff;
            --success: #01b574;
            --success-light: #e5f7ed;
            --danger: #ee5d50;
            --danger-light: #ffedeb;
            --border: #e0e5f2;
            --radius-sm: 10px;
            --radius-md: 16px;
            --radius-lg: 20px;
            --shadow: 0px 18px 40px rgba(112, 144, 176, 0.12);
            --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }
        body {
            background-color: var(--bg-body);
            color: var(--text-main);
            display: flex;
            min-height: 100vh;
            overflow-x: hidden;
        }
        ::-webkit-scrollbar {
            width: 6px;
        }
        ::-webkit-scrollbar-track {
            background: transparent;
        }
        ::-webkit-scrollbar-thumb {
            background: var(--border);
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: var(--text-muted);
        }
        .sidebar {
            width: 290px;
            background: var(--bg-card);
            position: fixed;
            height: 100vh;
            z-index: 100;
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            transition: var(--transition);
        }
        .sidebar-brand {
            padding: 32px 24px;
            display: flex;
            align-items: center;
            gap: 14px;
        }
        .brand-logo {
            width: 44px;
            height: 44px;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            border-radius: var(--radius-sm);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 22px;
            font-weight: 800;
            box-shadow: 0 4px 15px rgba(67, 24, 255, 0.3);
        }
        .brand-text h2 {
            font-size: 18px;
            font-weight: 800;
            color: var(--text-main);
            letter-spacing: -0.5px;
        }
        .sidebar-menu {
            padding: 0 16px 24px;
            overflow-y: auto;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            gap: 6px;
        }
        .menu-item {
            display: flex;
            align-items: center;
            gap: 14px;
            padding: 14px 18px;
            color: var(--text-muted);
            text-decoration: none;
            font-weight: 600;
            font-size: 15px;
            border-radius: var(--radius-md);
            transition: var(--transition);
        }
        .menu-item:hover {
            background: var(--bg-body);
            color: var(--primary);
            transform: translateX(4px);
        }
        .menu-item svg {
            width: 22px;
            height: 22px;
            stroke-width: 2.5;
        }
        .main-content {
            margin-left: 290px;
            flex-grow: 1;
            padding: 32px 40px;
            width: calc(100% - 290px);
        }
        .topbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(255, 255, 255, 0.7);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            padding: 16px 24px;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow);
            margin-bottom: 24px;
            border: 1px solid rgba(255, 255, 255, 0.5);
            position: sticky;
            top: 20px;
            z-index: 50;
        }
        .page-title {
            font-size: 24px;
            font-weight: 800;
            letter-spacing: -0.5px;
        }
        .topbar-actions {
            display: flex;
            align-items: center;
            gap: 16px;
        }
        .settings-btn {
            background: var(--bg-body);
            border: none;
            width: 44px;
            height: 44px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--text-muted);
            cursor: pointer;
            transition: var(--transition);
        }
        .settings-btn:hover {
            background: var(--primary-light);
            color: var(--primary);
        }
        .settings-btn svg {
            width: 20px;
            height: 20px;
            stroke-width: 2.5;
        }
        .user-widget {
            display: flex;
            align-items: center;
            gap: 12px;
            background: #fff;
            padding: 6px 16px 6px 6px;
            border-radius: 50px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.03);
            border: 1px solid var(--border);
        }
        .avatar {
            width: 38px;
            height: 38px;
            background: linear-gradient(135deg, var(--primary), var(--accent));
            color: #fff;
            font-weight: 700;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }
        .user-info {
            display: flex;
            flex-direction: column;
        }
        .user-name {
            font-size: 14px;
            font-weight: 700;
            color: var(--text-main);
        }
        .user-role {
            font-size: 11px;
            font-weight: 600;
            color: var(--primary);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        /* Alert Box */
        .alert {
            padding: 16px 20px;
            border-radius: var(--radius-sm);
            margin-bottom: 24px;
            font-weight: 600;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
            animation: slideUp 0.3s ease;
        }
        .alert.success {
            background: var(--success-light);
            color: var(--success);
            border: 1px solid #b7ecd4;
        }
        .alert.error {
            background: var(--danger-light);
            color: var(--danger);
            border: 1px solid #ffc8c4;
        }

        .grid-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 24px;
        }
        .module-card {
            background: var(--bg-card);
            border-radius: var(--radius-lg);
            padding: 24px;
            display: flex;
            align-items: center;
            gap: 20px;
            text-decoration: none;
            box-shadow: var(--shadow);
            border: 1px solid transparent;
            transition: var(--transition);
            animation: slideUp 0.5s ease backwards;
        }
        .module-card:hover {
            transform: translateY(-6px);
            border-color: var(--primary-light);
            box-shadow: 0 20px 40px rgba(67, 24, 255, 0.15);
        }
        .icon-box {
            width: 56px;
            height: 56px;
            background: var(--bg-body);
            color: var(--primary);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: var(--transition);
            flex-shrink: 0;
        }
        .module-card:hover .icon-box {
            background: var(--primary);
            color: #fff;
            transform: scale(1.1) rotate(5deg);
        }
        .icon-box svg {
            width: 26px;
            height: 26px;
        }
        .card-details {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        .card-title {
            font-size: 16px;
            font-weight: 700;
            color: var(--text-main);
        }
        .status-badge {
            align-self: flex-start;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 4px 10px;
            background: var(--success-light);
            color: var(--success);
            font-size: 11px;
            font-weight: 700;
            border-radius: 20px;
            text-transform: uppercase;
        }
        .status-badge::before {
            content: '';
            width: 6px;
            height: 6px;
            background: var(--success);
            border-radius: 50%;
            display: inline-block;
            box-shadow: 0 0 0 rgba(1, 181, 116, 0.4);
            animation: pulse-ring 2s infinite;
        }
        
        /* Modal Styles */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(43, 54, 116, 0.5);
            backdrop-filter: blur(4px);
            display: none; /* Hidden by default */
            align-items: center;
            justify-content: center;
            z-index: 1000;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .modal-overlay.active {
            display: flex;
            opacity: 1;
        }
        .modal-content {
            background: var(--bg-card);
            width: 90%;
            max-width: 400px;
            border-radius: var(--radius-lg);
            padding: 32px;
            box-shadow: var(--shadow);
            transform: translateY(20px);
            transition: transform 0.3s ease;
        }
        .modal-overlay.active .modal-content {
            transform: translateY(0);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
        }
        .modal-header h3 {
            font-size: 18px;
            color: var(--text-main);
        }
        .close-btn {
            background: transparent;
            border: none;
            font-size: 24px;
            color: var(--text-muted);
            cursor: pointer;
        }
        .form-group {
            margin-bottom: 16px;
        }
        .form-group label {
            display: block;
            font-size: 13px;
            font-weight: 600;
            color: var(--text-muted);
            margin-bottom: 6px;
        }
        .form-group input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid var(--border);
            border-radius: var(--radius-sm);
            font-size: 14px;
            color: var(--text-main);
            outline: none;
            transition: var(--transition);
            background: var(--bg-body);
        }
        .form-group input:focus {
            border-color: var(--primary);
            background: #fff;
            box-shadow: 0 0 0 3px var(--primary-light);
        }
        .submit-btn {
            width: 100%;
            padding: 14px;
            background: var(--primary);
            color: #fff;
            border: none;
            border-radius: var(--radius-sm);
            font-weight: 700;
            font-size: 15px;
            cursor: pointer;
            transition: var(--transition);
            margin-top: 10px;
        }
        .submit-btn:hover {
            background: var(--primary-hover);
        }

        @keyframes slideUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        @keyframes pulse-ring {
            0% { box-shadow: 0 0 0 0 rgba(1, 181, 116, 0.7); }
            70% { box-shadow: 0 0 0 6px rgba(1, 181, 116, 0); }
            100% { box-shadow: 0 0 0 0 rgba(1, 181, 116, 0); }
        }
        .empty-state {
            grid-column: 1 / -1;
            text-align: center;
            padding: 60px 20px;
            background: rgba(255,255,255,0.5);
            border-radius: var(--radius-lg);
            border: 2px dashed var(--border);
            color: var(--text-muted);
            font-weight: 600;
        }
        
        @media (max-width: 1024px) {
            .sidebar { width: 80px; }
            .brand-text, .menu-item span { display: none; }
            .sidebar-brand { justify-content: center; padding: 24px 0; }
            .menu-item { justify-content: center; padding: 14px; }
            .main-content { margin-left: 80px; width: calc(100% - 80px); padding: 24px; }
        }
        @media (max-width: 768px) {
            body { flex-direction: column; }
            .sidebar { width: 100%; height: auto; position: relative; border-right: none; border-bottom: 1px solid var(--border); }
            .sidebar-menu { flex-direction: row; padding: 12px; gap: 10px; overflow-x: auto; }
            .main-content { margin-left: 0; width: 100%; padding: 16px; }
            .topbar { flex-direction: column; gap: 16px; text-align: center; position: relative; top: 0; margin-bottom: 24px; }
            .topbar-actions { width: 100%; justify-content: space-between; }
            .grid-container { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>
    <div class="sidebar">
        <div class="sidebar-brand">
            <div class="brand-logo">Z</div>
            <div class="brand-text">
                <h2>Zabbar</h2>
            </div>
        </div>
        <div class="sidebar-menu">
            <?php foreach ($visibleModules as $index => $module): ?>
                <a href="<?= e($module['file']) ?>" class="menu-item" style="animation: slideUp <?= 0.1 * $index ?>s ease backwards;">
                    <?= getIcon((string)$module['label']) ?>
                    <span><?= e($module['label']) ?></span>
                </a>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="main-content">
        <div class="topbar">
            <h1 class="page-title">Operations Center</h1>
            <div class="topbar-actions">
                <?php if ($isAdmin): ?>
                    <!-- Settings Button for Super Admin Only -->
                    <button class="settings-btn" onclick="openPassModal()" title="Change Admin Credentials">
                        <svg fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 5.25a3 3 0 0 1 3 3m3 0a6 6 0 0 1-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1 1 21.75 8.25Z" />
                        </svg>
                    </button>
                <?php endif; ?>
                
                <div class="user-widget">
                    <div class="avatar"><?= e($initial) ?></div>
                    <div class="user-info">
                        <span class="user-name"><?= e($username) ?></span>
                        <span class="user-role"><?= $isAdmin ? 'Super Admin' : 'Staff' ?></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Flash Message Output -->
        <?php if ($flash_msg): ?>
            <div class="alert <?= $flash_type ?>">
                <?php if($flash_type === 'success'): ?>
                    <svg width="20" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                <?php else: ?>
                    <svg width="20" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                <?php endif; ?>
                <?= e($flash_msg) ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($visibleModules)): ?>
            <div class="grid-container">
                <?php foreach ($visibleModules as $index => $module): ?>
                    <a href="<?= e($module['file']) ?>" class="module-card" style="animation-delay: <?= 0.05 * $index ?>s;">
                        <div class="icon-box">
                            <?= getIcon((string)$module['label']) ?>
                        </div>
                        <div class="card-details">
                            <span class="card-title"><?= e($module['label']) ?></span>
                            <span class="status-badge">Active</span>
                        </div>
                    </a>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <div class="empty-state">Access restricted or no modules available for your session.</div>
        <?php endif; ?>
    </div>

    <!-- Password Change Modal -->
    <?php if ($isAdmin): ?>
    <div class="modal-overlay" id="passModal">
        <div class="modal-content">
            <div class="modal-header">
                <h3>Update Credentials</h3>
                <button class="close-btn" onclick="closePassModal()">&times;</button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="update_admin_credentials">
                
                <div class="form-group">
                    <label>Username</label>
                    <input type="text" name="new_username" value="<?= e($username) ?>" required autocomplete="off">
                </div>
                
                <div class="form-group">
                    <label>Old Password</label>
                    <input type="password" name="old_password" required placeholder="Enter current password" autocomplete="off">
                </div>
                
                <div class="form-group">
                    <label>New Password</label>
                    <input type="password" name="new_password" required placeholder="Enter new password" autocomplete="off">
                </div>
                
                <button type="submit" class="submit-btn">Save Changes</button>
            </form>
        </div>
    </div>

    <script>
        function openPassModal() {
            document.getElementById('passModal').classList.add('active');
        }
        
        function closePassModal() {
            document.getElementById('passModal').classList.remove('active');
        }

        // Close modal when clicking outside
        document.getElementById('passModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closePassModal();
            }
        });
    </script>
    <?php endif; ?>

</body>
</html>