<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
require_once __DIR__ . '/../../app/core/theme.php';
require_once __DIR__ . '/../../app/core/project_permissions.php';
require_once __DIR__ . '/../../app/core/portal_auth.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);
$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'] ?? '';

$isDark = $themeMode === 'dark';
$textColor = $isDark ? '#e5eefc' : '#0f172a';
$mutedColor = $isDark ? '#a8b5cd' : '#475569';
$cardBg = $isDark ? 'rgba(15,23,42,.68)' : 'rgba(255,255,255,.78)';
$cardBorder = $isDark ? 'rgba(255,255,255,.10)' : 'rgba(15,23,42,.08)';
$navBg1 = $isDark ? '#0f172a' : '#ffffff';
$navBg2 = $isDark ? '#111827' : '#f8fafc';
$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';
?>
<!doctype html>
<html lang="en" data-theme="<?php echo h($themeMode); ?>">
<head>
<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="/public/assets/css/app.css">
<style>
:root{--gp-primary:<?php echo h($primary); ?>;--gp-secondary:<?php echo h($secondary); ?>;--gp-text:<?php echo h($textColor); ?>;--gp-muted:<?php echo h($mutedColor); ?>;--gp-card-bg:<?php echo h($cardBg); ?>;--gp-card-border:<?php echo h($cardBorder); ?>;--gp-nav-bg-1:<?php echo h($navBg1); ?>;--gp-nav-bg-2:<?php echo h($navBg2); ?>;}
html,body{min-height:100%}
body{margin:0;color:var(--gp-text);background:<?php echo $bgCss; ?>}
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}
[data-theme="dark"] body::before{background:rgba(15,23,42,<?php echo h(number_format(max($overlayOpacity, 0.18), 2, '.', '')); ?>)}
.navbar-gp{position:sticky;top:0;z-index:2000;background:linear-gradient(135deg,var(--gp-nav-bg-1),var(--gp-nav-bg-2));border-bottom:1px solid var(--gp-card-border);box-shadow:0 12px 30px rgba(0,0,0,.10);backdrop-filter:blur(16px)}
.navbar-gp .inner{max-width:1400px;margin:0 auto;padding:12px 18px;display:flex;align-items:center;justify-content:space-between;gap:14px}
.brand{display:flex;align-items:center;gap:10px;font-weight:800;color:var(--gp-text);text-decoration:none;white-space:nowrap}
.brand img{width:34px;height:34px;object-fit:contain;border-radius:10px}
.brand .dot{width:10px;height:10px;border-radius:999px;background:linear-gradient(135deg,var(--gp-primary),var(--gp-secondary));box-shadow:0 0 0 4px rgba(37,99,235,.12)}
.nav-shell{display:flex;align-items:center;gap:10px;flex:1;justify-content:flex-end}
.nav-links{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.nav-link,.theme-toggle,.nav-item-dropdown>button{color:var(--gp-text);text-decoration:none;background:transparent;border:1px solid transparent;border-radius:12px;padding:9px 12px;cursor:pointer;transition:.18s ease}
.nav-link:hover,.theme-toggle:hover,.nav-item-dropdown>button:hover,.nav-item-dropdown.open>button{background:rgba(255,255,255,.08);border-color:var(--gp-card-border)}
.nav-link-strong{background:rgba(37,99,235,.12);border-color:rgba(37,99,235,.20)}
.nav-item-dropdown{position:relative}
.caret{margin-left:8px;font-size:.82rem;opacity:.78}
.nav-dropdown-menu{position:absolute;top:calc(100% + 10px);left:0;min-width:270px;background:<?php echo $glass ? 'rgb(198 207 227 / 92%)' : ($isDark ? '#0f172a' : '#ffffff'); ?>;border:1px solid var(--gp-card-border);border-radius:16px;box-shadow:0 20px 45px rgba(0,0,0,.18);padding:8px;display:none;backdrop-filter:<?php echo $glass ? 'blur(18px)' : 'none'; ?>}
.nav-item-dropdown.open .nav-dropdown-menu{display:block}
.nav-dropdown-title{font-size:.76rem;text-transform:uppercase;letter-spacing:.08em;color:var(--gp-muted);padding:6px 10px 8px}
.nav-dropdown-menu a{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:11px 12px;border-radius:12px;color:var(--gp-text);text-decoration:none}
.nav-dropdown-menu a:hover{background:rgb(37 99 235 / 80%)}
.nav-dropdown-menu a .meta{font-size:.8rem;color:var(--gp-muted)}
.nav-mobile-toggle{display:none;width:42px;height:42px;border-radius:12px;border:1px solid var(--gp-card-border);background:transparent;color:var(--gp-text);cursor:pointer}
.container-gp{position:relative;z-index:1;max-width:1400px;margin:0 auto;padding:18px}
.card{background:var(--gp-card-bg)!important;border:1px solid var(--gp-card-border)!important;border-radius:18px!important;box-shadow:0 18px 40px rgba(15,23,42,.08);backdrop-filter:<?php echo $glass ? 'blur(18px)' : 'none'; ?>}
@media (max-width:980px){
  .navbar-gp .inner{align-items:flex-start}
  .nav-mobile-toggle{display:inline-flex;align-items:center;justify-content:center}
  .nav-shell{flex-direction:column;align-items:stretch;width:100%}
  .nav-links{display:none;width:100%;flex-direction:column;align-items:stretch;gap:8px;padding-top:6px}
  .nav-shell.open .nav-links{display:flex}
  .nav-link,.theme-toggle,.nav-item-dropdown>button{width:100%;text-align:left}
  .nav-item-dropdown{width:100%}
  .nav-dropdown-menu{position:static;min-width:0;width:100%;margin-top:8px}
}
</style>
</head>
<body>
<?php if ($user): ?>
<nav class="navbar-gp">
  <div class="inner">
    <a class="brand" href="<?php echo gp_is_full_project_access_role($role) || gp_is_secretary_like_role($role) ? '/public/dashboard/index.php' : ($showEmployeeMenu ? '/public/employees/my_jobs.php' : ($showPartnerMenu ? '/public/partners/my_jobs.php' : '/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>
    <div class="nav-shell" data-nav-shell>
      <button class="nav-mobile-toggle" type="button" data-mobile-nav-toggle aria-label="Open menu">☰</button>
      <div class="nav-links">
        <?php if (gp_is_full_project_access_role($role) || gp_is_secretary_like_role($role)): ?>
        <a class="nav-link nav-link-strong" href="/public/dashboard/index.php">Dashboard</a>
        <?php endif; ?>

        <?php if ($showProjectsMenu): ?>
        <div class="nav-item-dropdown" data-nav-dropdown>
          <button type="button">Projects <span class="caret">▾</span></button>
          <div class="nav-dropdown-menu">
            <div class="nav-dropdown-title">Projects</div>
            <a href="/public/projects/index.php"><span>All Projects</span><span class="meta">list</span></a>
            <?php if (gp_can_create_project($pdo)): ?><a href="/public/projects/edit.php"><span>New Project</span><span class="meta">create</span></a><?php endif; ?>
            <a href="/public/projects/dispatch.php"><span>Dispatch</span><span class="meta">assign</span></a>
            <a href="/public/projects/send.php"><span>Send to Crew</span><span class="meta">email</span></a>
          </div>
        </div>
        <?php endif; ?>

        <?php if ($showPeopleMenu): ?>
        <div class="nav-item-dropdown" data-nav-dropdown>
          <button type="button">People <span class="caret">▾</span></button>
          <div class="nav-dropdown-menu">
            <div class="nav-dropdown-title">People & Portals</div>
            <a href="/public/customers/index.php"><span>Customers</span><span class="meta">clients</span></a>
            <a href="/public/customers/my_warranties.php"><span>Customer Portal</span><span class="meta">warranties</span></a>
            <a href="/public/employees/index.php"><span>Employees</span><span class="meta">team</span></a>
            <a href="/public/employees/my_jobs.php"><span>Employee Portal</span><span class="meta">jobs</span></a>
            <?php if (file_exists(__DIR__ . '/../employees/timeclock.php')): ?><a href="/public/employees/timeclock.php"><span>Time Clock</span><span class="meta">hours</span></a><?php endif; ?>
            <a href="/public/partners/index.php"><span>Partners</span><span class="meta">external</span></a>
            <a href="/public/partners/my_jobs.php"><span>Partner Portal</span><span class="meta">jobs</span></a>
          </div>
        </div>
        <?php endif; ?>

        <?php if ($showEmployeeMenu): ?>
        <a class="nav-link nav-link-strong" href="/public/employees/my_jobs.php">Employee Portal</a>
        <?php if (file_exists(__DIR__ . '/../employees/timeclock.php')): ?><a class="nav-link" href="/public/employees/timeclock.php">Time Clock</a><?php endif; ?>
        <?php endif; ?>

        <?php if ($showPartnerMenu): ?>
        <a class="nav-link nav-link-strong" href="/public/partners/my_jobs.php">Partner Portal</a>
        <?php endif; ?>

        <?php if ($showCustomerMenu): ?>
        <a class="nav-link nav-link-strong" href="/public/customers/my_warranties.php">Customer Portal</a>
        <?php endif; ?>

        <?php if ($showOperationsMenu): ?>
        <div class="nav-item-dropdown" data-nav-dropdown>
          <button type="button">Operations <span class="caret">▾</span></button>
          <div class="nav-dropdown-menu">
            <div class="nav-dropdown-title">Operations</div>
            <a href="/public/vehicles/index.php"><span>Vehicles</span><span class="meta">fleet</span></a>
            <a href="/public/reports/index.php"><span>Reports</span><span class="meta">export</span></a>
            <a href="/public/inbox/index.php"><span>Inbox</span><span class="meta">mail</span></a>
            <?php if (file_exists(__DIR__ . '/../reports/monthly_payroll.php')): ?><a href="/public/reports/monthly_payroll.php"><span>Monthly Payroll</span><span class="meta">hours</span></a><?php endif; ?>
          </div>
        </div>
        <?php endif; ?>

        <?php if ($isAdminSettingsUser): ?>
        <div class="nav-item-dropdown" data-nav-dropdown>
          <button type="button">Settings <span class="caret">▾</span></button>
          <div class="nav-dropdown-menu">
            <div class="nav-dropdown-title">System</div>
            <a href="/public/settings/index.php"><span>Settings Center</span><span class="meta">system</span></a>
            <a href="/public/settings/branding.php"><span>Branding & Theme</span><span class="meta">ui</span></a>
            <a href="/public/settings/email_to_project.php"><span>Email to Project</span><span class="meta">inbox</span></a>
            <a href="/public/settings/project_statuses.php"><span>Project Statuses</span><span class="meta">workflow</span></a>
            <a href="/public/settings/users.php"><span>Users Management</span><span class="meta">accounts</span></a>
            <a href="/public/settings/user_invites.php"><span>Users / Invites</span><span class="meta">access</span></a>
            <a href="/public/settings/smtp.php"><span>SMTP Settings</span><span class="meta">mail</span></a>
          </div>
        </div>
        <?php endif; ?>

        <button class="theme-toggle" type="button" data-theme-toggle>Theme</button>
        <a class="nav-link" href="/public/auth/logout.php">Logout (<?php echo h($user['username'] ?? 'user'); ?>)</a>
      </div>
    </div>
  </div>
</nav>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var shell=document.querySelector('[data-nav-shell]');
  var mobileToggle=document.querySelector('[data-mobile-nav-toggle]');
  var dropdowns=document.querySelectorAll('[data-nav-dropdown]');

  if (mobileToggle && shell){
    mobileToggle.addEventListener('click', function(e){
      e.stopPropagation();
      shell.classList.toggle('open');
    });
  }

  dropdowns.forEach(function(dd){
    var btn=dd.querySelector('button');
    if(!btn) return;
    btn.addEventListener('click', function(e){
      e.stopPropagation();
      dropdowns.forEach(function(other){ if(other!==dd) other.classList.remove('open'); });
      dd.classList.toggle('open');
    });
  });

  document.addEventListener('click', function(){
    dropdowns.forEach(function(dd){ dd.classList.remove('open'); });
  });

  document.addEventListener('keydown', function(e){
    if(e.key==='Escape'){
      dropdowns.forEach(function(dd){ dd.classList.remove('open'); });
      if(shell) shell.classList.remove('open');
    }
  });
});
</script>
<div class="container-gp">
