<?php
/* ============================================================================
   WBMCZ — Shared premium panel layout (Navy + Gold)
   Used by every customer (root) and seller (/seller) page.

   Usage in a page:
     require_once __DIR__ . '/includes/theme.php';   // '/../includes/theme.php' in /seller
     ... (page logic, $user, $wallet_balance, $unread_notifs ...)
     theme_open([
        'panel'   => 'user',           // 'user' | 'seller'
        'base'    => '',               // '' for root pages, '../' inside /seller
        'title'   => 'Dashboard',
        'active'  => 'dashboard',
        'user'    => $user,
        'wallet'  => $wallet_balance,
        'notifs'  => $unread_notifs,
        'logo'    => $company_logo,
        'brand'   => $company_name,
        'menu'    => [...],            // see theme_user_menu() / theme_seller_menu()
        'state'   => 'someModal: false',// extra Alpine state (optional)
     ]);
     ... page <main> content ...
     theme_close();
   ============================================================================ */

require_once __DIR__ . '/notify.php';

/* ---------- Design tokens + premium component CSS ---------- */
function theme_styles() {
    ?>
    <style>
        :root{
            --navy-900:#070D24; --navy-800:#0B1437; --navy-700:#111C44; --navy-600:#1B2559;
            --gold-400:#F5C451; --gold-500:#E3AE33; --gold-600:#C8901B;
            --ink:#0F172A; --muted:#64748B; --line:#E6E9F0; --canvas:#F5F7FB;
        }
        body{font-family:'Inter',sans-serif;background:var(--canvas);color:var(--ink);}
        .hide-scrollbar::-webkit-scrollbar{display:none;} .hide-scrollbar{-ms-overflow-style:none;scrollbar-width:none;}
        [x-cloak]{display:none!important;}

        /* Sidebar */
        .tp-aside{background:linear-gradient(180deg,var(--navy-800) 0%,var(--navy-900) 100%);}
        .tp-nav-link{display:flex;align-items:center;border-radius:.7rem;padding:.58rem .7rem;color:#AEB9D4;font-size:.8rem;font-weight:600;transition:all .2s;position:relative;}
        .tp-nav-link:hover{background:rgba(255,255,255,.06);color:#fff;}
        .tp-nav-link.is-active{background:linear-gradient(90deg,rgba(245,196,81,.18),rgba(245,196,81,.04));color:#fff;}
        .tp-nav-link.is-active::before{content:"";position:absolute;left:-12px;top:50%;transform:translateY(-50%);width:4px;height:60%;border-radius:0 4px 4px 0;background:var(--gold-400);}
        .tp-sub-link{display:flex;align-items:center;gap:.5rem;padding:.38rem .55rem;border-radius:.55rem;font-size:.755rem;color:#94A3C4;transition:all .2s;}
        .tp-sub-link:hover{background:rgba(255,255,255,.07);color:#fff;}
        .tp-sub-link.is-active{background:rgba(245,196,81,.16);color:#FFF3D4;font-weight:700;}
        .tp-group{font-size:9.5px;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:rgba(174,185,212,.45);padding:.85rem .75rem .3rem;margin:0;}
        .tp-group:first-child{padding-top:.15rem;}
        .tp-group-dash{height:1px;background:rgba(255,255,255,.09);margin:.6rem .4rem;}
        .tp-scroll::-webkit-scrollbar{width:5px;} .tp-scroll::-webkit-scrollbar-thumb{background:rgba(255,255,255,.15);border-radius:9999px;}

        /* Header */
        .tp-header{background:rgba(255,255,255,.85);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);border-bottom:1px solid var(--line);}
        .tp-icon-btn{width:2.5rem;height:2.5rem;display:flex;align-items:center;justify-content:center;border-radius:.75rem;color:var(--muted);transition:all .2s;}
        .tp-icon-btn:hover{background:#EEF1F7;color:var(--ink);}
        .tp-wallet{display:flex;align-items:center;gap:.6rem;padding:.35rem .35rem .35rem .9rem;border-radius:9999px;background:linear-gradient(135deg,var(--navy-800),var(--navy-600));color:#fff;box-shadow:0 6px 18px -8px rgba(11,20,55,.7);transition:transform .2s;}
        .tp-wallet:hover{transform:translateY(-1px);}
        .tp-wallet-plus{width:2rem;height:2rem;border-radius:9999px;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg,var(--gold-400),var(--gold-600));color:#3B2A05;font-weight:700;}

        /* Cards & bits */
        .tp-card{background:#fff;border:1px solid var(--line);border-radius:1rem;box-shadow:0 1px 2px rgba(16,24,40,.04);}
        .tp-card-hover{transition:transform .2s,box-shadow .2s;}
        .tp-card-hover:hover{transform:translateY(-3px);box-shadow:0 16px 32px -18px rgba(16,24,40,.35);}
        .tp-stat{position:relative;overflow:hidden;border-radius:1rem;padding:1.25rem;color:#fff;background:linear-gradient(135deg,var(--navy-700),var(--navy-900));}
        .tp-stat::after{content:"";position:absolute;right:-2rem;top:-2rem;width:8rem;height:8rem;border-radius:9999px;background:rgba(245,196,81,.16);filter:blur(28px);}
        .tp-stat-gold{background:linear-gradient(135deg,var(--gold-400),var(--gold-600));color:#3B2A05;}
        .tp-chip{display:inline-flex;align-items:center;gap:.35rem;padding:.15rem .6rem;border-radius:9999px;font-size:.65rem;font-weight:700;text-transform:uppercase;letter-spacing:.03em;}
        .tp-btn-gold{background:linear-gradient(135deg,var(--gold-400),var(--gold-600));color:#3B2A05;font-weight:700;border-radius:.75rem;padding:.7rem 1.2rem;box-shadow:0 10px 22px -12px rgba(200,144,27,.9);transition:transform .2s;}
        .tp-btn-gold:hover{transform:translateY(-2px);}
        .tp-title{font-family:'Poppins',sans-serif;font-weight:800;letter-spacing:-.01em;}

        /* Category tiles — clean professional card grid */
        .cat-tile{position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;
            background:#fff;border:1px solid var(--line);border-radius:1rem;padding:1.25rem .75rem;min-height:140px;
            box-shadow:0 1px 2px rgba(16,24,40,.04);transition:transform .22s ease,box-shadow .22s ease,border-color .22s ease;overflow:hidden;}
        .cat-tile::after{content:"";position:absolute;left:0;right:0;top:0;height:3px;background:linear-gradient(90deg,var(--gold-400),var(--gold-600));opacity:0;transition:opacity .22s;}
        .cat-tile:hover{transform:translateY(-4px);box-shadow:0 18px 30px -18px rgba(16,24,40,.35);border-color:#D8DEEA;}
        .cat-tile:hover::after{opacity:1;}
        .cat-tile-icon{width:54px;height:54px;border-radius:1rem;display:flex;align-items:center;justify-content:center;
            color:#fff;font-size:1.35rem;margin-bottom:.75rem;box-shadow:0 10px 20px -10px rgba(16,24,40,.55);transition:transform .22s;}
        .cat-tile:hover .cat-tile-icon{transform:scale(1.08);}
        .cat-tile-text{font-family:'Poppins',sans-serif;font-weight:700;font-size:.8rem;color:var(--ink);line-height:1.25;
            display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;}
        .cat-tile-arrow{position:absolute;right:.6rem;bottom:.6rem;width:22px;height:22px;border-radius:9999px;display:flex;align-items:center;
            justify-content:center;font-size:.6rem;color:#94A3B8;background:#F1F5F9;opacity:0;transform:translateX(-4px);transition:all .22s;}
        .cat-tile:hover .cat-tile-arrow{opacity:1;transform:translateX(0);color:var(--gold-600);background:#FFF6E0;}
        .cat-tile.is-locked{opacity:.6;}
        @media (min-width:640px){ .cat-tile{min-height:160px;padding:1.5rem 1rem;} .cat-tile-icon{width:60px;height:60px;font-size:1.5rem;} .cat-tile-text{font-size:.875rem;} }

        /* ===== SQUARE UNIFORM TILES — services + reports use the SAME box =====
           aspect-ratio 1/1 guarantees identical size in every condition.       */
        .tile-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(112px,1fr));gap:.6rem;}
        @media (min-width:640px){ .tile-grid{grid-template-columns:repeat(auto-fill,minmax(132px,1fr));gap:.75rem;} }
        .sq-tile{
            position:relative;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;
            aspect-ratio:1/1;width:100%;padding:.55rem .4rem;overflow:hidden;
            background:#fff;border:1px solid var(--line);border-radius:.9rem;
            box-shadow:0 1px 2px rgba(16,24,40,.05);
            transition:transform .2s ease,box-shadow .2s ease,border-color .2s ease;
        }
        .sq-tile::after{content:"";position:absolute;left:0;right:0;top:0;height:3px;
            background:linear-gradient(90deg,var(--gold-400),var(--gold-600));opacity:0;transition:opacity .2s;}
        .sq-tile:hover{transform:translateY(-3px);box-shadow:0 14px 26px -16px rgba(16,24,40,.4);border-color:#D8DEEA;}
        .sq-tile:hover::after{opacity:1;}
        .sq-ico{width:38px;height:38px;border-radius:.75rem;display:flex;align-items:center;justify-content:center;
            color:#fff;font-size:.95rem;margin-bottom:.4rem;flex-shrink:0;box-shadow:0 8px 16px -9px rgba(16,24,40,.6);}
        .sq-val{font-family:'Poppins',sans-serif;font-weight:800;font-size:1.05rem;line-height:1;color:var(--ink);}
        .sq-lbl{font-weight:700;font-size:.62rem;line-height:1.2;color:var(--muted);margin-top:.22rem;
            display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;width:100%;padding:0 .1rem;}
        .sq-tile .sq-title{font-family:'Poppins',sans-serif;font-weight:700;font-size:.68rem;line-height:1.2;color:var(--ink);
            display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;width:100%;padding:0 .1rem;}
        .sq-pill{margin-top:.28rem;font-size:.53rem;font-weight:800;letter-spacing:.04em;text-transform:uppercase;
            padding:.1rem .4rem;border-radius:999px;white-space:nowrap;}
        .sq-tile.is-locked{opacity:.55;}
        @media (min-width:640px){
            .sq-ico{width:44px;height:44px;font-size:1.1rem;}
            .sq-val{font-size:1.3rem;} .sq-lbl{font-size:.68rem;} .sq-tile .sq-title{font-size:.76rem;}
        }

        /* Language button */
        .tp-lang-btn{display:flex;align-items:center;gap:.45rem;height:2.5rem;padding:0 .7rem;border-radius:.75rem;
            background:#EEF1F7;color:#334155;font-size:.78rem;font-weight:700;transition:all .2s;}
        .tp-lang-btn:hover{background:#E2E8F0;color:var(--ink);}

        @media (max-width:767px){
            .tp-header{position:sticky;top:0;z-index:40;}
        }
    </style>
    <?php
}

/* ---------- Default menus ---------- */

/* ============================================================================
   MEMBER MENU — exact order requested:
   Dashboard · Profile · Wallet · Earning Report · Services · Order History
   · My Subscription · Refer & Earn · Helpdesk
   ============================================================================ */
/* $root = '' from the site root, '../' from inside /seller.
   profile.php is panel-local, my_commission.php lives at the site root. */
function theme_profile_children($root = '') {
    /* Single source of truth — the sidebar "Profile" menu AND the top-right
       avatar dropdown both render exactly these links, so they never drift. */
    return [
        ['label' => 'My Profile',      'icon' => 'fa-id-badge',    'href' => 'profile.php#profile'],
        ['label' => 'Edit Profile',    'icon' => 'fa-user-pen',    'href' => 'profile.php#edit'],
        ['label' => 'KYC',             'icon' => 'fa-id-card',     'href' => 'profile.php#kyc'],
        ['label' => 'Extra Information','icon' => 'fa-list-check',  'href' => $root . 'kyc_extra.php'],
        ['label' => 'My ID Card',      'icon' => 'fa-id-badge',    'href' => 'profile.php#id_card'],
        ['label' => 'Certificate',     'icon' => 'fa-certificate', 'href' => 'profile.php#certificate'],
        ['label' => 'My Commission',   'icon' => 'fa-hand-holding-dollar', 'href' => $root . 'my_commission.php'],
        ['label' => 'Change Password', 'icon' => 'fa-lock',        'href' => 'profile.php#password'],
    ];
}

function theme_user_menu($subcats = [], $categories = []) {
    /* Services: FLAT list only — no sub-categories in the sidebar. */
    $svc_children = [];
    foreach ($categories as $c) {
        if (!in_array($c['id'], [1, 5])) continue;
        $svc_children[] = ['label' => $c['title'], 'icon' => $c['icon_class'], 'href' => 'category.php?id=' . $c['id']];
    }

    return [
        ['label' => 'Dashboard',       'icon' => 'fa-gauge-high',    'href' => 'dashboard.php', 'key' => 'dashboard'],

        ['label' => 'Profile',         'icon' => 'fa-user-tie',      'key' => 'profile',
            'children' => theme_profile_children('')],

        ['label' => 'Wallet',          'icon' => 'fa-wallet',        'key' => 'wallet', 'children' => [
            ['label' => 'Add Money',       'icon' => 'fa-plus',              'href' => 'wallet.php#add_money'],
            ['label' => 'Main Wallet',     'icon' => 'fa-wallet',            'href' => 'wallet.php#history'],
            ['label' => 'Virtual Wallet',  'icon' => 'fa-gift',              'href' => 'wallet.php#virtual'],
            ['label' => 'Wallet History',  'icon' => 'fa-clock-rotate-left', 'href' => 'wallet.php#wallet_history'],
            ['label' => 'Wallet to Bank',  'icon' => 'fa-building-columns',  'href' => 'wallet.php#to_bank'],
        ]],

        ['label' => 'Earning Report',  'icon' => 'fa-chart-line',    'href' => 'earning_report.php', 'key' => 'earning'],
        ['label' => 'Services',        'icon' => 'fa-bag-shopping',  'key' => 'services', 'children' => $svc_children],
        ['label' => 'My Cart',         'icon' => 'fa-basket-shopping','href' => 'cart.php', 'key' => 'cart'],
        ['label' => 'Order History',   'icon' => 'fa-box',           'href' => 'orders.php', 'key' => 'orders'],
        ['label' => 'My Subscription', 'icon' => 'fa-crown',         'href' => 'subscription.php', 'key' => 'subscription'],
        ['label' => 'Refer & Earn',    'icon' => 'fa-gift',          'href' => 'refer.php', 'key' => 'refer'],
        ['label' => 'Seller Request',  'icon' => 'fa-store',         'href' => 'upgrade_request.php', 'key' => 'seller_request'],
        ['label' => 'Helpdesk',        'icon' => 'fa-headset',       'href' => 'helpdesk.php', 'key' => 'helpdesk'],
    ];
}

/* ============================================================================
   SELLER MENU — exact order requested:
   Dashboard · Profile · Wallet · Earning Report · Services · Order History
   · My Service · Customer Orders · Sell Report · My Subscription
   · Refer & Earn · Helpdesk

   "Services" and "Order History" are the seller shopping as a customer
   (root pages), while "My Service" and "Customer Orders" are their own
   business pages inside /seller.
   ============================================================================ */
function theme_seller_menu($assigned_cats = []) {
    $svc_kids = []; $ord_kids = []; $buy_kids = [];
    foreach ($assigned_cats as $c) {
        $svc_kids[] = ['label' => $c['title'], 'icon' => $c['icon_class'] ?: 'fa-angle-right', 'href' => 'services.php?cat_id=' . $c['id']];
        $ord_kids[] = ['label' => $c['title'], 'icon' => $c['icon_class'] ?: 'fa-angle-right', 'href' => 'orders.php?cat_id=' . $c['id']];
        if (in_array($c['id'], [1, 5])) {
            $buy_kids[] = ['label' => $c['title'], 'icon' => $c['icon_class'] ?: 'fa-angle-right', 'href' => '../category.php?id=' . $c['id']];
        }
    }
    // Sellers can always browse the two public catalogues
    if (empty($buy_kids)) {
        $buy_kids = [
            ['label' => 'Government Portals', 'icon' => 'fa-landmark',    'href' => '../category.php?id=1'],
            ['label' => 'Agency & Software',  'icon' => 'fa-laptop-code', 'href' => '../category.php?id=5'],
        ];
    }

    return [
        ['label' => 'Dashboard',       'icon' => 'fa-gauge-high',    'href' => 'index.php', 'key' => 'dashboard'],

        ['label' => 'Profile',         'icon' => 'fa-user-tie',      'key' => 'profile',
            'children' => array_merge(
                [['label' => 'Business Info', 'icon' => 'fa-store', 'href' => 'profile.php#business']],
                theme_profile_children('../')
            )],

        ['label' => 'Wallet',          'icon' => 'fa-wallet',        'key' => 'wallet', 'children' => [
            ['label' => 'Add Money',      'icon' => 'fa-plus',              'href' => 'wallet.php#add_money'],
            ['label' => 'Main Wallet',    'icon' => 'fa-wallet',            'href' => 'wallet.php#history'],
            ['label' => 'Virtual Wallet', 'icon' => 'fa-gift',              'href' => 'wallet.php#virtual'],
            ['label' => 'Wallet History', 'icon' => 'fa-clock-rotate-left', 'href' => 'wallet.php#wallet_history'],
            ['label' => 'Wallet to Bank', 'icon' => 'fa-building-columns',  'href' => 'wallet.php#to_bank'],
        ]],

        ['label' => 'Earning Report',  'icon' => 'fa-chart-line',    'href' => 'earning_report.php', 'key' => 'earning'],
        ['label' => 'Services',        'icon' => 'fa-bag-shopping',  'key' => 'buy', 'children' => $buy_kids],
        ['label' => 'Order History',   'icon' => 'fa-box',           'href' => '../orders.php', 'key' => 'myorders'],

        ['label' => 'My Service',      'icon' => 'fa-screwdriver-wrench', 'key' => 'services', 'children' => array_merge(
            [
                ['label' => 'All Services', 'icon' => 'fa-list', 'href' => 'services.php'],
                ['label' => 'Bulk Upload',  'icon' => 'fa-file-import', 'href' => 'service_import.php'],
            ], $svc_kids)],
        ['label' => 'Customer Orders', 'icon' => 'fa-users',         'key' => 'orders', 'children' => array_merge(
            [['label' => 'All Orders', 'icon' => 'fa-list', 'href' => 'orders.php']], $ord_kids)],
        ['label' => 'Visits & Money',  'icon' => 'fa-person-walking', 'key' => 'collections', 'children' => [
            ['label' => 'To collect',      'icon' => 'fa-sack-dollar',    'href' => 'collections.php?tab=collect'],
            ['label' => 'What I reported', 'icon' => 'fa-receipt',        'href' => 'collections.php?tab=reported'],
            ['label' => 'My dues',         'icon' => 'fa-scale-balanced', 'href' => 'collections.php?tab=dues'],
        ]],
        ['label' => 'Sell Report',     'icon' => 'fa-chart-simple',  'href' => 'reports.php', 'key' => 'reports'],

        ['label' => 'My Subscription', 'icon' => 'fa-crown',         'href' => '../subscription.php', 'key' => 'subscription'],
        ['label' => 'Refer & Earn',    'icon' => 'fa-gift',          'href' => '../refer.php', 'key' => 'refer'],
        ['label' => 'Helpdesk',        'icon' => 'fa-headset',       'href' => 'helpdesk.php', 'key' => 'helpdesk'],
    ];
}

/* ---------- Sidebar ---------- */
function theme_sidebar($cfg) {
    $menu   = $cfg['menu'] ?? [];
    $active = $cfg['active'] ?? '';
    $base   = $cfg['base'] ?? '';
    $logo   = $cfg['logo'] ?? ($base . 'assets/images/logo.png');
    $brand  = $cfg['brand'] ?? 'WBMCZ';
    $panel  = $cfg['panel'] ?? 'user';
    ?>
    <aside x-cloak
           :class="sidebarOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0 md:w-[76px]'"
           class="tp-aside fixed md:relative inset-y-0 left-0 z-50 w-[270px] md:w-64 text-white flex flex-col shadow-2xl transition-all duration-300 ease-in-out">

        <div class="flex items-center h-[68px] px-4 border-b border-white/10" :class="sidebarOpen ? 'justify-between' : 'md:justify-center'">
            <a href="<?php echo $panel === 'seller' ? 'index.php' : 'dashboard.php'; ?>" class="flex items-center gap-2.5 min-w-0">
                <img src="<?php echo htmlspecialchars($logo); ?>" alt="" class="h-9 w-9 rounded-lg bg-white object-contain p-1 flex-shrink-0">
                <div x-show="sidebarOpen" class="min-w-0">
                    <p class="tp-title text-[15px] leading-tight truncate"><?php echo htmlspecialchars($brand); ?></p>
                    <p class="text-[10px] uppercase tracking-[.18em] text-[#F5C451] font-bold"><?php echo $panel === 'seller' ? 'Seller' : 'Member'; ?></p>
                </div>
            </a>
            <button @click="sidebarOpen = false" class="md:hidden text-white/60 hover:text-white p-1"><i class="fas fa-xmark text-lg"></i></button>
        </div>

        <?php /* open: '' — every submenu starts CLOSED. Click a parent to open it. */ ?>
        <nav class="flex-1 overflow-y-auto tp-scroll px-3 py-3 space-y-0.5" x-data="{ open: '' }">
            <?php $__grp = null; foreach ($menu as $item):
                $has_kids = !empty($item['children']);
                $is_act   = (!empty($item['key']) && $item['key'] === $active);
                $__key    = $item['key'] ?? ($item['label'] ?? '');
            ?>
                <?php if (!empty($item['group']) && $item['group'] !== $__grp): $__grp = $item['group']; ?>
                    <p x-show="sidebarOpen" class="tp-group"><?php echo htmlspecialchars($__grp); ?></p>
                    <div x-show="!sidebarOpen" class="tp-group-dash"></div>
                <?php endif; ?>
                <?php if (!$has_kids): ?>
                    <a href="<?php echo htmlspecialchars($item['href']); ?>" class="tp-nav-link <?php echo $is_act ? 'is-active' : ''; ?>" :class="sidebarOpen ? '' : 'md:justify-center'">
                        <i class="fas <?php echo htmlspecialchars($item['icon']); ?> flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-lg'"></i>
                        <span x-show="sidebarOpen" class="ml-3 whitespace-nowrap"><?php echo htmlspecialchars($item['label']); ?></span>
                    </a>
                <?php else: ?>
                    <div>
                        <button @click="open = (open === '<?php echo htmlspecialchars($__key); ?>' ? '' : '<?php echo htmlspecialchars($__key); ?>'); sidebarOpen = true"
                                class="tp-nav-link w-full justify-between <?php echo $is_act ? 'is-active' : ''; ?>" :class="sidebarOpen ? '' : 'md:justify-center'">
                            <span class="flex items-center min-w-0">
                                <i class="fas <?php echo htmlspecialchars($item['icon']); ?> flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-lg'"></i>
                                <span x-show="sidebarOpen" class="ml-3 whitespace-nowrap"><?php echo htmlspecialchars($item['label']); ?></span>
                            </span>
                            <i x-show="sidebarOpen" class="fas fa-chevron-down text-[10px] transition-transform" :class="open === '<?php echo htmlspecialchars($__key); ?>' ? 'rotate-180' : ''"></i>
                        </button>
                        <div x-show="open === '<?php echo htmlspecialchars($__key); ?>' && sidebarOpen" x-collapse.duration.200ms x-transition class="mt-0.5 ml-4 pl-3 border-l border-white/10 space-y-0.5 pb-1">
                            <?php foreach ($item['children'] as $kid):
                                $kid_kids = !empty($kid['children']); ?>
                                <?php if (!$kid_kids): ?>
                                    <a href="<?php echo htmlspecialchars($kid['href']); ?>" class="tp-sub-link">
                                        <i class="fas <?php echo htmlspecialchars($kid['icon'] ?? 'fa-angle-right'); ?> w-4 text-center text-[11px]"></i>
                                        <span class="truncate"><?php echo htmlspecialchars($kid['label']); ?></span>
                                    </a>
                                <?php else: ?>
                                    <div x-data="{ o2: false }">
                                        <button @click="o2 = !o2" class="tp-sub-link w-full justify-between">
                                            <span class="flex items-center gap-2 min-w-0">
                                                <i class="fas <?php echo htmlspecialchars($kid['icon'] ?? 'fa-angle-right'); ?> w-4 text-center text-[11px]"></i>
                                                <span class="truncate"><?php echo htmlspecialchars($kid['label']); ?></span>
                                            </span>
                                            <i class="fas fa-chevron-down text-[9px] transition-transform" :class="o2 ? 'rotate-180' : ''"></i>
                                        </button>
                                        <div x-show="o2" x-transition class="ml-4 pl-2 border-l border-white/10 space-y-0.5 mt-0.5">
                                            <?php foreach ($kid['children'] as $g): ?>
                                                <a href="<?php echo htmlspecialchars($g['href']); ?>" class="tp-sub-link text-[12px]">
                                                    <i class="fas <?php echo htmlspecialchars($g['icon'] ?? 'fa-angle-right'); ?> w-4 text-center text-[10px]"></i>
                                                    <span class="truncate"><?php echo htmlspecialchars($g['label']); ?></span>
                                                </a>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>
            <?php endforeach; ?>
        </nav>

        <div class="p-3 border-t border-white/10">
            <a href="<?php echo $base; ?>logout.php" onclick="return confirm('Are you sure you want to logout?');"
               class="tp-nav-link text-rose-300 hover:bg-rose-500/15 hover:text-rose-100" :class="sidebarOpen ? '' : 'md:justify-center'">
                <i class="fas fa-right-from-bracket flex-shrink-0" :class="sidebarOpen ? 'w-6 text-center' : 'text-lg'"></i>
                <span x-show="sidebarOpen" class="ml-3">Logout</span>
            </a>
        </div>
    </aside>
    <?php
}

/* ---------- Header ---------- */
/* ---------- Languages available for the panel switcher ---------- */
function theme_languages() {
    static $cache = null;
    if ($cache !== null) return $cache;
    global $db;
    $cache = [];
    try {
        if (isset($db)) {
            $cache = $db->select("SELECT code, name FROM languages WHERE status = 1 ORDER BY is_default DESC, name ASC");
        }
    } catch (\Throwable $e) { $cache = []; }
    if (empty($cache)) {
        $cache = [['code' => 'bn', 'name' => 'বাংলা'], ['code' => 'en', 'name' => 'English'], ['code' => 'hi', 'name' => 'हिन्दी']];
    }
    return $cache;
}

/* Current page URL with ?lang=xx merged in (keeps every other query param) */
function theme_lang_url($code) {
    $parts = parse_url($_SERVER['REQUEST_URI'] ?? '');
    $path  = $parts['path'] ?? '';
    $q     = [];
    if (!empty($parts['query'])) { parse_str($parts['query'], $q); }
    $q['lang'] = $code;
    return $path . '?' . http_build_query($q);
}

function theme_header($cfg) {
    $base   = $cfg['base'] ?? '';
    $title  = $cfg['title'] ?? '';
    $user   = $cfg['user'] ?? ['name' => 'User', 'mobile' => ''];
    $wallet = $cfg['wallet'] ?? 0;
    $notifs = $cfg['notifs'] ?? [];
    $count  = count($notifs);
    $pic    = !empty($user['profile_pic']) ? $base . 'uploads/profiles/' . $user['profile_pic'] : '';
    $has_pic = $pic && file_exists($pic);

    $langs    = theme_languages();
    $cur_lang = $_SESSION['lang'] ?? ($langs[0]['code'] ?? 'bn');
    $cur_name = $cur_lang;
    foreach ($langs as $l) { if ($l['code'] === $cur_lang) { $cur_name = $l['name']; break; } }

    /* The avatar dropdown shows EXACTLY the sidebar "Profile" items. */
    $prof_links = [];
    foreach (($cfg['menu'] ?? []) as $m) {
        if (($m['key'] ?? '') === 'profile' && !empty($m['children'])) { $prof_links = $m['children']; break; }
    }
    if (empty($prof_links)) { $prof_links = theme_profile_children($base); }
    ?>
    <header class="tp-header h-[68px] flex items-center gap-3 px-3 sm:px-5 lg:px-7 flex-shrink-0 relative z-40">
        <button @click="sidebarOpen = !sidebarOpen" class="tp-icon-btn flex-shrink-0"><i class="fas fa-bars text-lg"></i></button>

        <h1 class="tp-title text-base sm:text-lg truncate min-w-0 flex-1"><?php echo htmlspecialchars($title); ?></h1>

        <div class="flex items-center gap-2 sm:gap-3 flex-shrink-0">

            <!-- ===== Language switcher ===== -->
            <div class="relative">
                <button @click="langOpen = !langOpen" @click.away="langOpen = false" class="tp-lang-btn" title="Change language">
                    <i class="fas fa-globe"></i>
                    <span class="hidden sm:inline"><?php echo htmlspecialchars($cur_name); ?></span>
                    <i class="fas fa-chevron-down text-[9px] opacity-60"></i>
                </button>
                <div x-show="langOpen" x-cloak x-transition class="absolute right-0 mt-2 w-44 tp-card shadow-2xl py-1.5 z-50">
                    <p class="px-4 pb-1.5 text-[10px] uppercase tracking-wider text-slate-400 font-bold">Language</p>
                    <?php foreach ($langs as $l): $on = ($l['code'] === $cur_lang); ?>
                        <a href="<?php echo htmlspecialchars(theme_lang_url($l['code'])); ?>"
                           class="flex items-center justify-between px-4 py-2 text-sm hover:bg-slate-50 <?php echo $on ? 'font-bold text-[#C8901B]' : 'text-slate-600'; ?>">
                            <span><?php echo htmlspecialchars($l['name']); ?></span>
                            <?php if ($on): ?><i class="fas fa-check text-[10px]"></i><?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </div>

            <?php
            /* The basket. Only where it means anything — a customer or a seller
               shopping as one — and only once the cart engine is loaded, so no
               page can break over it. */
            $__cart_n = 0;
            if (function_exists('cart_count') && !empty($_SESSION['user_id'])) {
                $__cart_n = (int)cart_count($GLOBALS['db'], (int)$_SESSION['user_id']);
            }
            ?>
            <a href="<?php echo $base; ?>cart.php" class="tp-icon-btn relative" title="My cart">
                <i class="fas fa-basket-shopping text-lg"></i>
                <?php if ($__cart_n > 0): ?>
                    <span class="absolute top-1 right-1 min-w-[16px] h-4 px-1 bg-[#C8901B] rounded-full flex items-center justify-center text-[9px] font-bold text-[#14202f]"><?php echo $__cart_n > 9 ? '9+' : $__cart_n; ?></span>
                <?php endif; ?>
            </a>

            <a href="<?php echo $base; ?>wallet.php" class="tp-wallet">
                <span class="flex flex-col leading-none text-right">
                    <span class="text-[9px] uppercase tracking-wider text-white/60 font-bold hidden sm:block">Wallet</span>
                    <span class="text-[13px] sm:text-sm font-extrabold whitespace-nowrap">₹<?php echo number_format((float)$wallet, 2); ?></span>
                </span>
                <span class="tp-wallet-plus"><i class="fas fa-plus text-xs"></i></span>
            </a>

            <div class="relative">
                <button @click="notifOpen = !notifOpen" @click.away="notifOpen = false" class="tp-icon-btn relative">
                    <i class="fas fa-bell text-lg"></i>
                    <?php if ($count > 0): ?>
                        <span class="absolute top-1 right-1 min-w-[16px] h-4 px-1 bg-rose-500 rounded-full flex items-center justify-center text-[9px] font-bold text-white"><?php echo $count; ?></span>
                    <?php endif; ?>
                </button>
                <div x-show="notifOpen" x-cloak x-transition class="absolute right-0 mt-2 w-[290px] sm:w-80 tp-card shadow-2xl overflow-hidden z-50">
                    <div class="px-4 py-3 border-b border-slate-100 flex items-center justify-between bg-slate-50">
                        <p class="font-bold text-sm">Notifications</p>
                        <?php if ($count > 0): ?>
                            <form method="POST" action="<?php echo $base; ?>notifications.php" class="m-0">
                                <button type="submit" name="mark_all_read" class="text-xs font-bold text-[#C8901B] hover:underline">Mark all read</button>
                            </form>
                        <?php endif; ?>
                    </div>
                    <div class="max-h-72 overflow-y-auto">
                        <?php if ($count > 0): foreach ($notifs as $n):
                            $nm = function_exists('notify_meta') ? notify_meta($n['type'] ?? 'general') : ['General','slate','fa-bell',''];
                        ?>
                            <a href="<?php echo $base; ?>notifications.php?open=<?php echo (int)$n['id']; ?>" class="flex gap-3 px-4 py-3 border-b border-slate-50 hover:bg-slate-50">
                                <span class="w-8 h-8 rounded-xl flex items-center justify-center flex-shrink-0 bg-<?php echo $nm[1]; ?>-50 text-<?php echo $nm[1]; ?>-600 text-xs">
                                    <i class="fas <?php echo $nm[2]; ?>"></i>
                                </span>
                                <span class="min-w-0 flex-1">
                                    <span class="block text-sm font-bold mb-0.5 truncate"><?php echo htmlspecialchars($n['title']); ?></span>
                                    <span class="block text-xs text-slate-500 line-clamp-2"><?php echo htmlspecialchars($n['message']); ?></span>
                                    <span class="block text-[10px] text-slate-400 mt-1.5">
                                        <i class="far fa-clock mr-1"></i><?php echo function_exists('notify_ago') ? notify_ago($n['created_at']) : date('d M, h:i A', strtotime($n['created_at'])); ?>
                                        <?php if (!empty($n['link'])): ?><span class="text-[#C8901B] font-bold ml-1">· Open <i class="fas fa-arrow-right text-[8px]"></i></span><?php endif; ?>
                                    </span>
                                </span>
                            </a>
                        <?php endforeach; else: ?>
                            <div class="px-4 py-8 text-center text-slate-400 text-sm">
                                <i class="fas fa-bell-slash text-2xl mb-2 block"></i> No new notifications
                            </div>
                        <?php endif; ?>
                    </div>
                    <a href="<?php echo $base; ?>notifications.php" class="block px-4 py-3 text-center text-sm font-bold text-[#C8901B] bg-slate-50 border-t border-slate-100">View All</a>
                </div>
            </div>

            <div class="relative">
                <button @click="profileOpen = !profileOpen" @click.away="profileOpen = false" class="flex items-center gap-1.5">
                    <?php if ($has_pic): ?>
                        <img src="<?php echo htmlspecialchars($pic); ?>" class="w-9 h-9 rounded-full object-cover ring-2 ring-[#F5C451]/60">
                    <?php else: ?>
                        <span class="w-9 h-9 rounded-full text-white flex items-center justify-center font-bold ring-2 ring-[#F5C451]/60" style="background:#111C44;"><?php echo strtoupper(substr($user['name'], 0, 1)); ?></span>
                    <?php endif; ?>
                    <i class="fas fa-chevron-down text-[10px] text-slate-400 hidden sm:block"></i>
                </button>
                <div x-show="profileOpen" x-cloak x-transition class="absolute right-0 mt-2 w-56 tp-card shadow-2xl py-2 z-50">
                    <div class="px-4 py-2 border-b border-slate-100">
                        <p class="text-[11px] text-slate-400">Signed in as</p>
                        <p class="text-sm font-bold truncate"><?php echo htmlspecialchars($user['name']); ?></p>
                        <?php if (!empty($user['mobile'])): ?><p class="text-[11px] text-slate-400"><?php echo htmlspecialchars($user['mobile']); ?></p><?php endif; ?>
                    </div>
                    <?php foreach ($prof_links as $pl): ?>
                        <a href="<?php echo htmlspecialchars($pl['href']); ?>" class="block px-4 py-2 text-sm hover:bg-slate-50">
                            <i class="fas <?php echo htmlspecialchars($pl['icon'] ?? 'fa-angle-right'); ?> w-4 mr-2 text-slate-400"></i><?php echo htmlspecialchars($pl['label']); ?>
                        </a>
                    <?php endforeach; ?>
                    <div class="border-t border-slate-100 mt-1 pt-1">
                        <a href="<?php echo $base; ?>logout.php" onclick="return confirm('Are you sure?');" class="block px-4 py-2 text-sm text-rose-600 hover:bg-rose-50"><i class="fas fa-right-from-bracket w-4 mr-2"></i>Logout</a>
                    </div>
                </div>
            </div>
        </div>
    </header>
    <?php
}

/* ---------- Shell open / close ---------- */
function theme_open($cfg) {
    $extra = !empty($cfg['state']) ? ', ' . $cfg['state'] : '';
    // Escaped so JSON/quotes inside the state can't break the attribute
    $xdata = htmlspecialchars('{ sidebarOpen: window.innerWidth >= 768, profileOpen: false, notifOpen: false, langOpen: false' . $extra . ' }', ENT_QUOTES);
    // Pages that use hash-based tabs (#edit, #kyc ...) need to react to hash changes
    $hashsync = (strpos($extra, 'currentTab') !== false)
        ? ' @hashchange.window="if (window.location.hash) { currentTab = window.location.hash.substring(1); profileOpen = false; }"'
        : '';
    ?>
<body x-data="<?php echo $xdata; ?>"<?php echo $hashsync; ?>>
    <?php theme_styles(); ?>
    <div class="flex h-screen overflow-hidden">
        <?php theme_sidebar($cfg); ?>
        <div x-show="sidebarOpen" x-cloak @click="sidebarOpen = false" x-transition.opacity class="fixed inset-0 bg-slate-900/50 z-40 md:hidden"></div>
        <div class="flex-1 flex flex-col min-w-0 min-h-0">
            <?php theme_header($cfg); ?>
    <?php
}

function theme_close() {
    ?>
        </div>
    </div>
</body>
    <?php
}
