<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/theme.php';
require_once __DIR__ . '/../../app/core/portal_auth.php';
require_once __DIR__ . '/../../app/core/AlertChecker.php';
require_once __DIR__ . '/../../app/core/i18n.php';

if (!isset($page_title)) $page_title = 'GoPools CRM';
$user = function_exists('auth_user') ? auth_user() : null;
$pdo = crm_pdo();
$theme = gp_theme_config($pdo);
$_gp_lang = gp_lang($pdo); // detect + cache language early

// Run Daily Alert Checks
if ($user && gp_is_full_project_access_role(strtolower(trim((string)($user['role'] ?? ''))))) {
    $alertChecker = new AlertChecker($pdo);
    $alertChecker->runDailyChecks();
}

$appName = $theme['app_name'] ?: 'GoPools CRM';
$bgCss = gp_theme_background_css($theme);
$themeMode = $theme['mode'];
$glass = !empty($theme['glass']);
$primary = $theme['primary'] ?: '#2563eb';
$secondary = $theme['secondary'] ?: '#0f172a';
$favicon = $theme['favicon'] ?? '';
$logo = $theme['logo'] ?? '';

$overlayOpacity = (float)($theme['background_overlay_opacity'] ?? 0.10);

$role = $user ? strtolower(trim((string)($user['role'] ?? ''))) : '';
$isAdminSettingsUser = ($user && gp_can_manage_project_access($pdo));
$showProjectsMenu = $user && (gp_is_full_project_access_role($role) || gp_is_secretary_like_role($role));
$showOperationsMenu = $user && (gp_is_full_project_access_role($role) || gp_is_secretary_like_role($role));
$showPeopleMenu = $user && (gp_is_full_project_access_role($role) || gp_is_secretary_like_role($role));
$showEmployeeMenu = $user && $role === 'employee';
$showPartnerMenu = $user && $role === 'partner';
$showCustomerMenu = $user && $role === 'customer';

// Load granular permissions for sidebar visibility
$_gpPerms = [];
if ($user && $user['id'] > 0) {
    try {
        $stmtPerms = $pdo->prepare("SELECT perm_expenses, perm_reports, perm_payroll, perm_dispatch,
            perm_warehouse, perm_settings, perm_branding, perm_users, perm_logs,
            perm_costings, perm_assign, perm_customers, perm_invoices, perm_financials, perm_photos
            FROM users WHERE id = ? LIMIT 1");
        $stmtPerms->execute([$user['id']]);
        $_gpPerms = $stmtPerms->fetch(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) { $_gpPerms = []; }
}
// Helper: check perm (admins/managers always pass)
$_gpHasPerm = function(string $key) use ($_gpPerms, $role): bool {
    if (in_array($role, ['admin','manager'], true)) return true;
    return (int)($_gpPerms[$key] ?? 0) === 1;
};
?>
<?php
$dbTheme = 'system';
if ($user && $user['id'] > 0) {
    if (isset($_SESSION['gp_theme_override'])) {
        $dbTheme = $_SESSION['gp_theme_override'];
    } else {
        try {
            $stmt = $pdo->prepare("SELECT theme_preference FROM users WHERE id = ?");
            $stmt->execute([$user['id']]);
            $dbTheme = $stmt->fetchColumn() ?: 'system';
            $_SESSION['gp_theme_override'] = $dbTheme;
        } catch (Throwable $e) {}
    }
}
$appliedTheme = ($dbTheme !== 'system' && $dbTheme !== '') ? $dbTheme : $themeMode;

$unreadNotifications = 0;
$userNotifications = [];
if ($user && $user['id'] > 0) {
    try {
        $stmtBadge = $pdo->prepare("SELECT COUNT(*) FROM user_notifications WHERE user_id = ? AND is_read = 0");
        $stmtBadge->execute([$user['id']]);
        $unreadNotifications = (int)$stmtBadge->fetchColumn();

        $stmtList = $pdo->prepare("SELECT * FROM user_notifications WHERE user_id = ? ORDER BY created_at DESC LIMIT 10");
        $stmtList->execute([$user['id']]);
        $userNotifications = $stmtList->fetchAll();
    } catch (Throwable $e) {}
}
?>
<!doctype html>
<html lang="<?php echo h($_gp_lang); ?>" data-theme="<?php echo h($appliedTheme); ?>">
<head>
<script>
    window.dbTheme = "<?php echo h($dbTheme); ?>";
    window.defaultThemeMode = "<?php echo h($themeMode); ?>";
    window.csrfToken = "<?php echo h(csrf_token()); ?>";
</script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo h($page_title); ?> · <?php echo h($appName); ?></title>
<?php if ($favicon !== ''): ?><link rel="icon" href="<?php echo h($favicon); ?>"><?php endif; ?>
<link rel="stylesheet" href="/gopools/public/assets/css/app.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<?php if ($appliedTheme === 'dark'): ?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/themes/dark.css">
<?php endif; ?>
<style>
:root {
  --gp-primary: <?php echo h($primary); ?>;
  --gp-secondary: <?php echo h($secondary); ?>;
  --gp-text: #0f172a;
  --gp-muted: #475569;
  --gp-card-bg: rgba(255, 255, 255, 0.78);
  --gp-card-border: rgba(15, 23, 42, 0.08);
  --gp-nav-bg-1: #ffffff;
  --gp-nav-bg-2: #f8fafc;
  --sidebar-w: <?php echo (int)($theme['sidebar_width'] ?? 260); ?>px;
  --radius: <?php echo (int)($theme['ui_border_radius'] ?? 20); ?>px !important;
  --font-sans: '<?php echo h($theme['font_family'] ?? 'Outfit'); ?>', sans-serif !important;
  --logo-h: <?php echo (int)($theme['brand_logo_height'] ?? 34); ?>px;
}
<?php
$selectedFont = $theme['font_family'] ?? 'Outfit';
$fontWeights = '300;400;500;600;700;800';
if ($selectedFont !== 'Outfit'): ?>
@import url('https://fonts.googleapis.com/css2?family=<?php echo urlencode($selectedFont); ?>:wght@<?php echo $fontWeights; ?>&display=swap');
<?php endif; ?>
:root[data-theme='dark'] {
  --gp-text: #e5eefc;
  --gp-muted: #a8b5cd;
  --gp-card-bg: rgba(15, 23, 42, 0.68);
  --gp-card-border: rgba(255, 255, 255, 0.12);
  --gp-nav-bg-1: #0f172a;
  --gp-nav-bg-2: #111827;
}

html,body{min-height:100%; margin:0;}
body{color:var(--gp-text);background:<?php echo $bgCss; ?>; transition: color 0.3s ease, background-color 0.3s ease; display:flex;}
body::before{content:"";position:fixed;inset:0;background:rgba(255,255,255,<?php echo h(number_format($overlayOpacity, 2, '.', '')); ?>);pointer-events:none;z-index:0; transition: background-color 0.3s ease;}
[data-theme="dark"] body::before{background:rgba(15,23,42,<?php echo h(number_format(max($overlayOpacity, 0.18), 2, '.', '')); ?>)}

/* ─── Sidebar ─── */
.sidebar-gp {
  position: fixed;
  top: 0; left: 0; bottom: 0;
  width: var(--sidebar-w);
  background: <?php echo $glass ? 'var(--gp-card-bg)' : 'var(--gp-nav-bg-1)'; ?>;
  border-right: 1px solid var(--gp-card-border);
  backdrop-filter: <?php echo $glass ? 'blur(24px)' : 'none'; ?>;
  -webkit-backdrop-filter: <?php echo $glass ? 'blur(24px)' : 'none'; ?>;
  z-index: 2000;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
  transition: transform 0.3s cubic-bezier(0.4,0,0.2,1);
}
.sidebar-gp::-webkit-scrollbar { width: 4px; }
.sidebar-gp::-webkit-scrollbar-thumb { background: rgba(128,128,128,0.2); border-radius: 4px; }

.sidebar-brand {
  display: flex; align-items: center; gap: 12px;
  padding: 22px 20px 18px;
  text-decoration: none; color: var(--gp-text);
  border-bottom: 1px solid var(--gp-card-border);
  flex-shrink: 0;
}
.sidebar-brand img { height: var(--logo-h); width: auto; max-width: 100%; object-fit: contain; border-radius: 8px; }
.sidebar-brand .dot { width: calc(var(--logo-h) * 0.35); height: calc(var(--logo-h) * 0.35); min-width: 10px; min-height: 10px; border-radius: 50%; background: linear-gradient(135deg, var(--gp-primary), var(--gp-secondary)); box-shadow: 0 0 12px rgba(37,99,235,.4); }
.sidebar-brand span { font-weight: 800; font-size: 1.05rem; letter-spacing: -0.02em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }

.sidebar-nav { flex: 1; padding: 12px 10px; display: flex; flex-direction: column; gap: 2px; }
.sidebar-section-title {
  font-size: 0.68rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.1em;
  color: var(--gp-muted); padding: 14px 12px 6px; margin-top: 4px;
}

.sidebar-link {
  display: flex; align-items: center; gap: 10px;
  padding: 10px 14px; border-radius: 12px;
  text-decoration: none; color: var(--gp-text);
  font-size: 0.88rem; font-weight: 500;
  transition: all 0.2s cubic-bezier(0.4,0,0.2,1);
  position: relative;
}
.sidebar-link:hover { background: rgba(0,0,0,0.04); color: var(--gp-text); transform: translateX(2px); }
[data-theme="dark"] .sidebar-link:hover { background: rgba(255,255,255,0.05); }
.sidebar-link-active { background: rgba(37,99,235,0.1); color: var(--gp-primary) !important; font-weight: 600; }
.sidebar-link-icon { width: 20px; text-align: center; font-size: 1rem; flex-shrink: 0; opacity: 0.8; }
.sidebar-link .meta { margin-left: auto; font-size: 0.68rem; font-weight: 600; color: var(--gp-muted); background: rgba(0,0,0,0.04); padding: 2px 7px; border-radius: 6px; }
[data-theme="dark"] .sidebar-link .meta { background: rgba(255,255,255,0.05); }

.sidebar-link-danger { color: #ef4444 !important; }
.sidebar-link-danger:hover { background: rgba(239,68,68,0.08); }

/* Sidebar footer (user profile) */
.sidebar-footer {
  flex-shrink: 0;
  padding: 14px 14px 18px;
  border-top: 1px solid var(--gp-card-border);
  display: flex; flex-direction: column; gap: 6px;
}
.sidebar-user {
  display: flex; align-items: center; gap: 10px;
  padding: 10px 12px; border-radius: 12px;
  background: rgba(0,0,0,0.02);
  text-decoration: none; color: var(--gp-text);
}
[data-theme="dark"] .sidebar-user { background: rgba(255,255,255,0.03); }
.sidebar-user-avatar {
  width: 32px; height: 32px; border-radius: 50%; flex-shrink: 0;
  display: flex; align-items: center; justify-content: center;
  font-size: 0.8rem; font-weight: 700; color: #fff;
  background: linear-gradient(135deg, var(--gp-primary), var(--gp-secondary));
  border: 1px solid rgba(255,255,255,0.2);
}
.sidebar-user-avatar img { width: 100%; height: 100%; border-radius: 50%; object-fit: cover; }
.sidebar-user-info { flex: 1; min-width: 0; }
.sidebar-user-name { font-size: 0.85rem; font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.sidebar-user-role { font-size: 0.72rem; color: var(--gp-muted); text-transform: capitalize; }

.sidebar-actions { display: flex; gap: 6px; }
.sidebar-action-btn {
  flex: 1; display: flex; align-items: center; justify-content: center; gap: 6px;
  padding: 8px; border-radius: 10px; border: 1px solid var(--gp-card-border);
  background: transparent; color: var(--gp-muted); cursor: pointer;
  font-family: inherit; font-size: 0.78rem; font-weight: 600;
  text-decoration: none; transition: all 0.2s;
}
.sidebar-action-btn:hover { background: rgba(0,0,0,0.04); color: var(--gp-text); }
[data-theme="dark"] .sidebar-action-btn:hover { background: rgba(255,255,255,0.05); color: #fff; }

/* ─── Top Bar (slim) ─── */
.topbar-gp {
  position: fixed;
  top: 0; left: var(--sidebar-w); right: 0;
  height: 56px; z-index: 1999;
  background: var(--gp-card-bg);
  border-bottom: 1px solid var(--gp-card-border);
  backdrop-filter: <?php echo $glass ? 'blur(16px)' : 'none'; ?>;
  display: flex; align-items: center; justify-content: space-between;
  padding: 0 24px; gap: 16px;
}
.topbar-search { position: relative; flex: 1; max-width: 420px; }
.topbar-search input {
  width: 100%; padding: 9px 16px 9px 36px; border-radius: 999px;
  border: 1px solid var(--gp-card-border); font-size: 0.85rem;
  background: rgba(0,0,0,0.02); color: var(--gp-text); outline: none;
  font-family: inherit; transition: all 0.2s;
}
.topbar-search input:focus { border-color: var(--gp-primary); box-shadow: 0 0 0 3px rgba(37,99,235,0.1); background: transparent; }
.topbar-search .search-icon { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); font-size: 0.82rem; color: var(--gp-muted); pointer-events: none; }
.topbar-right { display: flex; align-items: center; gap: 8px; }
.topbar-btn {
  position: relative; background: transparent; border: 1px solid var(--gp-card-border); border-radius: 10px;
  padding: 8px 10px; cursor: pointer; font-size: 1rem; color: var(--gp-muted);
  transition: all 0.2s; font-family: inherit;
}
.topbar-btn:hover { background: rgba(0,0,0,0.04); color: var(--gp-text); }
[data-theme="dark"] .topbar-btn:hover { background: rgba(255,255,255,0.05); color: #fff; }
.topbar-badge { position: absolute; top: 2px; right: 2px; background: #ef4444; color: #fff; font-size: 0.55rem; font-weight: 700; padding: 1px 4px; border-radius: 8px; line-height: 1; border: 2px solid var(--gp-card-bg); }

/* Notification dropdown */
.notif-dropdown {
  position: absolute; top: calc(100% + 8px); right: 0;
  min-width: 340px; background: var(--gp-card-bg); border: 1px solid var(--gp-card-border);
  border-radius: 16px; box-shadow: 0 20px 50px rgba(0,0,0,.15); padding: 8px;
  display: none; backdrop-filter: blur(20px); z-index: 2010; max-height: 420px; overflow-y: auto;
  animation: slideUp .2s cubic-bezier(0.4,0,0.2,1);
}
@keyframes slideUp { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.notif-dropdown.open { display: block; }
.notif-title { font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.08em; color: var(--gp-muted); padding: 8px 12px; display: flex; justify-content: space-between; align-items: center; }
.notif-title a { text-transform: none; font-size: 0.7rem; color: var(--gp-primary); text-decoration: none; }
.notif-item { display: flex; flex-direction: column; gap: 3px; padding: 10px 12px; border-radius: 10px; text-decoration: none; color: var(--gp-text); transition: background 0.2s; }
.notif-item:hover { background: rgba(0,0,0,0.03); }
.notif-item.unread { background: rgba(37,99,235,0.04); font-weight: 500; }
.notif-item-msg { font-size: 0.82rem; line-height: 1.3; }
.notif-item-time { font-size: 0.68rem; color: var(--gp-muted); }

/* Search dropdown */
.search-results-dropdown {
  position: absolute; top: calc(100% + 8px); left: 0; width: 100%;
  background: var(--gp-card-bg); border: 1px solid var(--gp-card-border);
  border-radius: 14px; box-shadow: 0 10px 40px rgba(0,0,0,0.1); padding: 8px;
  display: none; max-height: 400px; overflow-y: auto; z-index: 2001;
  backdrop-filter: blur(16px);
}

/* ─── Main Content ─── */
.main-wrap { margin-left: var(--sidebar-w); padding-top: 56px; flex: 1; min-width: 0; }
.container-gp { position: relative; z-index: 1; max-width: 1400px; margin: 0 auto; padding: 24px 28px; animation: fadeIn 0.5s ease-out; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

.card{background:var(--gp-card-bg)!important;border:1px solid var(--gp-card-border)!important;border-radius:20px!important;box-shadow:0 10px 30px rgba(0,0,0,.05);backdrop-filter:<?php echo $glass ? 'blur(16px)' : 'none'; ?>}

/* Mobile toggle */
.mobile-topbar { display: none; }

@media (max-width:1024px) {
  :root { --sidebar-w: 0px; }
  .sidebar-gp { transform: translateX(-280px); width: 280px; }
  .sidebar-gp.open { transform: translateX(0); box-shadow: 20px 0 60px rgba(0,0,0,0.2); }
  .sidebar-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.4); z-index: 1999; }
  .sidebar-overlay.open { display: block; }
  .topbar-gp { left: 0; }
  .main-wrap { margin-left: 0; }
  .mobile-topbar { display: flex; }
  .mobile-toggle {
    background: transparent; border: 1px solid var(--gp-card-border); border-radius: 10px;
    padding: 8px 10px; cursor: pointer; font-size: 1.1rem; color: var(--gp-text);
    font-family: inherit; transition: all 0.2s;
  }
}

/* ─── Mobile (≤ 768px) ─── */
@media (max-width: 768px) {
  /* Smaller container padding */
  .container-gp { padding: 16px 14px; }

  /* Smaller page title on mobile */
  .page-header-title h1 { font-size: 1.5rem !important; }
  .page-header { margin-bottom: 18px; gap: 10px; }
  .page-header-actions { width: 100%; justify-content: flex-start; flex-wrap: wrap; gap: 8px; }

  /* Notification dropdown: full width on mobile */
  .notif-dropdown { min-width: 280px; right: -60px; max-width: calc(100vw - 24px); }

  /* Topbar: hide search on very small screens, show just icon */
  .topbar-search { display: none; }
  .topbar-gp { padding: 0 12px; gap: 8px; }

  /* Cards: reduce padding */
  .card { padding: 16px !important; }
  .stat-card { padding: 16px !important; }
  .stat-value { font-size: 2rem; }

  /* Tables: always scrollable */
  .table-responsive { -webkit-overflow-scrolling: touch; }
  .table th, .table td { padding: 12px 10px; font-size: 0.82rem; }

  /* Forms */
  .form-grid { grid-template-columns: 1fr !important; gap: 14px; }
  .form-actions { flex-direction: column; gap: 8px; }
  .form-actions .btn { width: 100%; justify-content: center; }

  /* Grid overrides */
  .grid-4, .grid-3, .grid-2 { grid-template-columns: 1fr !important; gap: 12px; }

  /* Buttons: better tap target */
  .btn { min-height: 44px; }
  .btn-sm { min-height: 36px; padding: 8px 14px; }

  /* Page-header-actions: stack buttons */
  .page-header-actions { gap: 6px; }
}

/* ─── Very small (≤ 480px) ─── */
@media (max-width: 480px) {
  .container-gp { padding: 12px 10px; }
  .page-header-title h1 { font-size: 1.25rem !important; }
  .card { padding: 12px !important; border-radius: 14px !important; }

  /* 2-column stat grid on very small screens */
  .grid-4 { grid-template-columns: repeat(2, 1fr) !important; gap: 10px; }

  /* Hide text in some buttons, show only icon */
  .btn-hide-mobile-text span.btn-text { display: none; }
}
</style>
</head>
<body>
<?php if ($user): ?>
<!-- Sidebar -->
<aside class="sidebar-gp" id="sidebar">
  <a class="sidebar-brand" href="<?php echo gp_is_full_project_access_role($role) || gp_is_secretary_like_role($role) ? '/gopools/public/dashboard/index.php' : ($showEmployeeMenu ? '/gopools/public/employees/my_jobs.php' : ($showPartnerMenu ? '/gopools/public/partners/my_jobs.php' : '/gopools/public/customers/my_warranties.php')); ?>">
    <?php if ($logo !== ''): ?><img src="<?php echo h($logo); ?>" alt=""><?php else: ?><span class="dot"></span><?php endif; ?>
    <span><?php echo h($appName); ?></span>
  </a>

  <nav class="sidebar-nav">
    <?php if (gp_is_full_project_access_role($role) || gp_is_secretary_like_role($role)): ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/dashboard/') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/dashboard/index.php">
      <span class="sidebar-link-icon">📊</span> <?php echo gp_tr($pdo,'dashboard'); ?>
    </a>
    <?php endif; ?>

    <?php if ($showProjectsMenu): ?>
    <div class="sidebar-section-title"><?php echo gp_tr($pdo,'projects'); ?></div>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/projects/index') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/projects/index.php">
      <span class="sidebar-link-icon">📁</span> <?php echo gp_tr($pdo,'all_projects'); ?>
    </a>
    <?php if (gp_can_create_project($pdo)): ?>
    <a class="sidebar-link" href="/gopools/public/projects/edit.php">
      <span class="sidebar-link-icon">➕</span> <?php echo gp_tr($pdo,'new_project'); ?>
    </a>
    <?php endif; ?>
    <?php if ($_gpHasPerm('perm_dispatch')): ?>
    <a class="sidebar-link" href="/gopools/public/projects/dispatch.php">
      <span class="sidebar-link-icon">🚀</span> <?php echo gp_tr($pdo,'dispatch'); ?>
    </a>
    <?php endif; ?>
    <?php if ($_gpHasPerm('perm_assign')): ?>
    <a class="sidebar-link" href="/gopools/public/projects/send.php">
      <span class="sidebar-link-icon">📧</span> <?php echo gp_tr($pdo,'send_to_crew'); ?>
    </a>
    <?php endif; ?>
    <?php if ($_gpHasPerm('perm_warehouse')): ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/warehouse/') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/warehouse/index.php">
      <span class="sidebar-link-icon">📦</span> <?php echo gp_tr($pdo,'warehouse'); ?>
    </a>
    <?php endif; ?>
    <?php endif; ?>

    <?php if ($showPeopleMenu): ?>
    <div class="sidebar-section-title"><?php echo gp_tr($pdo,'people'); ?></div>
    <?php if ($_gpHasPerm('perm_customers')): ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/customers/index') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/customers/index.php">
      <span class="sidebar-link-icon">👥</span> <?php echo gp_tr($pdo,'customers'); ?>
    </a>
    <?php endif; ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/employees/index') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/employees/index.php">
      <span class="sidebar-link-icon">👷</span> <?php echo gp_tr($pdo,'employees'); ?>
    </a>
    <?php if (file_exists(__DIR__ . '/../employees/timeclock.php')): ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/timeclock') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/employees/timeclock.php">
      <span class="sidebar-link-icon">⏱️</span> <?php echo gp_tr($pdo,'time_clock'); ?>
    </a>
    <?php endif; ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/partners/index') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/partners/index.php">
      <span class="sidebar-link-icon">🤝</span> <?php echo gp_tr($pdo,'partners'); ?>
    </a>
    <?php endif; ?>

    <?php if ($showEmployeeMenu): ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/employees/my_jobs') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/employees/my_jobs.php">
      <span class="sidebar-link-icon">🔧</span> <?php echo gp_tr($pdo,'my_jobs'); ?>
    </a>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/employees/completed') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/employees/completed.php">
      <span class="sidebar-link-icon">✅</span> <?php echo gp_tr($pdo,'completed_projects'); ?>
    </a>
    <?php if (file_exists(__DIR__ . '/../employees/timeclock.php')): ?>
    <a class="sidebar-link" href="/gopools/public/employees/timeclock.php">
      <span class="sidebar-link-icon">⏱️</span> <?php echo gp_tr($pdo,'time_clock'); ?>
    </a>
    <?php endif; ?>
    <?php endif; ?>

    <?php if ($showPartnerMenu): ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/partners/my_jobs') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/partners/my_jobs.php">
      <span class="sidebar-link-icon">🏠</span> Κεντρική
    </a>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/partners/completed') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/partners/completed.php">
      <span class="sidebar-link-icon">✅</span> <?php echo gp_tr($pdo,'completed_projects'); ?>
    </a>
    <?php endif; ?>

    <?php if ($showCustomerMenu): ?>
    <a class="sidebar-link sidebar-link-active" href="/gopools/public/customers/my_warranties.php">
      <span class="sidebar-link-icon">📋</span> <?php echo gp_tr($pdo,'my_warranties'); ?>
    </a>
    <?php endif; ?>

    <?php if ($showOperationsMenu): ?>
    <div class="sidebar-section-title"><?php echo gp_tr($pdo,'operations'); ?></div>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/vehicles/') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/vehicles/index.php">
      <span class="sidebar-link-icon">🚛</span> <?php echo gp_tr($pdo,'vehicles'); ?>
    </a>
    <?php if ($_gpHasPerm('perm_reports')): ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/reports/') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/reports/index.php">
      <span class="sidebar-link-icon">📈</span> <?php echo gp_tr($pdo,'reports'); ?>
    </a>
    <?php endif; ?>
    <a class="sidebar-link <?php echo strpos($_SERVER['REQUEST_URI'] ?? '', '/inbox/') !== false ? 'sidebar-link-active' : ''; ?>" href="/gopools/public/inbox/index.php">
      <span class="sidebar-link-icon">📬</span> <?php echo gp_tr($pdo,'inbox'); ?>
    </a>
    <?php if ($_gpHasPerm('perm_payroll') && file_exists(__DIR__ . '/../reports/monthly_payroll.php')): ?>
    <a class="sidebar-link" href="/gopools/public/reports/monthly_payroll.php">
      <span class="sidebar-link-icon">💰</span> <?php echo gp_tr($pdo,'payroll'); ?>
    </a>
    <?php endif; ?>
    <?php endif; ?>

    <?php if ($isAdminSettingsUser): ?>
    <div class="sidebar-section-title"><?php echo gp_tr($pdo,'settings'); ?></div>
    <a class="sidebar-link" href="/gopools/public/settings/index.php">
      <span class="sidebar-link-icon">⚙️</span> <?php echo gp_tr($pdo,'settings_center'); ?>
    </a>
    <a class="sidebar-link" href="/gopools/public/settings/logs.php">
      <span class="sidebar-link-icon">📋</span> <?php echo gp_tr($pdo,'system_logs'); ?>
    </a>
    <a class="sidebar-link" href="/gopools/public/settings/branding.php">
      <span class="sidebar-link-icon">🎨</span> <?php echo gp_tr($pdo,'branding'); ?>
    </a>
    <a class="sidebar-link" href="/gopools/public/settings/users.php">
      <span class="sidebar-link-icon">🔑</span> <?php echo gp_tr($pdo,'users'); ?>
    </a>
    <a class="sidebar-link" href="/gopools/scripts/fix_permissions.php?force=1">
      <span class="sidebar-link-icon">🛡️</span> <?php echo gp_tr($pdo,'fix_permissions'); ?>
    </a>
    <?php endif; ?>
  </nav>

  <!-- Sidebar Footer: User -->
  <div class="sidebar-footer">
    <a class="sidebar-user" href="/gopools/public/auth/profile.php">
      <div class="sidebar-user-avatar">
        <?php if (!empty($user['avatar_path'])): ?>
          <img src="<?php echo h($user['avatar_path']); ?>" alt="">
        <?php else: ?>
          <?php echo strtoupper(substr($user['username'] ?? 'U', 0, 1)); ?>
        <?php endif; ?>
      </div>
      <div class="sidebar-user-info">
        <div class="sidebar-user-name"><?php echo h($user['username'] ?? 'User'); ?></div>
        <div class="sidebar-user-role"><?php echo h($role ?: 'user'); ?></div>
      </div>
    </a>
    <div class="sidebar-actions">
      <button class="sidebar-action-btn" type="button" data-theme-toggle title="Toggle theme">◑ <?php echo gp_tr($pdo,'theme'); ?></button>
      <button class="sidebar-action-btn" id="langToggleBtn" type="button" title="Switch language">
        <?php echo $_gp_lang === 'el' ? '🇬🇧 EN' : '🇬🇷 ΕΛ'; ?>
      </button>
      <a class="sidebar-action-btn sidebar-link-danger" href="/gopools/public/auth/logout.php" style="color:#ef4444;">⏻ <?php echo gp_tr($pdo,'logout'); ?></a>
    </div>
  </div>
</aside>

<!-- Overlay for mobile -->
<div class="sidebar-overlay" id="sidebar-overlay"></div>

<!-- Top Bar -->
<header class="topbar-gp">
  <div class="mobile-topbar" style="gap:10px;align-items:center;">
    <button class="mobile-toggle" type="button" id="mobile-toggle-btn" aria-label="Menu">☰</button>
  </div>

  <div class="topbar-search">
    <span class="search-icon">🔍</span>
    <input type="search" placeholder="Search projects, customers... (press /)" id="global-search-input" autocomplete="off">
    <div class="search-results-dropdown" id="global-search-results"></div>
  </div>

  <div class="topbar-right">
    <!-- Mobile search toggle (only visible on small screens) -->
    <button class="topbar-btn" id="mobile-search-btn" type="button" aria-label="Search"
      style="display:none;" onclick="document.getElementById('mobile-search-bar').classList.toggle('open');">🔍</button>

    <!-- Notifications -->
    <div style="position:relative;" id="notif-wrap">
      <button class="topbar-btn btn-bell" type="button" id="notif-toggle" aria-label="<?php echo gp_tr($pdo,'notifications'); ?>">
        🔔<?php if ($unreadNotifications > 0): ?><span class="topbar-badge"><?php echo $unreadNotifications; ?></span><?php endif; ?>
      </button>
      <div class="notif-dropdown" id="notif-dropdown">
        <div class="notif-title">
          <span><?php echo gp_tr($pdo,'notifications'); ?></span>
          <div style="display:flex;gap:10px;">
            <?php if ($unreadNotifications > 0): ?><a href="javascript:void(0)" id="mark-all-read-btn"><?php echo gp_tr($pdo,'mark_all_read'); ?></a><?php endif; ?>
            <?php if ($userNotifications): ?><a href="javascript:void(0)" id="clear-all-notif-btn" style="color:var(--gp-muted);"><?php echo gp_tr($pdo,'clear_all'); ?></a><?php endif; ?>
          </div>
        </div>
        <?php if (!$userNotifications): ?>
          <div style="padding:16px;text-align:center;color:var(--gp-muted);font-size:0.82rem;"><?php echo gp_tr($pdo,'no_notifications'); ?></div>
        <?php else: ?>
          <?php foreach ($userNotifications as $n): ?>
            <a href="<?php echo h($n['link_url'] ?: '#'); ?>" class="notif-item <?php echo $n['is_read'] ? '' : 'unread'; ?>" data-notification-id="<?php echo $n['id']; ?>">
              <span class="notif-item-msg"><?php echo h($n['message']); ?></span>
              <span class="notif-item-time"><?php echo h(date('M d, H:i', strtotime($n['created_at']))); ?></span>
            </a>
          <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
  </div>
</header>

<!-- Mobile Search Bar (slides in below topbar) -->
<div id="mobile-search-bar" style="display:none;position:fixed;top:56px;left:0;right:0;z-index:1998;padding:10px 14px;background:var(--gp-nav-bg-1);border-bottom:1px solid var(--gp-card-border);backdrop-filter:blur(16px);">
  <div class="topbar-search" style="max-width:100%;display:block;">
    <span class="search-icon">🔍</span>
    <input type="search" placeholder="Αναζήτηση..." id="mobile-search-input" autocomplete="off" style="width:100%;padding:10px 16px 10px 36px;border-radius:999px;border:1px solid var(--gp-card-border);background:rgba(0,0,0,0.02);color:var(--gp-text);font-family:inherit;font-size:0.9rem;outline:none;">
  </div>
</div>

<style>
#mobile-search-bar.open { display: block !important; }
@media (max-width: 768px) {
  #mobile-search-btn { display: flex !important; }
  .topbar-gp .topbar-search { display: none !important; }
}
</style>
<?php endif; ?>

<div class="main-wrap">
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
  try {
    flatpickr('input[type="date"]', {
      altInput: true,
      altFormat: "d/m/Y",
      dateFormat: "Y-m-d",
      locale: "default",
      disableMobile: true
    });
  } catch(e) { console.warn('Flatpickr init failed:', e); }
  // Mobile sidebar toggle
  var sidebar = document.getElementById('sidebar');
  var overlay = document.getElementById('sidebar-overlay');
  var mobileBtn = document.getElementById('mobile-toggle-btn');

  function toggleSidebar() {
    sidebar && sidebar.classList.toggle('open');
    overlay && overlay.classList.toggle('open');
  }
  if (mobileBtn) mobileBtn.addEventListener('click', toggleSidebar);
  if (overlay) overlay.addEventListener('click', toggleSidebar);

  // Notification toggle
  var notifToggle = document.getElementById('notif-toggle');
  var notifDropdown = document.getElementById('notif-dropdown');
  if (notifToggle && notifDropdown) {
    notifToggle.addEventListener('click', function(e) {
      e.stopPropagation();
      notifDropdown.classList.toggle('open');
    });
    document.addEventListener('click', function(e) {
      if (!notifDropdown.contains(e.target) && e.target !== notifToggle) {
        notifDropdown.classList.remove('open');
      }
    });
  }

  // Mark all read
  var markAllBtn = document.getElementById('mark-all-read-btn');
  if (markAllBtn) {
    markAllBtn.addEventListener('click', function(e) {
      e.stopPropagation(); e.preventDefault();
      fetch('/gopools/public/api/notifications_read.php', {
        method: 'POST', headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({mark_all: true})
      }).then(r => r.json()).then(res => { if (res.ok) window.location.reload(); });
    });
  }

  // Read single notification
  document.querySelectorAll('a[data-notification-id]').forEach(function(el) {
    el.addEventListener('click', function(e) {
      if (el.classList.contains('unread')) {
        e.preventDefault();
        var nid = el.getAttribute('data-notification-id');
        var href = el.getAttribute('href');
        fetch('/gopools/public/api/notifications_read.php', {
          method: 'POST', headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({id: nid})
        }).then(r => r.json()).then(res => {
          if (href && href !== '#') window.location.href = href;
          else window.location.reload();
        });
      }
    });
  });

  // Clear all
  var clearAllBtn = document.getElementById('clear-all-notif-btn');
  if (clearAllBtn) {
    clearAllBtn.addEventListener('click', function(e) {
      e.stopPropagation(); e.preventDefault();
      fetch('/gopools/public/api/notifications_clear.php', {
        method: 'POST', headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({clear_all: true})
      }).then(r => r.json()).then(res => { if (res.ok) window.location.reload(); });
    });
  }

  // Language toggle
  var langBtn = document.getElementById('langToggleBtn');
  if (langBtn) {
    langBtn.addEventListener('click', function() {
      var currentLang = '<?php echo $_gp_lang; ?>';
      var newLang = currentLang === 'el' ? 'en' : 'el';
      fetch('/gopools/public/api/save_user_lang.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({lang: newLang})
      }).then(function() {
        // Reload keeping same URL but stripping old lang param
        var url = new URL(window.location.href);
        url.searchParams.set('lang', newLang);
        window.location.href = url.toString();
      });
    });
  }

  // ESC to close
  document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
      if (notifDropdown) notifDropdown.classList.remove('open');
      if (sidebar) sidebar.classList.remove('open');
      if (overlay) overlay.classList.remove('open');
    }
  });
});
</script>
<div class="container-gp">
