<?php
/**
 * CSR Manager Portal — Shared Layout
 * Every page in csr_manager/ includes this file via:
 *   $content = ob_get_clean();
 *   include __DIR__ . '/layout.php';
 */
if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/app_helpers.php';
require_once __DIR__ . '/../includes/csr_report_helpers.php';

// ── Auth: only csr_manager role ──────────────────────────────
if (!isset($_SESSION['csr_id'])) {
    header('Location: ../login.php');
    exit();
}

$_db_layout = (new Database())->getConnection();
ensureCsrRoleSchema($_db_layout);
$_mgr_role = getCsrRoleForReport($_db_layout, (int)$_SESSION['csr_id']);

if ($_mgr_role !== 'csr_manager') {
    // Team leaders & regular CSRs go back to their own portal
    header('Location: ../csr/dashboard.php');
    exit();
}

// ── Manager info ────────────────────────────────────────────
$_mgrStmt = $_db_layout->prepare("SELECT first_name, last_name FROM csr_users WHERE id = :id LIMIT 1");
$_mgrStmt->execute([':id' => $_SESSION['csr_id']]);
$_mgr = $_mgrStmt->fetch(PDO::FETCH_ASSOC);
$mgrFullName = trim(($_mgr['first_name'] ?? '') . ' ' . ($_mgr['last_name'] ?? ''));
$mgrInitials  = strtoupper(substr($_mgr['first_name'] ?? 'C', 0, 1) . substr($_mgr['last_name'] ?? 'M', 0, 1));

// ── Notification count ───────────────────────────────────────
$_nStmt = $_db_layout->prepare("SELECT COUNT(*) FROM csr_notifications WHERE csr_id = :id AND is_read = 0");
$_nStmt->execute([':id' => $_SESSION['csr_id']]);
$mgrNotifCount = (int)$_nStmt->fetchColumn();

// ── Current page (for nav active state) ─────────────────────
$_currentPage = basename($_SERVER['PHP_SELF']);

// Title fallback
$title = $title ?? 'Manager';
$extra_styles  = $extra_styles  ?? '';
$extra_scripts = $extra_scripts ?? '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSR Manager — <?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Space+Grotesk:wght@500;600;700;800&display=swap">
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>

<link rel="stylesheet" href="../assets/ushs-global-theme.css">
<link rel="stylesheet" href="../assets/ushs-header.css">

<style>
/* ============================================================
   CSR Manager Portal — Design Tokens & Base Layout
   Consistent deep-navy theme that never changes between pages.
   ============================================================ */
:root {
  --cm-bg:       oklch(0.13 0.035 260);
  --cm-bg2:      oklch(0.11 0.032 261);
  --cm-card:     oklch(0.18 0.038 262);
  --cm-card2:    oklch(0.16 0.035 261);
  --cm-border:   oklch(0.98 0.005 250 / 0.12);
  --cm-border2:  oklch(0.98 0.005 250 / 0.20);
  --cm-text:     oklch(0.98 0.005 250);
  --cm-muted:    oklch(0.72 0.02 260);
  --cm-blue:     oklch(0.62 0.22 255);
  --cm-cyan:     oklch(0.72 0.18 195);
  --cm-green:    oklch(0.72 0.18 155);
  --cm-purple:   oklch(0.72 0.18 300);
  --cm-yellow:   oklch(0.82 0.16 85);
  --cm-red:      oklch(0.68 0.22 27);
  --cm-header-h: 62px;
  --cm-nav-h:    58px;
}

*, *::before, *::after { box-sizing: border-box; }

html, body {
  margin: 0;
  padding: 0;
  min-height: 100%;
  font-family: 'Inter', system-ui, sans-serif;
  background:
    radial-gradient(circle at 18% 0%, oklch(0.62 0.22 255 / 0.13), transparent 34%),
    linear-gradient(135deg, var(--cm-bg) 0%, var(--cm-bg2) 100%) fixed;
  color: var(--cm-text);
  overflow-x: hidden;
}

/* Subtle grid pattern */
body::before {
  content: "";
  position: fixed;
  inset: 0;
  pointer-events: none;
  z-index: -1;
  background-image:
    linear-gradient(oklch(0.98 0.005 250 / 0.022) 1px, transparent 1px),
    linear-gradient(90deg, oklch(0.98 0.005 250 / 0.016) 1px, transparent 1px);
  background-size: 44px 44px;
}

/* ── Main content area ─────────────────────────────────────── */
.cm-main {
  padding: calc(var(--cm-header-h) + 16px) 20px calc(var(--cm-nav-h) + 20px);
  min-height: 100vh;
}

/* ── Cards / Panels ────────────────────────────────────────── */
.cm-card {
  background: var(--cm-card);
  border: 1px solid var(--cm-border);
  border-radius: 16px;
  padding: 16px;
}

.cm-card--hover {
  transition: border-color .2s, transform .2s;
}
.cm-card--hover:hover {
  border-color: var(--cm-border2);
  transform: translateY(-2px);
}

.cm-card__title {
  font-family: 'Space Grotesk', system-ui, sans-serif;
  font-size: .88rem;
  font-weight: 700;
  color: var(--cm-muted);
  margin-bottom: 12px;
  letter-spacing: .02em;
}

/* ── Buttons ───────────────────────────────────────────────── */
.cm-btn {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 8px 14px;
  border-radius: 10px;
  border: 1px solid var(--cm-border);
  background: var(--cm-card);
  color: var(--cm-text) !important;
  font-size: .82rem;
  font-weight: 700;
  text-decoration: none !important;
  cursor: pointer;
  transition: background .18s, border-color .18s;
  white-space: nowrap;
}
.cm-btn:hover {
  background: oklch(0.62 0.22 255 / 0.16);
  border-color: oklch(0.62 0.22 255 / 0.45);
}
.cm-btn--primary {
  background: var(--cm-blue);
  border-color: transparent;
  color: #fff !important;
}
.cm-btn--primary:hover {
  background: oklch(0.68 0.22 255);
  border-color: transparent;
}
.cm-btn--active {
  background: oklch(0.62 0.22 255 / 0.22);
  border-color: oklch(0.62 0.22 255 / 0.55);
}
.cm-back-btn {
  width: 36px; height: 36px;
  border-radius: 10px;
  border: 1px solid var(--cm-border);
  background: oklch(0.98 0.005 250 / 0.07);
  color: var(--cm-text) !important;
  display:inline-flex; align-items:center; justify-content:center;
  text-decoration:none !important;
  margin-left:8px;
}
.cm-back-btn:hover { background: oklch(0.62 0.22 255 / 0.16); border-color: oklch(0.62 0.22 255 / 0.45); }

/* ── Tables ────────────────────────────────────────────────── */
.cm-table-wrap {
  overflow-x: auto;
  border-radius: 12px;
}

.cm-table {
  width: 100%;
  border-collapse: collapse;
  color: var(--cm-text);
  font-size: .86rem;
}

.cm-table thead th {
  background: oklch(0.98 0.005 250 / 0.06);
  color: var(--cm-muted);
  font-weight: 700;
  font-size: .75rem;
  text-transform: uppercase;
  letter-spacing: .06em;
  padding: 10px 14px;
  border-bottom: 1px solid var(--cm-border);
  white-space: nowrap;
}

.cm-table tbody tr {
  border-bottom: 1px solid var(--cm-border);
  transition: background .15s;
}

.cm-table tbody tr:hover {
  background: oklch(0.62 0.22 255 / 0.07);
}

.cm-table tbody td {
  padding: 10px 14px;
  vertical-align: middle;
}

/* ── Badges ────────────────────────────────────────────────── */
.cm-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  padding: 3px 8px;
  border-radius: 999px;
  font-size: .72rem;
  font-weight: 800;
}

.cm-badge--blue   { background: oklch(0.62 0.22 255 / 0.18); color: var(--cm-blue); border: 1px solid oklch(0.62 0.22 255 / 0.35); }
.cm-badge--green  { background: oklch(0.72 0.18 155 / 0.18); color: var(--cm-green); border: 1px solid oklch(0.72 0.18 155 / 0.35); }
.cm-badge--yellow { background: oklch(0.82 0.16 85 / 0.18);  color: var(--cm-yellow); border: 1px solid oklch(0.82 0.16 85 / 0.35); }
.cm-badge--red    { background: oklch(0.68 0.22 27 / 0.18);  color: var(--cm-red); border: 1px solid oklch(0.68 0.22 27 / 0.35); }
.cm-badge--muted  { background: oklch(0.98 0.005 250 / 0.08); color: var(--cm-muted); border: 1px solid var(--cm-border); }

/* ── Forms ─────────────────────────────────────────────────── */
.cm-input,
.cm-select {
  background: oklch(0.98 0.005 250 / 0.08) !important;
  border: 1px solid var(--cm-border) !important;
  border-radius: 10px !important;
  color: var(--cm-text) !important;
  padding: 8px 12px;
  font-size: .86rem;
  width: 100%;
  transition: border-color .18s;
}

.cm-input::placeholder { color: var(--cm-muted) !important; }
.cm-input:focus, .cm-select:focus {
  border-color: var(--cm-blue) !important;
  outline: none;
  box-shadow: 0 0 0 3px oklch(0.62 0.22 255 / 0.15) !important;
}

.cm-select option {
  background: oklch(0.20 0.04 262);
  color: var(--cm-text);
}

/* ── Skeleton loading ──────────────────────────────────────── */
.cm-skeleton {
  background: linear-gradient(90deg, var(--cm-card) 25%, oklch(0.20 0.04 260) 50%, var(--cm-card) 75%);
  background-size: 200% 100%;
  animation: cm-shine 1.4s ease infinite;
  border-radius: 8px;
}

@keyframes cm-shine {
  0%   { background-position: 200% 0; }
  100% { background-position: -200% 0; }
}

/* ── Toast ─────────────────────────────────────────────────── */
.cm-toast-container {
  position: fixed;
  bottom: calc(var(--cm-nav-h) + 12px);
  right: 16px;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* ── Sidebar overlay ───────────────────────────────────────── */
.cm-sidebar-overlay {
  display: none;
  position: fixed;
  inset: 0;
  background: oklch(0 0 0 / .58);
  backdrop-filter: blur(3px);
  z-index: 2000;
}

.cm-sidebar {
  position: fixed;
  top: 0;
  left: -310px;
  width: min(290px, 88vw);
  height: 100%;
  background: linear-gradient(180deg, oklch(0.20 0.04 262), oklch(0.14 0.034 261));
  border-right: 1px solid var(--cm-border2);
  box-shadow: 18px 0 55px oklch(0 0 0 / .45);
  z-index: 2001;
  transition: left .26s cubic-bezier(.4,0,.2,1);
  overflow-y: auto;
}

.cm-sidebar.open { left: 0; }

.cm-sidebar__hdr {
  padding: 18px 16px 14px;
  border-bottom: 1px solid var(--cm-border);
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: oklch(0.98 0.005 250 / 0.04);
}

.cm-sidebar__hdr-brand {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cm-sidebar__hdr-icon {
  width: 34px; height: 34px;
  border-radius: 10px;
  background: oklch(0.62 0.22 255 / 0.18);
  border: 1px solid oklch(0.62 0.22 255 / 0.35);
  display: flex; align-items: center; justify-content: center;
  flex-shrink: 0;
}

.cm-sidebar__hdr-name  { font-family: 'Space Grotesk', system-ui, sans-serif; font-weight: 800; font-size: .9rem; }
.cm-sidebar__hdr-role  { font-size: .68rem; color: var(--cm-muted); }

.cm-sidebar__close {
  width: 32px; height: 32px;
  border-radius: 8px;
  border: 1px solid var(--cm-border);
  background: oklch(0.98 0.005 250 / 0.07);
  color: var(--cm-text);
  display: flex; align-items: center; justify-content: center;
  cursor: pointer; flex-shrink: 0; font-size: 14px;
}

.cm-sidebar__nav { padding: 10px; }

.cm-sidebar__item {
  display: flex;
  align-items: center;
  gap: 11px;
  padding: 11px 12px;
  border-radius: 12px;
  color: var(--cm-text) !important;
  text-decoration: none !important;
  font-weight: 700;
  font-size: .88rem;
  margin-bottom: 3px;
  border: 1px solid transparent;
  transition: background .18s, border-color .18s, transform .18s;
}

.cm-sidebar__item i { color: var(--cm-blue); width: 20px; text-align: center; flex-shrink: 0; }
.cm-sidebar__item:hover,
.cm-sidebar__item.active {
  background: oklch(0.62 0.22 255 / 0.14);
  border-color: oklch(0.62 0.22 255 / 0.30);
  transform: translateX(3px);
}
.cm-sidebar__item.logout { color: var(--cm-red) !important; }
.cm-sidebar__item.logout i { color: var(--cm-red) !important; }

.cm-sidebar__divider {
  height: 1px;
  background: var(--cm-border);
  margin: 8px 10px;
}

/* ── Bottom navigation ─────────────────────────────────────── */
.cm-bottom-nav {
  position: fixed;
  bottom: 0; left: 0; right: 0;
  height: var(--cm-nav-h);
  background: oklch(0.16 0.038 262 / 0.97);
  border-top: 1px solid var(--cm-border);
  backdrop-filter: blur(20px) saturate(150%);
  display: flex;
  align-items: center;
  justify-content: space-around;
  z-index: 1000;
}

.cm-nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 3px;
  text-decoration: none !important;
  color: var(--cm-muted) !important;
  font-size: .62rem;
  font-weight: 700;
  transition: color .18s;
  padding: 4px 10px;
}

.cm-nav-item i { font-size: 20px; }
.cm-nav-item:hover,
.cm-nav-item.active { color: var(--cm-blue) !important; }

/* ── Modal overrides ───────────────────────────────────────── */
.modal-content {
  background: var(--cm-card) !important;
  border: 1px solid var(--cm-border2) !important;
  border-radius: 16px !important;
  color: var(--cm-text) !important;
}
.modal-header {
  border-bottom: 1px solid var(--cm-border) !important;
  background: oklch(0.98 0.005 250 / 0.04) !important;
}
.modal-footer {
  border-top: 1px solid var(--cm-border) !important;
  background: oklch(0.98 0.005 250 / 0.04) !important;
}

/* ── Scrollbars ────────────────────────────────────────────── */
*::-webkit-scrollbar { width: 6px; height: 6px; }
*::-webkit-scrollbar-track { background: transparent; }
*::-webkit-scrollbar-thumb { background: oklch(0.62 0.22 255 / 0.28); border-radius: 4px; }
*::-webkit-scrollbar-thumb:hover { background: oklch(0.62 0.22 255 / 0.50); }

/* ── Responsive ────────────────────────────────────────────── */
@media (max-width: 600px) {
  .cm-main { padding-left: 12px; padding-right: 12px; }
}
</style>
<?php echo $extra_styles; ?>
</head>
<body>

<!-- ============================================================
     HEADER
     ============================================================ -->
<header class="ushs-header" style="position:fixed;top:0;left:0;right:0;z-index:1060;">
  <!-- Hamburger -->
  <button class="ushs-header__menu-btn" id="cmSidebarToggle" aria-label="Open menu">
    <i class="fas fa-bars"></i>
  </button>

  <!-- Brand -->
  <a class="ushs-header__brand" href="dashboard.php" style="text-decoration:none; margin-left:4px;">
    <div class="ushs-header__logo">
      <img src="../assets/icons/ushs.avif" alt="USHS"
           onerror="this.style.display='none';this.parentNode.innerHTML='<i class=\'fas fa-chart-pie\' style=\'font-size:15px;color:inherit;\'></i>'">
    </div>
    <div class="ushs-header__brand-text">
      <span class="ushs-header__brand-name">CSR Dashboard</span>
      <span class="ushs-header__brand-sub">Latest: <?= date('n/j/y') ?> &middot; CSR Manager</span>
    </div>
  </a>

  <!-- Page title -->
  <span class="ushs-header__title"><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></span>
  <a href="javascript:history.length > 1 ? history.back() : window.location.href='dashboard.php';" class="cm-back-btn" title="Back">
    <i class="fas fa-arrow-left"></i>
  </a>

  <!-- Right actions -->
  <div class="ushs-header__actions">
    <!-- Notifications -->
    <div class="dropdown">
      <button class="ushs-header__icon-btn" id="cmNotifToggle" data-bs-toggle="dropdown" aria-label="Notifications">
        <i class="fas fa-bell"></i>
        <span id="cmNotifBadge" class="ushs-header__badge" style="display:none;">0</span>
      </button>
      <div class="dropdown-menu dropdown-menu-end ushs-notif-panel" id="cmNotifPanel">
        <div class="dropdown-header">
          <span>Notifications</span>
          <a href="notifications.php" style="font-size:.75rem;color:var(--cm-blue)!important;">View all</a>
        </div>
        <div id="cmNotifList" style="padding:14px;text-align:center;font-size:.8rem;color:var(--cm-muted);">Loading…</div>
      </div>
    </div>

    <!-- Messages -->
    <a href="messages.php" class="ushs-header__icon-btn" title="Messages">
      <i class="fas fa-comment-dots"></i>
    </a>

    <!-- User chip -->
    <div class="dropdown">
      <div class="ushs-header__user" data-bs-toggle="dropdown" aria-expanded="false">
        <div class="ushs-header__avatar"><?= htmlspecialchars($mgrInitials, ENT_QUOTES, 'UTF-8') ?></div>
        <div class="ushs-header__user-info">
          <span class="ushs-header__user-name"><?= htmlspecialchars($mgrFullName, ENT_QUOTES, 'UTF-8') ?></span>
          <span class="ushs-header__user-role">CSR Manager</span>
        </div>
        <i class="fas fa-chevron-down ushs-header__user-chevron"></i>
      </div>
      <div class="dropdown-menu dropdown-menu-end">
        <a class="dropdown-item" href="announcements.php"><i class="fas fa-bullhorn me-2"></i>Announcements</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="logout.php"
           style="color:oklch(0.72 0.20 27)!important;"
           onclick="return confirm('Log out of CSR Manager Portal?');">
          <i class="fas fa-sign-out-alt me-2"></i>Logout
        </a>
      </div>
    </div>
  </div>
</header>

<!-- ============================================================
     SIDEBAR (slide-out)
     ============================================================ -->
<div class="cm-sidebar-overlay" id="cmSidebarOverlay"></div>
<aside class="cm-sidebar" id="cmSidebar" aria-hidden="true">
  <div class="cm-sidebar__hdr">
    <div class="cm-sidebar__hdr-brand">
      <div class="cm-sidebar__hdr-icon">
        <i class="fas fa-chart-pie" style="color:oklch(0.62 0.22 255);font-size:15px;"></i>
      </div>
      <div>
        <div class="cm-sidebar__hdr-name">CSR Manager</div>
        <div class="cm-sidebar__hdr-role"><?= htmlspecialchars($mgrFullName, ENT_QUOTES, 'UTF-8') ?></div>
      </div>
    </div>
    <button class="cm-sidebar__close" id="cmSidebarClose" aria-label="Close menu">
      <i class="fas fa-times"></i>
    </button>
  </div>

  <nav class="cm-sidebar__nav">
    <?php
    $navItems = [
        ['dashboard.php',      'fas fa-chart-pie',         'Overview'],
        ['tickets.php',        'fas fa-clipboard-list',    'Tickets'],
        ['verification_queue.php','fas fa-shield-alt',       'Verification Queue'],
        ['calls.php',          'fas fa-phone-volume',      'Calls'],
        ['messages.php',       'fas fa-comments',          'Messages'],
        ['manual_ticket.php',  'fas fa-ticket-alt',        'Manual Ticket'],
        ['mistake.php',        'fas fa-circle-exclamation','Mistake'],
        ['warning.php',        'fas fa-triangle-exclamation','Warning'],
        ['report.php',         'fas fa-chart-line',        'Report'],
        ['announcements.php',  'fas fa-bullhorn',          'Announcements'],
        ['notifications.php',  'fas fa-bell',              'Notifications'],
    ];
    foreach ($navItems as [$href, $icon, $label]):
        $active = $_currentPage === $href ? 'active' : '';
    ?>
    <a href="<?= htmlspecialchars($href, ENT_QUOTES, 'UTF-8') ?>" class="cm-sidebar__item <?= $active ?>">
      <i class="<?= htmlspecialchars($icon, ENT_QUOTES, 'UTF-8') ?>"></i>
      <span><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></span>
    </a>
    <?php endforeach; ?>
    <div class="cm-sidebar__divider"></div>
    <a href="logout.php" class="cm-sidebar__item logout"
       onclick="return confirm('Log out of CSR Manager Portal?');">
      <i class="fas fa-sign-out-alt"></i>
      <span>Logout</span>
    </a>
  </nav>
</aside>

<!-- ============================================================
     PAGE CONTENT
     ============================================================ -->
<main class="cm-main">
  <?php echo $content ?? ''; ?>
</main>

<!-- ============================================================
     BOTTOM NAVIGATION
     ============================================================ -->
<nav class="cm-bottom-nav">
  <?php
  $bottomNav = [
    ['dashboard.php',     'fas fa-chart-pie',      'Overview'],
    ['report.php',        'fas fa-chart-line',      'Report'],
    ['tickets.php',       'fas fa-clipboard-list',  'Tickets'],
    ['verification_queue.php','fas fa-shield-alt',     'Verify'],
    ['messages.php',      'fas fa-comments',        'Messages'],
    ['mistake.php',       'fas fa-circle-exclamation','Mistake'],
    ['warning.php',       'fas fa-triangle-exclamation','Warning'],
  ];
  foreach ($bottomNav as [$href, $icon, $label]):
    $active = $_currentPage === $href ? 'active' : '';
  ?>
  <a href="<?= htmlspecialchars($href, ENT_QUOTES, 'UTF-8') ?>" class="cm-nav-item <?= $active ?>">
    <i class="<?= htmlspecialchars($icon, ENT_QUOTES, 'UTF-8') ?>"></i>
    <span><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?></span>
  </a>
  <?php endforeach; ?>
</nav>

<!-- Toast container -->
<div class="cm-toast-container" id="cmToastContainer"></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>

<script>
/* ── Sidebar ──────────────────────────────────────────────── */
(function () {
  const sidebar  = document.getElementById('cmSidebar');
  const overlay  = document.getElementById('cmSidebarOverlay');
  const toggle   = document.getElementById('cmSidebarToggle');
  const close    = document.getElementById('cmSidebarClose');

  function openSidebar() {
    sidebar.classList.add('open');
    sidebar.setAttribute('aria-hidden', 'false');
    overlay.style.display = 'block';
    document.body.style.overflow = 'hidden';
  }
  function closeSidebar() {
    sidebar.classList.remove('open');
    sidebar.setAttribute('aria-hidden', 'true');
    overlay.style.display = 'none';
    document.body.style.overflow = '';
  }

  if (toggle)  toggle.addEventListener('click', function(e){ e.preventDefault(); sidebar.classList.contains('open') ? closeSidebar() : openSidebar(); });
  if (close)   close.addEventListener('click', closeSidebar);
  if (overlay) overlay.addEventListener('click', closeSidebar);
  document.addEventListener('keydown', e => { if(e.key === 'Escape') closeSidebar(); });
}());

/* ── Notifications ────────────────────────────────────────── */
function cmLoadNotifications() {
  $.ajax({
    url: '../csr/ajax/get_notifications.php',
    method: 'GET',
    data: { limit: 6 },
    dataType: 'json',
    success: function(res) {
      if (!res.success) return;
      const badge = document.getElementById('cmNotifBadge');
      const list  = document.getElementById('cmNotifList');
      const count = parseInt(res.unread_count) || 0;

      if (count > 0) {
        badge.textContent = count > 99 ? '99+' : count;
        badge.style.display = 'block';
      } else {
        badge.style.display = 'none';
      }

      if (!res.notifications || !res.notifications.length) {
        list.innerHTML = '<div style="text-align:center;color:var(--cm-muted);padding:12px 0;"><i class="fas fa-bell-slash mb-2" style="font-size:1.4rem;display:block;"></i>No new notifications</div>';
        return;
      }

      list.innerHTML = res.notifications.map(n => `
        <div class="notif-item ${n.is_read ? '' : 'unread'}"
             onclick="cmMarkNotifRead(${n.id},'${cmEsc(n.link||'')}')">
          <div class="notif-icon" style="background:oklch(0.62 0.22 255 / 0.14);">
            <i class="fas fa-bell" style="color:oklch(0.62 0.22 255);font-size:13px;"></i>
          </div>
          <div class="notif-body">
            <strong>${cmEsc(n.title)}</strong>
            <small>${cmEsc((n.message||'').substring(0,80))}${(n.message||'').length>80?'…':''}</small>
          </div>
        </div>`).join('');
    }
  });
}

function cmMarkNotifRead(id, link) {
  $.post('../csr/ajax/mark_notification_read.php', { notification_id: id });
  if (link) window.location.href = link;
}

/* ── Toast ────────────────────────────────────────────────── */
function cmToast(message, type) {
  type = type || 'info';
  const colors = { success:'oklch(0.60 0.18 150)', error:'oklch(0.62 0.24 27)', warning:'oklch(0.82 0.16 85)', info:'oklch(0.62 0.22 255)' };
  const icons  = { success:'fa-check-circle', error:'fa-times-circle', warning:'fa-exclamation-triangle', info:'fa-info-circle' };
  const el = document.createElement('div');
  el.style.cssText = `background:var(--cm-card);border:1px solid ${colors[type]||colors.info};border-radius:12px;padding:12px 16px;display:flex;gap:10px;align-items:center;max-width:320px;box-shadow:0 8px 24px oklch(0 0 0 / .35);color:var(--cm-text);font-size:.84rem;font-weight:600;`;
  el.innerHTML = `<i class="fas ${icons[type]||icons.info}" style="color:${colors[type]||colors.info};font-size:16px;flex-shrink:0;"></i><span>${cmEsc(message)}</span>`;
  document.getElementById('cmToastContainer').appendChild(el);
  setTimeout(() => el.remove(), 4000);
}

/* ── Escape ───────────────────────────────────────────────── */
function cmEsc(str) {
  return String(str||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}

/* ── Boot ─────────────────────────────────────────────────── */
$(document).ready(function () {
  cmLoadNotifications();
  setInterval(cmLoadNotifications, 15000);
  $('#cmNotifToggle').on('click', cmLoadNotifications);
});
</script>

<?php echo $extra_scripts; ?>
</body>
</html>
