<?php

use Core\System\Language;
use Core\App\Models\ThemeSettings;
use Core\App\Models\AdminProfileModel;

if (defined('MTE_ADMIN_LAYOUT_HEADER_RENDERED')) {
    return;
}
define('MTE_ADMIN_LAYOUT_HEADER_RENDERED', true);

if (!defined('ADMIN_PATH')) {
    define('ADMIN_PATH', dirname(__DIR__));
}

/* =============================
   Session (SAFE)
============================= */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/* =============================
   URL NORMALIZER (CRITICAL FIX)
   Fixes: https://uploads/... problem
============================= */
if (!function_exists('mte_normalize_asset_url')) {
    function mte_normalize_asset_url($path): string
    {
        $path = trim((string)$path);

        if ($path === '') {
            return '';
        }

        // If already absolute URL (http/https), keep as is
        if (preg_match('#^https?://#i', $path)) {
            return $path;
        }

        // If already root path, keep as is
        if ($path[0] === '/') {
            return $path;
        }

        // Otherwise make it root-relative
        return '/' . $path;
    }
}

/* =============================
   Load Admin Theme Settings (SAFE)
============================= */
$themeSettings = new ThemeSettings();
$settings = $themeSettings->getAll();

/* =============================
   Language
============================= */
$currentLangCode = Language::code();
$dir             = Language::direction();

$availableLanguages = [];
$langDir = ROOT_PATH . '/lang/';

if (is_dir($langDir)) {
    foreach (glob($langDir . '*.json') as $file) {
        $code = basename($file, '.json');
        $data = json_decode(file_get_contents($file), true) ?: [];
        $name = $data['language.name'] ?? strtoupper($code);

        $availableLanguages[] = [
            'code' => $code,
            'name' => $name,
        ];
    }
}

/* =============================
   Admin Theme
============================= */
$adminTheme  = $settings['admin_theme'] ?? [];
$adminFonts  = $adminTheme['fonts']  ?? [];
$adminColors = $adminTheme['colors'] ?? [];
$adminMode   = $adminTheme['mode']   ?? 'light';

$fontMap = [
    'ar_cairo' => [
        'family' => "'Cairo', sans-serif",
        'import' => "/public/assets/fonts/cairo/cairo.css",
    ],
    'ar_tajawal' => [
        'family' => "'Tajawal', sans-serif",
        'import' => "/public/assets/fonts/tajawal/tajawal.css",
    ],
    'ar_noto_kufi' => [
        'family' => "'Noto Kufi Arabic', sans-serif",
        'import' => "/public/assets/fonts/noto-kufi-arabic/noto-kufi-arabic.css",
    ],
    'en_poppins' => [
        'family' => "'Poppins', sans-serif",
        'import' => "/public/assets/fonts/poppins/poppins.css",
    ],
    'en_roboto' => [
        'family' => "'Roboto', sans-serif",
        'import' => "/public/assets/fonts/roboto/roboto.css",
    ],
];

$adminBodyKey    = $adminFonts['body']    ?? null;
$adminHeadingKey = $adminFonts['heading'] ?? null;

/* =============================
   Admin Logo + Favicon (DB)
   admin_logo → site_logo → fallback
============================= */

$adminLogo  = '/admin/assets/adminlte-assets/img/AdminLTELogo.png';
$adminFavicon = '/admin/assets/adminlte-assets/img/favicon.ico';

try {
    $_hdrSettings = new \Core\App\Models\Settings();
    $logoPath = $_hdrSettings->get('admin_logo', '') ?: $_hdrSettings->get('site_logo', '');
    if (!empty($logoPath)) {
        $adminLogo = mte_normalize_asset_url($logoPath);
    }
    $faviconPath = $_hdrSettings->get('favicon', '');
    if (!empty($faviconPath)) {
        $adminFavicon = mte_normalize_asset_url($faviconPath);
    }
} catch (\Throwable $e) {
    // fallback silently
}

/* =============================
   Admin Notifications List
============================= */
$adminNotifications = [];

try {
    $_notifModel = new \Core\App\Models\AdminNotificationModel();
    $currentAdminId = (int)($_SESSION['admin_id'] ?? 0);
    $isNotifManager = in_array((string)($_SESSION['admin_role'] ?? ''), ['owner', 'manager'], true);
    $adminNotifications  = $_notifModel->getLatestForAdmin($currentAdminId, $isNotifManager, 5);
    $latestNotifications = $adminNotifications;
    $unreadNotifications = $_notifModel->countUnread($currentAdminId, $isNotifManager);
} catch (\Throwable $e) {
    $adminNotifications  = [];
    $latestNotifications = [];
    $unreadNotifications = 0;
}

/* =============================
   Team Unread Message Count
============================= */
$teamUnreadCount = 0;
if (!empty($_SESSION['admin_id'])) {
    try {
        $teamUnreadCount = (new \Core\App\Models\TeamMessageModel())->totalUnread((int)$_SESSION['admin_id']);
    } catch (\Throwable $e) {
        $teamUnreadCount = 0;
    }
}

$adminAvatar = '/admin/assets/adminlte-assets/img/avatar.png';
$adminName   = 'Admin';

try {
    if (true) { // kept for compatibility
        // no-op
    }
} catch (\Throwable $e) {
    $unreadNotifications = 0;
    $latestNotifications = [];
}

if (!empty($_SESSION['admin_id'])) {
    $adminModel = new AdminProfileModel();
    $adminData  = $adminModel->findById((int) $_SESSION['admin_id']);

    if ($adminData) {
        $adminName = $adminData['username'] ?? $adminName;

        if (!empty($adminData['avatar'])) {
            $adminAvatar = mte_normalize_asset_url($adminData['avatar']);
        }
    }
}

/* =============================
   ✅ Helper: HEX => RGB (for Bootstrap vars)
============================= */
if (!function_exists('mte_hex_to_rgb')) {
    function mte_hex_to_rgb(string $hex): ?array
    {
        $hex = trim($hex);
        $hex = ltrim($hex, '#');

        if (strlen($hex) === 3) {
            $hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
        }

        if (strlen($hex) !== 6 || !ctype_xdigit($hex)) {
            return null;
        }

        return [
            hexdec(substr($hex, 0, 2)),
            hexdec(substr($hex, 2, 2)),
            hexdec(substr($hex, 4, 2)),
        ];
    }
}
?>
<!doctype html>
<html lang="<?= htmlspecialchars($currentLangCode, ENT_QUOTES, 'UTF-8') ?>"
      dir="<?= htmlspecialchars($dir, ENT_QUOTES, 'UTF-8') ?>">
<head>
    <meta charset="utf-8">
    <title>MTEngine | Admin Panel</title>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="color-scheme" content="light dark">

    <link rel="icon" type="image/x-icon"
          href="<?= htmlspecialchars($adminFavicon, ENT_QUOTES, 'UTF-8') ?>">

    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/@fontsource/source-sans-3@5.0.12/index.css">
    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css">
    <link rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/overlaysscrollbars@2.11.0/styles/overlaysscrollbars.min.css">
    <link rel="stylesheet" href="/plugins/SocialProductStudio/assets/css/social-preview.css">
    

    <?php if ($dir === 'rtl'): ?>
        <link rel="stylesheet" href="/admin/assets/css/adminlte.rtl.css">
    <?php else: ?>
        <link rel="stylesheet" href="/admin/assets/css/adminlte.css">
    <?php endif; ?>

    <!-- Admin Fonts Imports -->
    <?php
    $imports = [];
    foreach ([$adminBodyKey, $adminHeadingKey] as $key) {
        if ($key && isset($fontMap[$key])) {
            $imports[$key] = $fontMap[$key]['import'];
        }
    }
    foreach ($imports as $css): ?>
        <link rel="stylesheet" href="<?= $css ?>">
    <?php endforeach; ?>
    <style>
        .app-header {
            position: sticky;
            top: 0;
            z-index: 1035;
            height: var(--mte-header-h);
        }

        /* ===== Admin Fonts ===== */
        <?php if ($adminBodyKey && isset($fontMap[$adminBodyKey])): ?>
        body,
        .app-wrapper,
        .nav,
        .nav-link,
        .sidebar,
        .app-sidebar,
        .app-header,
        .brand-text,
        .btn,
        .table,
        .card,
        .form-control,
        .form-select {
            font-family: <?= $fontMap[$adminBodyKey]['family'] ?> !important;
        }
        <?php endif; ?>

        <?php if ($adminHeadingKey && isset($fontMap[$adminHeadingKey])): ?>
        h1, h2, h3, h4, h5, h6 {
            font-family: <?= $fontMap[$adminHeadingKey]['family'] ?> !important;
        }
        <?php endif; ?>

        /* ===== Admin Colors ===== */

        /* ✅ Bootstrap Vars (this is the KEY to change buttons + alerts + badges correctly) */
        :root,
        [data-bs-theme=light] {
            <?php
            $bsKeys = ['primary','secondary','success','info','warning','danger','light','dark'];

            foreach ($bsKeys as $k) {
                if (!empty($adminColors[$k])) {
                    $hex = (string) $adminColors[$k];
                    $rgb = mte_hex_to_rgb($hex);

                    echo "--bs-{$k}: {$hex};\n";

                    if ($rgb) {
                        echo "--bs-{$k}-rgb: {$rgb[0]}, {$rgb[1]}, {$rgb[2]};\n";
                    }
                }
            }

            // Extra admin layout vars (optional)
            if (!empty($adminColors['body_bg'])) {
                echo "--bs-body-bg: {$adminColors['body_bg']};\n";
            }
            if (!empty($adminColors['body_text'])) {
                echo "--bs-body-color: {$adminColors['body_text']};\n";
            }
            if (!empty($adminColors['border'])) {
                echo "--bs-border-color: {$adminColors['border']};\n";
            }
            if (!empty($adminColors['link'])) {
                echo "--bs-link-color: {$adminColors['link']};\n";
            }
            ?>
        }

        /* ✅ Keep your old primary override (safe) */
        <?php if (!empty($adminColors['primary'])): ?>
        .btn-primary,
        .bg-primary {
            background-color: <?= $adminColors['primary'] ?> !important;
            border-color: <?= $adminColors['primary'] ?> !important;
        }
        <?php endif; ?>

        /* ✅ Sidebar */
        <?php if (!empty($adminColors['sidebar_bg'])): ?>
        .app-sidebar {
            background-color: <?= $adminColors['sidebar_bg'] ?> !important;
        }
        <?php endif; ?>

        <?php if (!empty($adminColors['sidebar_text'])): ?>
        .app-sidebar .nav-link,
        .app-sidebar .brand-link,
        .app-sidebar .brand-link .brand-text {
            color: <?= $adminColors['sidebar_text'] ?> !important;
        }
        <?php endif; ?>

        <?php if (!empty($adminColors['sidebar_active_bg'])): ?>
        .app-sidebar .nav-link.active,
        .app-sidebar .nav-link:hover {
            background-color: <?= $adminColors['sidebar_active_bg'] ?> !important;
        }
        <?php endif; ?>

        <?php if (!empty($adminColors['sidebar_active_text'])): ?>
        .app-sidebar .nav-link.active,
        .app-sidebar .nav-link.active .nav-icon,
        .app-sidebar .nav-link:hover,
        .app-sidebar .nav-link:hover .nav-icon {
            color: <?= $adminColors['sidebar_active_text'] ?> !important;
        }
        <?php endif; ?>

        /* ✅ Header */
        <?php if (!empty($adminColors['header_bg'])): ?>
        .app-header {
            background-color: <?= $adminColors['header_bg'] ?> !important;
        }
        <?php endif; ?>

        <?php if (!empty($adminColors['header_text'])): ?>
        .app-header,
        .app-header .nav-link {
            color: <?= $adminColors['header_text'] ?> !important;
        }
        <?php endif; ?>

        /* ✅ Body */
        <?php if (!empty($adminColors['body_bg'])): ?>
        body {
            background-color: <?= $adminColors['body_bg'] ?> !important;
        }
        <?php endif; ?>

        <?php if (!empty($adminColors['body_text'])): ?>
        body {
            color: <?= $adminColors['body_text'] ?> !important;
        }
        <?php endif; ?>

        /* ✅ Card */
        <?php if (!empty($adminColors['card_bg'])): ?>
        .card {
            background-color: <?= $adminColors['card_bg'] ?> !important;
        }
        <?php endif; ?>

        <?php if (!empty($adminColors['card_header_bg'])): ?>
        .card .card-header {
            background-color: <?= $adminColors['card_header_bg'] ?> !important;
        }
        <?php endif; ?>

        <?php if ($adminMode === 'dark'): ?>
        body {
            color-scheme: dark;
        }
        <?php endif; ?>

        .admin-notifications .notification-icon {
            position: relative;
            display: inline-flex;
            align-items: center;
        }

        .admin-notifications .notification-badge {
            position: absolute;
            top: -4px;
            inset-inline-end: -6px;

            min-width: 18px;
            height: 18px;
            padding: 0 5px;

            background-color: #dc3545;
            color: #fff;

            font-size: 11px;
            font-weight: 700;
            line-height: 18px;
            text-align: center;

            border-radius: 999px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, .25);
        }


        /* ===== Unified admin cards / section icons / page titles ===== */
        :root {
            --mte-card-blue: #0d6efd;
            --mte-card-green: #198754;
            --mte-card-cyan: #0dcaf0;
            --mte-card-purple: #6f42c1;
            --mte-card-orange: #fd7e14;
            --mte-card-red: #dc3545;
            --mte-card-border: rgba(15, 23, 42, 0.08);
            --mte-card-shadow: 0 10px 30px rgba(15, 23, 42, 0.06);
            --mte-title-size: 2rem;
            --mte-section-title-size: 1.125rem;
            --mte-body-size: 0.95rem;
        }

        .content-wrapper,
        .content-wrapper .card,
        .content-wrapper .table,
        .content-wrapper .form-label,
        .content-wrapper .form-control,
        .content-wrapper .form-select,
        .content-wrapper .small,
        .content-wrapper p,
        .content-wrapper li,
        .content-wrapper span {
            font-size: var(--mte-body-size);
        }

        .content-wrapper .card {
            border: 0 !important;
            border-radius: 14px !important;
            box-shadow: var(--mte-card-shadow) !important;
            overflow: hidden;
        }

        .content-wrapper .row > [class*="col-"] > .card,
        .content-wrapper .col > .card {
            border-top: 3px solid var(--mte-card-blue);
        }
        .content-wrapper .row > [class*="col-"]:nth-child(4n+2) > .card,
        .content-wrapper .col:nth-child(4n+2) > .card {
            border-top-color: var(--mte-card-green);
        }
        .content-wrapper .row > [class*="col-"]:nth-child(4n+3) > .card,
        .content-wrapper .col:nth-child(4n+3) > .card {
            border-top-color: var(--mte-card-cyan);
        }
        .content-wrapper .row > [class*="col-"]:nth-child(4n+4) > .card,
        .content-wrapper .col:nth-child(4n+4) > .card {
            border-top-color: var(--mte-card-purple);
        }

        .content-wrapper .card .card-header {
            background: #fff !important;
            border-bottom: 1px solid var(--mte-card-border) !important;
            padding-top: 1rem;
            padding-bottom: 1rem;
        }

        .content-wrapper .card .card-header h1,
        .content-wrapper .card .card-header h2,
        .content-wrapper .card .card-header h3,
        .content-wrapper .card .card-header h4,
        .content-wrapper .card .card-header h5,
        .content-wrapper .card .card-header h6,
        .content-wrapper .card-title {
            font-size: var(--mte-section-title-size) !important;
            font-weight: 700 !important;
            margin-bottom: 0 !important;
            line-height: 1.35;
        }

        .content-wrapper .card .card-header .bi,
        .content-wrapper .card .card-header [class^="fa"],
        .content-wrapper .card .card-header [class*=" fa"] {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 34px;
            height: 34px;
            border-radius: 999px;
            margin-inline-end: .5rem;
            font-size: 1rem;
            background: rgba(13, 110, 253, 0.12);
            color: var(--mte-card-blue) !important;
            vertical-align: middle;
        }

        .content-wrapper .row > [class*="col-"]:nth-child(4n+2) .card .card-header .bi,
        .content-wrapper .row > [class*="col-"]:nth-child(4n+2) .card .card-header [class^="fa"],
        .content-wrapper .row > [class*="col-"]:nth-child(4n+2) .card .card-header [class*=" fa"] {
            background: rgba(25, 135, 84, 0.12);
            color: var(--mte-card-green) !important;
        }
        .content-wrapper .row > [class*="col-"]:nth-child(4n+3) .card .card-header .bi,
        .content-wrapper .row > [class*="col-"]:nth-child(4n+3) .card .card-header [class^="fa"],
        .content-wrapper .row > [class*="col-"]:nth-child(4n+3) .card .card-header [class*=" fa"] {
            background: rgba(13, 202, 240, 0.12);
            color: var(--mte-card-cyan) !important;
        }
        .content-wrapper .row > [class*="col-"]:nth-child(4n+4) .card .card-header .bi,
        .content-wrapper .row > [class*="col-"]:nth-child(4n+4) .card .card-header [class^="fa"],
        .content-wrapper .row > [class*="col-"]:nth-child(4n+4) .card .card-header [class*=" fa"] {
            background: rgba(111, 66, 193, 0.12);
            color: var(--mte-card-purple) !important;
        }

        .content-wrapper .content-header h1,
        .content-wrapper .page-title,
        .content-wrapper .page-title h1,
        .content-wrapper .page-title h2,
        .content-wrapper .page-title h3,
        .content-wrapper .d-flex.flex-wrap.justify-content-between.align-items-center.gap-3.mb-4 h3,
        .content-wrapper .d-flex.flex-wrap.justify-content-between.align-items-center.gap-3.mb-4 h1 {
            font-size: var(--mte-title-size) !important;
            font-weight: 800 !important;
            line-height: 1.2;
            margin-bottom: 0 !important;
            letter-spacing: -0.02em;
        }

        .content-wrapper .content-header h1 .bi,
        .content-wrapper .page-title .bi,
        .content-wrapper .d-flex.flex-wrap.justify-content-between.align-items-center.gap-3.mb-4 h3 .bi,
        .content-wrapper .d-flex.flex-wrap.justify-content-between.align-items-center.gap-3.mb-4 h1 .bi {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 38px;
            height: 38px;
            border-radius: 999px;
            margin-inline-end: .55rem;
            font-size: 1.05rem;
            background: rgba(111, 66, 193, 0.12);
            color: var(--mte-card-purple) !important;
            vertical-align: middle;
        }

        .content-wrapper .d-flex.flex-wrap.justify-content-between.align-items-center.gap-3.mb-4 > div > small,
        .content-wrapper .page-subtitle,
        .content-wrapper .content-header p,
        .content-wrapper .content-header small {
            font-size: .92rem !important;
            color: #6b7280 !important;
        }

        .content-wrapper .card .card-body .text-muted,
        .content-wrapper .card .card-footer .text-muted {
            color: #6b7280 !important;
        }

    </style>
    <link rel="stylesheet" href="/public/assets/shared/product-badges.css">
</head>
<body class="layout-fixed sidebar-expand-lg bg-body-tertiary <?= $dir === 'rtl' ? 'rtl' : 'ltr' ?>">

<div class="app-wrapper">

<nav class="app-header navbar navbar-expand bg-body border-bottom">
    <div class="container-fluid">

        <ul class="navbar-nav">
            <li class="nav-item">
                <a class="nav-link" data-lte-toggle="sidebar" href="#" role="button">
                    <i class="bi bi-list"></i>
                </a>
            </li>

<li class="nav-item d-none d-md-flex align-items-center">
    <div class="d-flex align-items-center gap-2">

        <!-- ✅ Preview Button -->
        <a href="/" target="_blank" class="btn btn-outline-primary btn-sm">
            <i class="bi bi-eye me-1"></i>
            <?= __('actions.preview', 'Preview') ?>
        </a>

        <!-- ✅ Clear Cache Button -->
        <form method="POST"
              action="/admin/system/clear-cache"
              class="m-0 p-0"
              onsubmit="return confirm(<?= json_encode(__('actions.confirm_clear_cache', 'Clear cache now? Visitors will see the latest changes immediately.')) ?>);">
            <?= \Core\System\Csrf::field(); ?>
            <button type="submit" class="btn btn-outline-danger btn-sm">
                <i class="bi bi-trash3 me-1"></i>
                <?= __('actions.clear_cache', 'Clear Cache') ?>
            </button>
        </form>

    </div>
</li>

        </ul>

        <ul class="navbar-nav ms-auto">

            <!-- Language -->
            <li class="nav-item dropdown">
                <a class="nav-link" data-bs-toggle="dropdown" href="#" role="button">
                    <i class="bi bi-translate"></i>
                </a>
                <div class="dropdown-menu dropdown-menu-end">
                    <?php foreach ($availableLanguages as $language): ?>
                        <a href="/admin/lang/<?= htmlspecialchars($language['code']) ?>" class="dropdown-item">
                            <?= htmlspecialchars($language['name']) ?>
                            <?= $language['code'] === $currentLangCode ? ' ✓' : '' ?>
                        </a>
                    <?php endforeach; ?>
                </div>
            </li>

            <!-- Notifications -->
            <li class="nav-item dropdown admin-notifications">
                <a class="nav-link notification-icon"
                   href="#"
                   id="notificationsDropdown"
                   data-bs-toggle="dropdown"
                   aria-expanded="false">

                    <i class="bi bi-bell"></i>

                    <?php if ($unreadNotifications > 0): ?>
                        <span class="notification-badge">
                            <?= (int) $unreadNotifications ?>
                        </span>
                    <?php endif; ?>
                </a>

                <div class="dropdown-menu dropdown-menu-end p-0"
                     style="width:340px"
                     aria-labelledby="notificationsDropdown">

                    <div class="dropdown-header fw-bold">
                        <?= __('admin.notifications', 'Notifications') ?>
                    </div>

                    <div id="notifications-list">
                        <div class="text-center py-3 text-muted">
                            <?= __('admin.loading', 'Loading...') ?>
                        </div>
                    </div>

                    <div class="dropdown-divider"></div>

                    <a href="/admin/notifications"
                       class="dropdown-item text-center">
                        <?= __('admin.view_all', 'View all notifications') ?>
                    </a>
                </div>
            </li>

            <!-- Admin Profile -->
            <li class="nav-item dropdown">
                <a class="nav-link d-flex align-items-center"
                   data-bs-toggle="dropdown"
                   href="#"
                   role="button">
                    <img src="<?= htmlspecialchars($adminAvatar, ENT_QUOTES, 'UTF-8') ?>"
                         class="rounded-circle"
                         width="32"
                         height="32"
                         alt="Admin">
                    <span class="ms-2 d-none d-sm-inline">
                        <?= htmlspecialchars($adminName, ENT_QUOTES, 'UTF-8') ?>
                    </span>
                </a>
                <div class="dropdown-menu dropdown-menu-end">
                    <a href="/admin/profile" class="dropdown-item">
                        <i class="bi bi-person-gear me-2"></i>
                        <?= __('sidebar.account_settings', 'Account Settings') ?>
                    </a>
                    <div class="dropdown-divider"></div>
                    <form method="POST" action="/admin/logout" class="d-inline w-100">
                        <input type="hidden" name="_csrf" value="<?= htmlspecialchars(\Core\System\Csrf::token(), ENT_QUOTES, 'UTF-8') ?>">
                        <button type="submit" class="dropdown-item border-0 bg-transparent w-100 text-start">
                            <i class="bi bi-box-arrow-right me-2"></i>
                            <?= __('sidebar.logout', 'Logout') ?>
                        </button>
                    </form>
                </div>
            </li>

        </ul>
    </div>
</nav>

<aside class="app-sidebar bg-body-secondary shadow" data-bs-theme="dark">
    <div class="sidebar-brand">
        <a href="/admin/dashboard" class="brand-link">
            <img src="<?= htmlspecialchars($adminLogo, ENT_QUOTES, 'UTF-8') ?>"
                 class="brand-image"
                 alt="Admin Logo">
        </a>
    </div>

    <div class="sidebar-wrapper">
        <nav class="mt-2">
            <?php
            $uri  = $_SERVER['REQUEST_URI'] ?? '';
            $role = $_SESSION['admin_role'] ?? 'owner';

            $active      = fn(string $p) => str_starts_with($uri, '/admin'.$p) ? 'active' : '';
            $activeExact = fn(string $p) => ($uri === '/admin'.$p || $uri === '/admin'.$p.'/') ? 'active' : '';
            $isOwner     = in_array($role, ['owner','manager'], true);
            $isCan       = fn(string $p) => \Core\App\Models\TeamMemberModel::can($role, $p);
            ?>
            <ul class="nav sidebar-menu flex-column" data-widget="treeview">

                <!-- ══ Dashboard ══ -->
                <?php if ($isOwner || $isCan('view_stats')): ?>
                <li class="nav-item">
                    <a href="/admin/dashboard" class="nav-link <?= $activeExact('/dashboard') ?>">
                        <i class="nav-icon bi bi-speedometer2"></i>
                        <p><?= __('sidebar.dashboard','Dashboard') ?></p>
                    </a>
                </li>
                <?php endif; ?>

                <!-- ══ Finance ══ -->
                <?php if (in_array($role, ['owner','manager','accountant'], true)): ?>
                <li class="nav-item">
                    <a href="/admin/finance" class="nav-link <?= $active('/finance') ?>">
                        <i class="nav-icon bi bi-bar-chart-line-fill"></i>
                        <p><?= __('sidebar.finance','Finance & Analytics') ?></p>
                    </a>
                </li>
                <?php endif; ?>

                <!-- ══ Products ══ -->
                <?php if ($isOwner || $isCan('view_products')): ?>
                <li class="nav-item">
                    <a href="#" class="nav-link <?= (str_starts_with($uri,'/admin/products')||str_starts_with($uri,'/admin/inventory')||str_starts_with($uri,'/admin/categories')||str_starts_with($uri,'/admin/reviews')) ? 'active' : '' ?>"
                       data-lte-toggle="treeview">
                        <i class="nav-icon bi bi-box-seam-fill"></i>
                        <p>
                            <?= __('sidebar.products','Products') ?>
                            <i class="bi bi-chevron-down nav-arrow"></i>
                        </p>
                    </a>
                    <ul class="nav nav-treeview">
                        <li class="nav-item">
                            <a href="/admin/products" class="nav-link <?= $active('/products') ?>">
                                <i class="nav-icon bi bi-grid-3x3-gap"></i>
                                <p><?= __('sidebar.all_products','All Products') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/inventory" class="nav-link <?= $active('/inventory') ?>">
                                <i class="nav-icon bi bi-archive-fill"></i>
                                <p><?= __('sidebar.inventory','Inventory') ?></p>
                            </a>
                        </li>
                                        <!-- ══ AI Landing Pages ══ -->
                <?php if ($isOwner || $isCan('view_products')): ?>
                <li class="nav-item">
                    <a href="/admin/ai-landing-pages" class="nav-link <?= $active('/ai-landing-pages') ?>">
                        <i class="nav-icon bi bi-stars"></i>
                        <p><?= __('sidebar.ai_landing_pages','AI Landing Pages') ?></p>
                    </a>
                </li>
                <?php endif; ?>
                        <?php if ($isOwner): ?>
                        <li class="nav-item">
                            <a href="/admin/categories" class="nav-link <?= $active('/categories') ?>">
                                <i class="nav-icon bi bi-tags-fill"></i>
                                <p><?= __('sidebar.categories','Categories') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/reviews" class="nav-link <?= $active('/reviews') ?>">
                                <i class="nav-icon bi bi-star-half"></i>
                                <p><?= __('sidebar.reviews','Reviews') ?></p>
                            </a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ══ Orders ══ -->
                <?php if ($isOwner || $isCan('view_orders') || $isCan('view_assigned_orders') || $isCan('view_confirmed_orders') || $isCan('view_orders_readonly') || $isCan('manage_shipping')): ?>
                <li class="nav-item">
                    <a href="#" class="nav-link <?= (str_starts_with($uri,'/admin/orders')||str_starts_with($uri,'/admin/shipments')||str_starts_with($uri,'/admin/suspicious')) ? 'active' : '' ?>"
                       data-lte-toggle="treeview">
                        <i class="nav-icon bi bi-bag-check-fill"></i>
                        <p>
                            <?= __('sidebar.orders','Orders') ?>
                            <i class="bi bi-chevron-down nav-arrow"></i>
                        </p>
                    </a>
                    <ul class="nav nav-treeview">
                        <?php if ($isOwner || $isCan('view_orders') || $isCan('view_assigned_orders') || $isCan('view_confirmed_orders') || $isCan('view_orders_readonly')): ?>
                        <li class="nav-item">
                            <a href="/admin/orders" class="nav-link <?= $activeExact('/orders') ?>">
                                <i class="nav-icon bi bi-receipt-cutoff"></i>
                                <p><?= __('sidebar.all_orders','All Orders') ?></p>
                            </a>
                        </li>
                        <?php endif; ?>
                        <?php if ($isOwner || $isCan('manage_shipping')): ?>
                        <li class="nav-item">
                            <a href="/admin/shipments" class="nav-link <?= $activeExact('/shipments') ?>">
                                <i class="nav-icon bi bi-send-check-fill"></i>
                                <p><?= __('shipments.title','My Shipments') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/shipments/control" class="nav-link <?= $active('/shipments/control') ?>">
                                <i class="nav-icon bi bi-truck-front-fill"></i>
                                <p><?= __('sidebar.shipping.control','Shipping Control') ?></p>
                            </a>
                        </li>
                        <?php endif; ?>
                        <?php if ($isOwner || $isCan('confirm_orders')): ?>
                        <li class="nav-item">
                            <a href="/admin/orders/call-attempts" class="nav-link <?= $active('/orders/call-attempts') ?>">
                                <i class="nav-icon bi bi-telephone-fill"></i>
                                <p><?= __('calls.nav_title','Call Attempts') ?></p>
                            </a>
                        </li>
                        <?php endif; ?>
                        <?php if ($isOwner || $isCan('view_suspicious')): ?>
                        <li class="nav-item">
                            <a href="/admin/suspicious-orders" class="nav-link <?= $active('/suspicious') ?>">
                                <i class="nav-icon bi bi-exclamation-triangle-fill"></i>
                                <p><?= __('fraud.page_title','Suspicious Orders') ?></p>
                            </a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ══ Customers ══ -->
                <?php if ($isOwner): ?>
                <li class="nav-item">
                    <a href="#" class="nav-link <?= str_starts_with($uri,'/admin/customers') ? 'active' : '' ?>"
                       data-lte-toggle="treeview">
                        <i class="nav-icon bi bi-people-fill"></i>
                        <p>
                            <?= __('sidebar.customers','Customers') ?>
                            <i class="bi bi-chevron-down nav-arrow"></i>
                        </p>
                    </a>
                    <ul class="nav nav-treeview">
                        <li class="nav-item">
                            <a href="/admin/customers" class="nav-link <?= ($active('/customers') && !str_contains($uri,'marketing')) ? 'active' : '' ?>">
                                <i class="nav-icon bi bi-person-lines-fill"></i>
                                <p><?= __('sidebar.customers_list','Customer List') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/customers/marketing" class="nav-link <?= $active('/customers/marketing') ?>">
                                <i class="nav-icon bi bi-megaphone-fill"></i>
                                <p><?= __('sidebar.marketing','Marketing Campaigns') ?></p>
                            </a>
                        </li>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ══ Team ══ (parent visible to all authenticated admins) -->
                <li class="nav-item">
                    <a href="#" class="nav-link <?= (str_starts_with($uri,'/admin/team')) ? 'active' : '' ?>"
                       data-lte-toggle="treeview">
                        <i class="nav-icon bi bi-person-workspace"></i>
                        <p>
                            <?= __('sidebar.team','Team Management') ?>
                            <?php if (($teamUnreadCount ?? 0) > 0): ?>
                            <span class="badge bg-danger ms-auto" id="nav-msg-badge"><?= min(99, (int)$teamUnreadCount) ?></span>
                            <?php endif; ?>
                            <i class="bi bi-chevron-down nav-arrow"></i>
                        </p>
                    </a>
                    <ul class="nav nav-treeview">
                        <?php if (in_array($role, ['owner','manager'], true)): ?>
                        <li class="nav-item">
                            <a href="/admin/team" class="nav-link <?= ($uri === '/admin/team') ? 'active' : '' ?>">
                                <i class="nav-icon bi bi-people-fill"></i>
                                <p><?= __('sidebar.team_members','Team Members') ?></p>
                            </a>
                        </li>
                        <?php endif; ?>
                        <li class="nav-item">
                            <a href="/admin/team/communication" class="nav-link <?= (str_starts_with($uri,'/admin/team/communication') || str_starts_with($uri,'/admin/team/messages')) ? 'active' : '' ?>">
                                <i class="nav-icon bi bi-chat-dots-fill"></i>
                                <p>
                                    <?= __('sidebar.team_communication','Communication') ?>
                                    <?php if (($teamUnreadCount ?? 0) > 0): ?>
                                    <span class="badge bg-danger ms-1"><?= min(99, (int)$teamUnreadCount) ?></span>
                                    <?php endif; ?>
                                </p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/team/meetings" class="nav-link <?= str_starts_with($uri,'/admin/team/meetings') ? 'active' : '' ?>">
                                <i class="nav-icon bi bi-calendar-event-fill"></i>
                                <p><?= __('sidebar.team_meetings','Meetings') ?></p>
                            </a>
                        </li>
                        <?php if (in_array($role, ['owner','manager'], true)): ?>
                        <li class="nav-item">
                            <a href="/admin/team/activity" class="nav-link <?= str_starts_with($uri,'/admin/team/activity') ? 'active' : '' ?>">
                                <i class="nav-icon bi bi-activity"></i>
                                <p><?= __('sidebar.team_activity','Activity & Presence') ?></p>
                            </a>
                        </li>
                        <?php endif; ?>
                    </ul>
                </li>

                <!-- ══ Appearance ══ -->
                <?php if ($isOwner): ?>
                <li class="nav-item">
                    <a href="#" class="nav-link <?= (str_starts_with($uri,'/admin/appearance')||str_starts_with($uri,'/admin/home-sections')||str_starts_with($uri,'/admin/footer')||str_starts_with($uri,'/admin/settings/identity')||str_starts_with($uri,'/admin/languages')) ? 'active' : '' ?>"
                       data-lte-toggle="treeview">
                        <i class="nav-icon bi bi-palette2"></i>
                        <p>
                            <?= __('sidebar.branding','Appearance') ?>
                            <i class="bi bi-chevron-down nav-arrow"></i>
                        </p>
                    </a>
                    <ul class="nav nav-treeview">
                        <li class="nav-item">
                            <a href="/admin/appearance/customize" class="nav-link <?= $active('/appearance/customize') ?>">
                                <i class="nav-icon bi bi-brush-fill"></i>
                                <p><?= __('sidebar.theme_customizer','Theme Customizer') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/settings/identity" class="nav-link <?= $active('/settings/identity') ?>">
                                <i class="nav-icon bi bi-badge-ad-fill"></i>
                                <p><?= __('sidebar.site_identity','Site Identity') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/home-sections/" class="nav-link <?= $active('/home-sections') ?>">
                                <i class="nav-icon bi bi-layout-wtf"></i>
                                <p><?= __('sidebar.home_builder','Home Sections') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/appearance/header" class="nav-link <?= $active('/appearance/header') ?>">
                                <i class="nav-icon bi bi-window-nav"></i>
                                <p><?= __('sidebar.top_links','Header Links') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/footer/" class="nav-link <?= $active('/footer') ?>">
                                <i class="nav-icon bi bi-layout-text-window-reverse"></i>
                                <p><?= __('sidebar.footer','Footer') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/languages" class="nav-link <?= $active('/languages') ?>">
                                <i class="nav-icon bi bi-translate"></i>
                                <p><?= __('sidebar.languages','Languages') ?></p>
                            </a>
                        </li>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ══ Integrations ══ -->
                <?php if ($isOwner): ?>
                <li class="nav-item">
                    <a href="#" class="nav-link <?= (str_starts_with($uri,'/admin/integrations')||str_starts_with($uri,'/admin/settings/whatsapp')||str_starts_with($uri,'/admin/settings/gsheets')||str_starts_with($uri,'/admin/settings/ga4')||str_starts_with($uri,'/admin/settings/facebook')||str_starts_with($uri,'/admin/settings/tiktok')||str_starts_with($uri,'/admin/settings/gtm')||str_starts_with($uri,'/admin/settings/ai')) ? 'active' : '' ?>"
                       data-lte-toggle="treeview">
                        <i class="nav-icon bi bi-plug-fill"></i>
                        <p>
                            <?= __('sidebar.integrations','Integrations') ?>
                            <i class="bi bi-chevron-down nav-arrow"></i>
                        </p>
                    </a>
                    <ul class="nav nav-treeview">
                        <li class="nav-item">
                            <a href="/admin/integrations" class="nav-link <?= $activeExact('/integrations') ?>">
                                <i class="nav-icon bi bi-grid-1x2-fill"></i>
                                <p><?= __('sidebar.all_integrations','All Integrations') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/settings/whatsapp" class="nav-link <?= $active('/settings/whatsapp') ?>">
                                <i class="nav-icon bi bi-whatsapp"></i>
                                <p><?= __('sidebar.whatsapp','WhatsApp') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/settings/gsheets" class="nav-link <?= $active('/settings/gsheets') ?>">
                                <i class="nav-icon bi bi-file-earmark-spreadsheet-fill"></i>
                                <p><?= __('sidebar.gsheets','Google Sheets') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/settings/ai" class="nav-link <?= $active('/settings/ai') ?>">
                                <i class="nav-icon bi bi-robot"></i>
                                <p><?= __('sidebar.ai','AI Assistant') ?></p>
                            </a>
                        </li>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ══ Store Settings ══ -->
                <?php if ($isOwner): ?>
                <li class="nav-item">
                    <a href="#" class="nav-link <?= (str_starts_with($uri,'/admin/settings/basic')||str_starts_with($uri,'/admin/settings/shipping')||str_starts_with($uri,'/admin/pages')||str_starts_with($uri,'/admin/settings/security')) ? 'active' : '' ?>"
                       data-lte-toggle="treeview">
                        <i class="nav-icon bi bi-gear-wide-connected"></i>
                        <p>
                            <?= __('sidebar.manage_site','Store Settings') ?>
                            <i class="bi bi-chevron-down nav-arrow"></i>
                        </p>
                    </a>
                    <ul class="nav nav-treeview">
                        <li class="nav-item">
                            <a href="/admin/settings/basic" class="nav-link <?= $active('/settings/basic') ?>">
                                <i class="nav-icon bi bi-sliders2-vertical"></i>
                                <p><?= __('sidebar.basic_settings','Basic Settings') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/settings/shipping" class="nav-link <?= $active('/settings/shipping') ?>">
                                <i class="nav-icon bi bi-truck-flatbed"></i>
                                <p><?= __('sidebar.shipping','Shipping Settings') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/pages" class="nav-link <?= $active('/pages') ?>">
                                <i class="nav-icon bi bi-file-earmark-text-fill"></i>
                                <p><?= __('sidebar.pages','Pages') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/settings/security" class="nav-link <?= $active('/settings/security') ?>">
                                <i class="nav-icon bi bi-shield-fill-check"></i>
                                <p><?= __('sidebar.security_settings','Security') ?></p>
                            </a>
                        </li>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ══ System ══ -->
                <?php if ($isOwner): ?>
                <li class="nav-item">
                    <a href="#" class="nav-link <?= (str_starts_with($uri,'/admin/plugins')||str_starts_with($uri,'/admin/system')||str_starts_with($uri,'/admin/updates')||str_starts_with($uri,'/admin/support')) ? 'active' : '' ?>"
                       data-lte-toggle="treeview">
                        <i class="nav-icon bi bi-cpu-fill"></i>
                        <p>
                            <?= __('sidebar.system','System') ?>
                            <i class="bi bi-chevron-down nav-arrow"></i>
                        </p>
                    </a>
                    <ul class="nav nav-treeview">
                        <li class="nav-item">
                            <a href="/admin/plugins" class="nav-link <?= $active('/plugins') ?>">
                                <i class="nav-icon bi bi-puzzle-fill"></i>
                                <p><?= __('sidebar.plugins','Plugins') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/system/cleanup" class="nav-link <?= $active('/system/cleanup') ?>">
                                <i class="nav-icon bi bi-trash3-fill"></i>
                                <p><?= __('sidebar.cleanup','Cleanup') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/system/errors" class="nav-link <?= $active('/system/errors') ?>">
                                <i class="nav-icon bi bi-bug-fill"></i>
                                <p><?= __('sidebar.error_logs','Error Logs') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/system/backup" class="nav-link <?= $active('/system/backup') ?>">
                                <i class="nav-icon bi bi-cloud-arrow-down-fill"></i>
                                <p><?= __('sidebar.backup','Backup') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/updates-license" class="nav-link <?= $active('/updates-license') ?>">
                                <i class="nav-icon bi bi-patch-check-fill"></i>
                                <p><?= __('sidebar.updates_license','Updates & License') ?></p>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a href="/admin/support" class="nav-link <?= $active('/support') ?>">
                                <i class="nav-icon bi bi-headset"></i>
                                <p><?= __('sidebar.support','Support') ?></p>
                            </a>
                        </li>
                    </ul>
                </li>
                <?php endif; ?>

                <!-- ══ Logout ══ -->
                <li class="nav-item mt-2">
                    <form method="POST" action="/admin/logout">
                        <input type="hidden" name="_csrf" value="<?= htmlspecialchars(\Core\System\Csrf::token(), ENT_QUOTES, 'UTF-8') ?>">
                        <button type="submit" class="nav-link border-0 bg-transparent w-100 text-start">
                            <i class="nav-icon bi bi-box-arrow-right"></i>
                            <p><?= __('sidebar.logout','Logout') ?></p>
                        </button>
                    </form>
                </li>

            </ul>
        </nav>
    </div>
</aside>

<script>
// Team presence heartbeat — sends every 60s to update last_seen_at
(function() {
    const CSRF_TOKEN = <?php echo json_encode(\Core\System\Csrf::token()); ?>;
    function heartbeat() {
        fetch('/admin/team/presence/heartbeat', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: '_csrf=' + encodeURIComponent(CSRF_TOKEN)
        }).catch(function(){});
    }
    heartbeat(); // immediate on load
    setInterval(heartbeat, 60000);
})();
</script>
<main class="app-main">
<div class="app-content">
