<?php
// team_leader/layout.php — Team Leader Portal layout using CSR Manager dashboard style
if (session_status() === PHP_SESSION_NONE) session_start();

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

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

$database = new Database();
$db = $database->getConnection();

$stmt = $db->prepare("SELECT * FROM csr_users WHERE id = :id LIMIT 1");
$stmt->execute([':id' => $_SESSION['csr_id']]);
$csr = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$csr) { header('Location: logout.php'); exit(); }

if (function_exists('ensureAnnouncementTables')) ensureAnnouncementTables($db);
$_SESSION['csr_role'] = $csr['role'] ?? ($_SESSION['csr_role'] ?? 'csr');

// CSR Manager and Team Leader have their own portals.
if ($_SESSION['csr_role'] === 'csr_manager') {
    header('Location: ../csr_manager/dashboard.php');
    exit();
}
if ($_SESSION['csr_role'] !== 'team_leader') {
    if ($_SESSION['csr_role'] === 'csr_manager') { header('Location: ../csr_manager/dashboard.php'); exit(); }
    header('Location: ../csr/dashboard.php');
    exit();
}

$currentPage = basename($_SERVER['PHP_SELF']);
$fullName = trim(($csr['first_name'] ?? '') . ' ' . ($csr['last_name'] ?? '')) ?: 'Team Leader';
$initials = strtoupper(substr($csr['first_name'] ?? 'C', 0, 1) . substr($csr['last_name'] ?? 'A', 0, 1));
$roleDisplay = match($_SESSION['csr_role'] ?? 'csr') {
    'team_leader' => 'Team Leader',
    'csr_manager' => 'CSR Manager',
    default => 'CSR Agent',
};

$notif_count = 0;
try {
    $n = $db->prepare("SELECT COUNT(*) FROM csr_notifications WHERE csr_id = :id AND is_read = 0");
    $n->execute([':id' => $_SESSION['csr_id']]);
    $notif_count = (int)$n->fetchColumn();
} catch (Exception $e) {}

$title = $title ?? 'Dashboard';
$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>Team Leader — <?= 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://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
<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>
: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/.12);--cm-border2:oklch(0.98 0.005 250/.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;min-height:100%;font-family:'Inter',system-ui,sans-serif;background:radial-gradient(circle at 18% 0%,oklch(0.62 0.22 255/.13),transparent 34%),linear-gradient(135deg,var(--cm-bg) 0%,var(--cm-bg2) 100%) fixed;color:var(--cm-text);overflow-x:hidden}body::before{content:"";position:fixed;inset:0;pointer-events:none;z-index:-1;background-image:linear-gradient(oklch(0.98 0.005 250/.022) 1px,transparent 1px),linear-gradient(90deg,oklch(0.98 0.005 250/.016) 1px,transparent 1px);background-size:44px 44px}.cm-main,.main-content{padding:calc(var(--cm-header-h) + 16px) 20px calc(var(--cm-nav-h) + 20px);min-height:100vh;background:transparent!important}.cm-card,.card,.stats-card,.filter-section{background:var(--cm-card)!important;border:1px solid var(--cm-border)!important;border-radius:16px!important;color:var(--cm-text)!important;box-shadow:none!important}.cm-card{padding:16px}.card-header{background:oklch(0.98 0.005 250/.04)!important;border-bottom:1px solid var(--cm-border)!important;color:var(--cm-text)!important}.cm-card__title{font-family:'Space Grotesk',system-ui,sans-serif;font-size:.88rem;font-weight:800;color:var(--cm-muted);margin-bottom:12px;letter-spacing:.02em}.cm-btn,.btn-outline-primary,.btn-outline-info,.btn-outline-secondary{display:inline-flex;align-items:center;gap:7px;padding:8px 14px;border-radius:10px!important;border:1px solid var(--cm-border)!important;background:var(--cm-card)!important;color:var(--cm-text)!important;font-size:.82rem;font-weight:800;text-decoration:none!important;cursor:pointer;white-space:nowrap}.cm-btn:hover,.btn-outline-primary:hover,.btn-outline-info:hover,.btn-outline-secondary:hover{background:oklch(0.62 0.22 255/.16)!important;border-color:oklch(0.62 0.22 255/.45)!important}.cm-btn--primary,.btn-primary,.btn-info{background:var(--cm-blue)!important;border-color:transparent!important;color:#fff!important;font-weight:800!important;border-radius:10px!important}.btn-success{background:var(--cm-green)!important;border:0!important;color:#07130d!important;font-weight:800!important;border-radius:10px!important}.btn-warning{background:var(--cm-yellow)!important;border:0!important;color:#141006!important;font-weight:800!important;border-radius:10px!important}.btn-danger{background:var(--cm-red)!important;border:0!important;color:#fff!important;font-weight:800!important;border-radius:10px!important}.table{color:var(--cm-text)!important}.table thead th,.table-light th{background:oklch(0.98 0.005 250/.06)!important;color:var(--cm-muted)!important;border-color:var(--cm-border)!important;font-weight:800;text-transform:uppercase;font-size:.75rem;letter-spacing:.05em}.table td,.table th{border-color:var(--cm-border)!important;color:var(--cm-text)!important}.table tbody tr:hover{background:oklch(0.62 0.22 255/.07)!important}.text-muted{color:var(--cm-muted)!important}.badge{border-radius:999px!important;padding:6px 10px!important;font-weight:800!important}.form-control,.form-select,textarea{background:oklch(0.11 0.032 261/.85)!important;border:1px solid var(--cm-border)!important;color:var(--cm-text)!important;border-radius:10px!important}.form-control:focus,.form-select:focus{border-color:oklch(0.62 0.22 255/.55)!important;box-shadow:0 0 0 .2rem oklch(0.62 0.22 255/.14)!important}.form-control::placeholder{color:oklch(0.72 0.02 260/.72)!important}.form-select option{background:#111a33;color:#fff}.dropdown-menu{background:var(--cm-card)!important;border:1px solid var(--cm-border2)!important;border-radius:14px!important;box-shadow:0 18px 50px oklch(0 0 0/.35)!important}.dropdown-item{color:var(--cm-text)!important}.dropdown-item:hover{background:oklch(0.62 0.22 255/.14)!important}.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/.04)!important}.modal-footer{border-top:1px solid var(--cm-border)!important;background:oklch(0.98 0.005 250/.04)!important}.btn-close{filter:invert(1);opacity:.9}.cm-toast-container{position:fixed;right:16px;bottom:calc(var(--cm-nav-h) + 12px);z-index:2200;display:flex;flex-direction:column;gap:10px}.cm-sidebar-overlay{display:none;position:fixed;inset:0;background:oklch(0 0 0/.55);backdrop-filter:blur(3px);z-index:1070}.cm-sidebar{position:fixed;top:0;left:-320px;width:min(300px,86vw);height:100vh;background:oklch(0.16 0.038 262/.98);border-right:1px solid var(--cm-border2);box-shadow:18px 0 45px oklch(0 0 0/.34);z-index:1080;transition:left .26s ease;overflow-y:auto}.cm-sidebar.open{left:0}.cm-sidebar__hdr{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:16px;border-bottom:1px solid var(--cm-border)}.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/.18);border:1px solid oklch(0.62 0.22 255/.35);display:flex;align-items:center;justify-content:center}.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/.07);color:var(--cm-text);display:flex;align-items:center;justify-content:center;cursor:pointer}.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:800;font-size:.88rem;margin-bottom:3px;border:1px solid transparent;transition:.18s}.cm-sidebar__item i{color:var(--cm-blue);width:20px;text-align:center}.cm-sidebar__item:hover,.cm-sidebar__item.active{background:oklch(0.62 0.22 255/.14);border-color:oklch(0.62 0.22 255/.30);transform:translateX(3px)}.cm-sidebar__item.logout,.cm-sidebar__item.logout i{color:var(--cm-red)!important}.cm-sidebar__divider{height:1px;background:var(--cm-border);margin:8px 10px}.cm-bottom-nav{position:fixed;bottom:0;left:0;right:0;height:var(--cm-nav-h);background:oklch(0.16 0.038 262/.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:800;transition:color .18s;padding:4px 8px}.cm-nav-item i{font-size:19px}.cm-nav-item:hover,.cm-nav-item.active{color:var(--cm-blue)!important}*::-webkit-scrollbar{width:6px;height:6px}*::-webkit-scrollbar-track{background:transparent}*::-webkit-scrollbar-thumb{background:oklch(0.62 0.22 255/.28);border-radius:4px}.ca-stat-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}.ca-stat{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:14px;padding:16px}.ca-stat__icon{font-size:18px;color:var(--cm-muted);margin-bottom:8px}.ca-stat__value{font-family:'Space Grotesk',system-ui,sans-serif;font-size:2rem;font-weight:900;line-height:1;color:var(--cm-text)}.ca-stat__label{font-size:.68rem;text-transform:uppercase;letter-spacing:.06em;font-weight:800;color:var(--cm-muted);margin-top:6px}.ca-quick-bar{display:flex;gap:8px;margin-bottom:18px;flex-wrap:wrap}.ca-grid-2{display:grid;grid-template-columns:1fr 1fr;gap:16px}.status-badge{padding:5px 10px;border-radius:999px;font-size:12px;font-weight:800;background:oklch(0.62 0.22 255/.16);color:var(--cm-text)}.cm-back-btn{width:auto!important;min-width:42px;padding:0 12px!important;gap:7px}.cm-back-btn span{font-size:.78rem;font-weight:800}@media(max-width:640px){.cm-back-btn span{display:none}.cm-back-btn{padding:0!important}}@media(max-width:900px){.ca-stat-grid{grid-template-columns:repeat(2,1fr)}.ca-grid-2{grid-template-columns:1fr}}@media(max-width:600px){.cm-main,.main-content{padding-left:12px;padding-right:12px}.ushs-header__brand-sub,.ushs-header__title{display:none}.ca-stat-grid{grid-template-columns:1fr 1fr}}

.ca-profile-chip{height:100%;min-width:185px;padding:12px 14px;border:1px solid rgba(255,255,255,.10);border-radius:16px;background:rgba(255,255,255,.055);display:flex;flex-direction:column;gap:3px;color:rgba(255,255,255,.92)}
.ca-profile-chip i{color:var(--cm-cyan);font-size:1rem;margin-bottom:2px}.ca-profile-chip span{font-size:.74rem;text-transform:uppercase;letter-spacing:.08em;color:rgba(255,255,255,.56)}.ca-profile-chip strong{font-size:.95rem;color:#fff;word-break:break-word}
.ca-filter-form{display:flex;flex-wrap:wrap;gap:12px;align-items:end;margin-bottom:16px}.ca-filter-form .form-label{color:rgba(255,255,255,.72);font-size:.78rem;text-transform:uppercase;letter-spacing:.08em;margin-bottom:6px}.ca-filter-form .form-control{background:rgba(255,255,255,.08)!important;border:1px solid rgba(255,255,255,.14)!important;color:#fff!important;border-radius:12px!important}.ca-filter-form .form-control::-webkit-calendar-picker-indicator{filter:invert(1)}

</style>
<?= $extra_styles ?>
</head>
<body>
<header class="ushs-header" style="position:fixed;top:0;left:0;right:0;z-index:1060;">
  <button class="ushs-header__menu-btn" id="cmSidebarToggle" aria-label="Open menu"><i class="fas fa-bars"></i></button>
  <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-headset\' style=\'font-size:15px;color:inherit;\'></i>'"></div>
    <div class="ushs-header__brand-text"><span class="ushs-header__brand-name">Team Leader Portal</span><span class="ushs-header__brand-sub">Latest: <?= date('n/j/y') ?> &middot; <?= htmlspecialchars($roleDisplay, ENT_QUOTES, 'UTF-8') ?></span></div>
  </a>
  <span class="ushs-header__title"><?= htmlspecialchars($title, ENT_QUOTES, 'UTF-8') ?></span>
  <div class="ushs-header__actions">
    <button type="button" class="ushs-header__icon-btn cm-back-btn" title="Back" onclick="cmGoBack()"><i class="fas fa-arrow-left"></i><span>Back</span></button>
    <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="<?= $notif_count > 0 ? '' : 'display:none;' ?>"><?= $notif_count ?></span></button>
      <div class="dropdown-menu dropdown-menu-end ushs-notif-panel"><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>
    <a href="messages.php" class="ushs-header__icon-btn" title="Messages"><i class="fas fa-comment-dots"></i></a>
    <div class="dropdown"><div class="ushs-header__user" data-bs-toggle="dropdown" aria-expanded="false"><div class="ushs-header__avatar"><?= htmlspecialchars($initials, ENT_QUOTES, 'UTF-8') ?></div><div class="ushs-header__user-info"><span class="ushs-header__user-name"><?= htmlspecialchars($fullName, ENT_QUOTES, 'UTF-8') ?></span><span class="ushs-header__user-role"><?= htmlspecialchars($roleDisplay, ENT_QUOTES, 'UTF-8') ?></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="dashboard.php"><i class="fas fa-user me-2"></i>Profile Summary</a><a class="dropdown-item" href="announcements.php"><i class="fas fa-bullhorn me-2"></i>Announcement</a><a class="dropdown-item" href="notifications.php"><i class="fas fa-bell me-2"></i>Notifications</a><div class="dropdown-divider"></div><a class="dropdown-item" href="logout.php" style="color:var(--cm-red)!important;" onclick="return confirm('Log out of Team Leader Portal?');"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></div></div>
  </div>
</header>
<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-users-viewfinder" style="color:var(--cm-blue);font-size:15px;"></i></div><div><div class="cm-sidebar__hdr-name">Team Leader</div><div class="cm-sidebar__hdr-role"><?= htmlspecialchars($fullName, 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','Dashboard'],
      ['team_requests.php','fas fa-ticket-alt','Team Requests'],
      ['verification_queue.php','fas fa-shield-alt','Verification Queue'],
      ['manual_ticket.php','fas fa-plus-circle','Manual Ticket'],
      ['technicians.php','fas fa-user-cog','Technicians'],
      ['team_agents.php','fas fa-user-group','Team Agents'],
      ['calls.php','fas fa-phone-volume','Web Calls'],
      ['team_performance.php','fas fa-chart-line','Team Performance'],
      ['mistake.php','fas fa-circle-exclamation','Mistake'],
      ['warning.php','fas fa-triangle-exclamation','Warning'],
      ['messages.php','fas fa-comments','Messages'],
      ['announcements.php','fas fa-bullhorn','Announcements'],
      ['notifications.php','fas fa-bell','Notifications'],
    ];
    foreach ($navItems as [$href,$icon,$label]):
      $active = $currentPage === $href || ($href === 'manual_ticket.php' && $currentPage === 'ticket.php') ? '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 Team Leader Portal?');"><i class="fas fa-sign-out-alt"></i><span>Logout</span></a>
  </nav>
</aside>
<main class="cm-main"><?= $content ?? '' ?></main>
<nav class="cm-bottom-nav">
  <?php $bottomNav=[['dashboard.php','fas fa-chart-pie','Home'],['team_requests.php','fas fa-ticket-alt','Requests'],['verification_queue.php','fas fa-shield-alt','Verify'],['manual_ticket.php','fas fa-plus-circle','Manual'],['calls.php','fas fa-phone-volume','Calls'],['team_performance.php','fas fa-chart-line','Performance'],['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>
<div class="cm-toast-container" id="cmToastContainer"></div>
<div class="modal fade" id="csrAnnouncementModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="modal-header"><h5 class="modal-title"><i class="fas fa-bullhorn me-2" style="color:var(--cm-cyan)"></i><span id="csrAnnouncementTitle">Announcement</span></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div id="csrAnnouncementMessage" style="white-space:pre-wrap;line-height:1.6"></div><small id="csrAnnouncementDate" class="text-muted d-block mt-3"></small></div><div class="modal-footer"><button type="button" class="btn btn-primary" id="markAnnouncementReadBtn">Got it</button></div></div></div></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>
(function(){const sidebar=document.getElementById('cmSidebar'),overlay=document.getElementById('cmSidebarOverlay'),toggle=document.getElementById('cmSidebarToggle'),close=document.getElementById('cmSidebarClose');function openS(){sidebar.classList.add('open');overlay.style.display='block';document.body.style.overflow='hidden'}function closeS(){sidebar.classList.remove('open');overlay.style.display='none';document.body.style.overflow=''}window.toggleSidebar=openS;window.closeSidebar=closeS;if(toggle)toggle.addEventListener('click',e=>{e.preventDefault();sidebar.classList.contains('open')?closeS():openS()});if(close)close.addEventListener('click',closeS);if(overlay)overlay.addEventListener('click',closeS);document.addEventListener('keydown',e=>{if(e.key==='Escape')closeS()})}());
function cmGoBack(){if(window.history.length>1){window.history.back();}else{window.location.href='dashboard.php';}}
function cmEsc(str){return String(str||'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;')}
function showToast(message,type='info'){cmToast(message,type)}
function cmToast(message,type='info'){const colors={success:'var(--cm-green)',error:'var(--cm-red)',warning:'var(--cm-yellow)',info:'var(--cm-blue)'};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:700;`;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)}
function loadNotificationDropdown(){ $.ajax({url:'../csr/ajax/get_notifications.php',method:'GET',data:{limit:6},dataType:'json',success:function(r){if(!r.success)return;updateNotificationBadge(parseInt(r.unread_count)||0);let list=$('#cmNotifList');if(!r.notifications||!r.notifications.length){list.html('<div style="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.html(r.notifications.map(n=>`<div class="dropdown-item" style="white-space:normal;cursor:pointer;" onclick="viewNotificationFromDropdown(${n.id},'${cmEsc(n.title)}','${cmEsc(n.message)}','${cmEsc(n.link||'')}')"><strong class="small">${cmEsc(n.title)}</strong><p class="small mb-0 text-muted">${cmEsc((n.message||'').substring(0,90))}${(n.message||'').length>90?'…':''}</p></div>`).join(''));}})}
function updateNotificationBadge(count){if(count>0){$('#cmNotifBadge').text(count>99?'99+':count).show()}else{$('#cmNotifBadge').hide()}}
function viewNotificationFromDropdown(id,title,message,link){$.post('../csr/ajax/mark_notification_read.php',{notification_id:id}); if(link){window.location.href=link}else{cmToast(message,'info')}}
function formatDate(dateString){if(!dateString)return 'N/A';let d=new Date(dateString);return d.toLocaleDateString('en-US',{year:'numeric',month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'});}
let pendingAnnouncements=[],activeAnnouncementId=null,activeAnnouncementIdsInQueue=new Set(),announcementCheckRunning=false;
function checkCsrAnnouncements(){if(announcementCheckRunning)return;announcementCheckRunning=true;$.ajax({url:'../csr/ajax/get_unread_announcements.php',method:'GET',data:{_:Date.now()},cache:false,dataType:'json',success:function(r){if(r.success&&r.announcements&&r.announcements.length){r.announcements.forEach(a=>{const id=String(a.id);if(String(activeAnnouncementId)!==id&&!activeAnnouncementIdsInQueue.has(id)){pendingAnnouncements.push(a);activeAnnouncementIdsInQueue.add(id)}});showNextAnnouncement()}},complete:function(){announcementCheckRunning=false}})}
function showNextAnnouncement(){const modalEl=document.getElementById('csrAnnouncementModal');if(!modalEl||!pendingAnnouncements.length||$('#csrAnnouncementModal').hasClass('show'))return;const a=pendingAnnouncements.shift();activeAnnouncementId=a.id;activeAnnouncementIdsInQueue.delete(String(a.id));$('#csrAnnouncementTitle').text(a.title||'Announcement');$('#csrAnnouncementMessage').text(a.message||'');$('#csrAnnouncementDate').text(a.created_at?'Posted: '+formatDate(a.created_at):'');bootstrap.Modal.getOrCreateInstance(modalEl).show()}
$(document).on('click','#markAnnouncementReadBtn',function(){if(!activeAnnouncementId)return;$.ajax({url:'../csr/ajax/mark_announcement_read.php',method:'POST',data:{announcement_id:activeAnnouncementId},complete:function(){const m=bootstrap.Modal.getInstance(document.getElementById('csrAnnouncementModal'));if(m)m.hide();activeAnnouncementId=null;setTimeout(()=>{showNextAnnouncement();checkCsrAnnouncements()},500)}})});
$(document).ready(function(){loadNotificationDropdown();setInterval(loadNotificationDropdown,10000);$('#cmNotifToggle').on('click',loadNotificationDropdown);checkCsrAnnouncements();setInterval(checkCsrAnnouncements,5000);});
</script>
<?= $extra_scripts ?>
</body>
</html>
