<?php
// =============================================================================
// page_header.php — opens the shared admin layout shell:
// sticky topbar + collapsible sidebar + main column.
//
// Pages should set:
//   $page_title          (string)  — browser title
//   $page_breadcrumb     (array)   — ['Module', 'Sub']  (Master Panel is prepended)
//   $page_heading        (string)  — h2 text in the page-header band
//   $page_heading_icon   (string)  — phosphor icon class (e.g. 'ph-squares-four')
//   $page_module_pill    (string)  — optional emerald pill text (e.g. 'IBO Ultra')
//   $page_active         (string)  — sidebar key: 'dashboard'|'services_clients'|...
//
// Then include this file and emit body content, finishing with page_footer.php.
// =============================================================================

require __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/auth.php';
auth_require_login();

$user = auth_user();
$initials = $user ? strtoupper(substr($user['username'], 0, 2)) : 'AD';
$active = isset($page_active) ? $page_active : '';
$title  = isset($page_title)  ? $page_title  : 'Master Panel';

// Default-password warning — shows on every page until the admin changes it.
// Cheapest possible "first-run installer" — buyers can't miss it.
$default_pw_active = false;
if ($user) {
    $row = db_one('SELECT password_hash FROM admin_users WHERE id = ?', [(int)$user['id']]);
    if ($row && password_verify(PANEL_DEFAULT_ADMIN_PASS, $row['password_hash'])) {
        $default_pw_active = true;
    }
}

// =============================================================================
// Sidebar — assembled from modules in `modules/*/module.php`.
//
//   1. Navigation        — Base panel pages (Dashboard / Store / Settings).
//   2..N                 — One section per module-declared `section` key.
//                          Modules contribute flat links or collapsible groups.
//
// To add a new module, drop a folder under `modules/` with a `module.php`
// returning a manifest (see includes/modules.php for the shape).
// =============================================================================
require_once __DIR__ . '/modules.php';

$nav_top = [
    ['key' => 'dashboard', 'href' => 'dashboard.php', 'icon' => 'ph-squares-four', 'label' => 'Dashboard'],
    ['key' => 'settings',  'href' => 'settings.php',  'icon' => 'ph-gear',         'label' => 'Settings'],
];

$sidebar = panel_sidebar();
?>
<!doctype html>
<html lang="en" style="background:#0a0a0a;color-scheme:dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="dark">
<meta name="theme-color" content="#0a0a0a">
<base href="<?php echo h(panel_base_path()); ?>">
<style>
/* Paint the dark background BEFORE Tailwind CDN finishes downloading,
   compiling, and applying its bg-dark-900 class. Without this, the browser
   shows white between navigation start and Tailwind apply — a noticeable
   flash on every page click. */
html,body{background:#0a0a0a;color:#e2e8f0;}
</style>
<title><?php echo h($title); ?> — Master Panel</title>
<link rel="icon" href="assets/images/favicon.ico" type="image/x-icon">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="assets/css/phosphor.css">
<link rel="stylesheet" href="assets/css/panel.css">
<link rel="stylesheet" href="assets/css/extra.css">
<script>
tailwind.config = {
    darkMode: 'class',
    theme: {
        extend: {
            colors: {
                primary: {50:'#fff8eb',100:'#ffefc6',200:'#ffdb88',300:'#ffc44a',400:'#f9a825',500:'#f39c12',600:'#d68910',700:'#b8760e',800:'#955f0b',900:'#7a4d0c'},
                dark:    {50:'#e2e8f0',100:'#ccc',200:'#aaa',300:'#999',400:'#777',500:'#666',600:'#2a2a2a',700:'#1e1e1e',800:'#161616',900:'#0a0a0a',950:'#111'}
            }
        }
    }
}
</script>
<meta name="csrf-token" content="<?php echo h(csrf_token()); ?>">

<!-- Load shared helpers (api/, toast(), escapeHtml(), confirmDanger()) BEFORE
     any page-specific inline scripts run. Synchronous on purpose so every
     body-level <script> can rely on `api` / `toast` being defined. -->
<script src="assets/js/app.js"></script>
</head>
<body class="min-h-screen" x-data="{ sidebarOpen: false }" x-cloak>

<!-- ============================ TOP HEADER ============================ -->
<header class="sticky top-0 z-50 bg-dark-900 border-b border-dark-700">
    <div class="flex items-center justify-between px-5 py-2.5">
        <div class="flex items-center gap-3">
            <button @click="sidebarOpen=!sidebarOpen" class="lg:hidden p-1.5 text-dark-400 hover:text-white hover:bg-dark-700 rounded-lg">
                <i class="ph ph-list text-xl"></i>
            </button>
            <a href="dashboard.php" class="flex items-center gap-2.5">
                <div class="h-8 w-8 bg-primary-500 rounded-lg flex items-center justify-center flex-shrink-0">
                    <span class="text-white font-bold text-sm">T</span>
                </div>
                <span class="text-sm font-bold text-primary-400 tracking-wider uppercase">Master Panel</span>
            </a>
        </div>
        <div class="flex items-center gap-1" x-data="{ profileOpen: false }" @click.outside="profileOpen=false">
            <a href="downloads.php" class="p-2 rounded-lg hover:bg-dark-700 transition-colors group" title="Downloads">
                <i class="ph ph-download-simple text-lg text-dark-400 group-hover:text-primary-400"></i>
            </a>
            <div class="w-px h-5 bg-dark-700 mx-1"></div>
            <a href="settings.php" class="p-2 rounded-lg hover:bg-dark-700 transition-colors group" title="Settings">
                <i class="ph ph-gear text-lg text-dark-400 group-hover:text-primary-400"></i>
            </a>
            <form method="post" action="logout.php" class="inline">
                <input type="hidden" name="_csrf" value="<?php echo h(csrf_token()); ?>">
                <button type="submit" class="p-2 rounded-lg hover:bg-dark-700 transition-colors group" title="Logout" style="background:transparent;border:0;cursor:pointer">
                    <i class="ph ph-sign-out text-lg text-dark-400 group-hover:text-red-400"></i>
                </button>
            </form>
            <div class="w-px h-5 bg-dark-700 mx-1"></div>
            <div class="relative">
                <button @click="profileOpen=!profileOpen" class="flex items-center gap-2 p-1.5 rounded-lg hover:bg-dark-700 transition-colors">
                    <div class="h-8 w-8 bg-primary-500/20 rounded-full flex items-center justify-center">
                        <span class="text-primary-400 font-semibold text-xs"><?php echo h($initials); ?></span>
                    </div>
                    <span class="text-sm text-dark-300 hidden sm:block"><?php echo h($user['username']); ?></span>
                </button>
                <div x-show="profileOpen" x-transition class="profile-dropdown" style="display:none">
                    <div class="px-4 py-3 border-b border-dark-700">
                        <p class="text-sm font-medium text-white"><?php echo h($user['username']); ?></p>
                        <p class="text-xs text-dark-400 capitalize"><?php echo h($user['role']); ?></p>
                    </div>
                    <a href="settings.php?tab=account"><i class="ph ph-user text-base"></i> Profile</a>
                    <a href="settings.php?tab=security"><i class="ph ph-shield-check text-base"></i> Security</a>
                    <div class="border-t border-dark-700">
                        <form method="post" action="logout.php">
                            <input type="hidden" name="_csrf" value="<?php echo h(csrf_token()); ?>">
                            <button type="submit" class="text-red-400 hover:!text-red-300 hover:!bg-red-500/10 w-full text-left flex items-center gap-2" style="background:transparent;border:0;cursor:pointer;padding:inherit;font:inherit">
                                <i class="ph ph-sign-out text-base"></i> Sign Out
                            </button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</header>

<div class="flex" style="height:calc(100vh - 45px);">
    <!-- Mobile overlay -->
    <div x-show="sidebarOpen" @click="sidebarOpen=false" class="fixed inset-0 bg-black/60 z-40 lg:hidden" x-transition style="display:none"></div>

    <!-- ============================ SIDEBAR (1:1 IBO GLASS) ============================ -->
    <aside class="fixed top-[45px] bottom-0 left-0 z-50 w-56 bg-dark-900 border-r border-dark-700 transform transition-transform duration-300 lg:translate-x-0 lg:static overflow-y-auto"
           :class="sidebarOpen ? 'translate-x-0' : '-translate-x-full'">
        <nav class="px-3 py-4 space-y-0.5">

            <!-- Section: Navigation -->
            <p class="px-3 mb-2 text-[10px] font-semibold text-dark-400 uppercase tracking-wider">Navigation</p>
            <?php foreach ($nav_top as $item): ?>
                <a href="<?php echo h($item['href']); ?>" class="sidebar-link <?php echo $active === $item['key'] ? 'active' : ''; ?>">
                    <i class="ph <?php echo h($item['icon']); ?> text-base"></i> <?php echo h($item['label']); ?>
                </a>
            <?php endforeach; ?>

            <?php foreach ($sidebar as $section_label => $entries):
                $keys = panel_sidebar_keys_in_section($entries);
                $section_active = in_array($active, $keys, true);
                $count = count($entries);
            ?>
            <div x-data="{ sectionOpen: <?php echo $section_active ? 'true' : 'false'; ?> }" class="mt-2">
                <button @click="sectionOpen=!sectionOpen" class="w-full flex items-center justify-between px-3 py-1.5 group cursor-pointer">
                    <span class="text-[10px] font-semibold text-dark-400 uppercase tracking-wider group-hover:text-dark-300 transition-colors"><?php echo h($section_label); ?></span>
                    <span class="flex items-center gap-1">
                        <span class="text-[9px] text-dark-600 font-medium"><?php echo $count; ?></span>
                        <i class="ph ph-caret-down text-[9px] text-dark-500 transition-transform duration-200" :class="sectionOpen ? 'rotate-180' : ''"></i>
                    </span>
                </button>
                <div x-show="sectionOpen" x-collapse class="space-y-0.5">
                    <?php foreach ($entries as $entry):
                        if ($entry['kind'] === 'flat'):
                            $p = $entry['page'];
                    ?>
                        <a href="<?php echo h($p['href']); ?>" class="sidebar-link <?php echo $active === ($p['key'] ?? '') ? 'active' : ''; ?>">
                            <?php if (!empty($p['image'])): ?>
                                <img src="assets/images/<?php echo h($p['image']); ?>" alt="" class="w-4 h-4 rounded flex-shrink-0" onerror="this.style.display='none';this.nextElementSibling.style.display='';">
                                <i class="ph <?php echo h($p['icon'] ?? 'ph-circle'); ?> text-base flex-shrink-0" style="display:none"></i>
                            <?php else: ?>
                                <i class="ph <?php echo h($p['icon'] ?? 'ph-circle'); ?> text-base flex-shrink-0"></i>
                            <?php endif; ?>
                            <span class="truncate"><?php echo h($p['label']); ?></span>
                        </a>
                    <?php else:
                            $parent = $entry['parent'];
                            $group_active = false;
                            foreach ($entry['pages'] as $pp) {
                                if (!empty($pp['key']) && $pp['key'] === $active) { $group_active = true; break; }
                            }
                    ?>
                        <div x-data="{ open: <?php echo $group_active ? 'true' : 'false'; ?> }">
                            <button @click="open=!open" class="sidebar-link w-full justify-between">
                                <span class="flex items-center gap-2 min-w-0">
                                    <?php if (!empty($parent['image'])): ?>
                                        <img src="assets/images/<?php echo h($parent['image']); ?>" alt="" class="w-4 h-4 rounded flex-shrink-0" onerror="this.style.display='none';this.nextElementSibling.style.display='';">
                                        <i class="ph <?php echo h($parent['icon'] ?? 'ph-circle'); ?> text-base flex-shrink-0" style="display:none"></i>
                                    <?php else: ?>
                                        <i class="ph <?php echo h($parent['icon'] ?? 'ph-circle'); ?> text-base flex-shrink-0"></i>
                                    <?php endif; ?>
                                    <span class="truncate"><?php echo h($parent['label']); ?></span>
                                </span>
                                <i class="ph ph-caret-down text-[10px] flex-shrink-0 transition-transform duration-200" :class="open ? 'rotate-180' : ''"></i>
                            </button>
                            <div x-show="open" x-collapse class="sidebar-dropdown">
                                <?php foreach ($entry['pages'] as $pp): ?>
                                    <a href="<?php echo h($pp['href']); ?>" class="sidebar-sublink <?php echo $active === ($pp['key'] ?? '') ? 'active' : ''; ?>">
                                        <?php echo h($pp['label']); ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endif; endforeach; ?>
                </div>
            </div>
            <?php endforeach; ?>
        </nav>
    </aside>

    <!-- ============================ MAIN ============================ -->
    <main class="flex-1 min-w-0 flex flex-col overflow-y-auto">
        <?php if ($default_pw_active && $active !== 'settings'): ?>
        <div class="mx-6 mt-4 mb-0 p-3 rounded-lg border border-amber-500/40 bg-amber-500/10 text-amber-200 text-sm flex items-center gap-3">
            <i class="ph ph-warning text-xl"></i>
            <div class="flex-1">
                <p class="font-semibold">Your admin account is still using the default password.</p>
                <p class="text-xs text-amber-300/80">Anyone with this URL can log in as you. Change it now to secure your panel.</p>
            </div>
            <a href="settings.php" class="px-3 py-1.5 rounded-md bg-amber-500 hover:bg-amber-400 text-amber-950 text-xs font-semibold whitespace-nowrap">
                Change password
            </a>
        </div>
        <?php endif; ?>
        <div class="p-6 fade-in flex-1">
            <?php if (!empty($page_heading)): ?>
                <div class="page-header">
                    <?php if (!empty($page_breadcrumb)): ?>
                        <p class="text-xs font-semibold text-primary-400 uppercase tracking-wider mb-1">
                            <span class="text-dark-400">Master Panel</span>
                            <?php foreach ($page_breadcrumb as $crumb): ?>
                                / <?php echo h($crumb); ?>
                            <?php endforeach; ?>
                        </p>
                    <?php endif; ?>
                    <div class="flex items-center justify-between gap-3">
                        <h2 class="text-2xl font-bold text-white flex items-center gap-3">
                            <?php if (!empty($page_heading_icon)): ?>
                                <i class="ph <?php echo h($page_heading_icon); ?> text-primary-400"></i>
                            <?php endif; ?>
                            <?php echo h($page_heading); ?>
                        </h2>
                        <?php if (!empty($page_module_pill)): ?>
                            <span class="px-3 py-1 bg-emerald-500/15 text-emerald-400 border border-emerald-500/30 rounded-full text-xs font-semibold">
                                <?php echo h($page_module_pill); ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endif; ?>
<!-- ============================ PAGE CONTENT BELOW ============================ -->
