<?php
// csr/manager_dashboard.php
// CSR Manager / Team Leader exclusive dashboard.
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config/database.php';
require_once '../includes/app_helpers.php';
require_once '../includes/csr_report_helpers.php';

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

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

$managerId = (int)$_SESSION['csr_id'];
$role      = getCsrRoleForReport($db, $managerId);

if (!in_array($role, ['team_leader', 'csr_manager'], true)) {
    header('Location: dashboard.php');
    exit();
}

// Manager info
$mgrStmt = $db->prepare("SELECT first_name, last_name FROM csr_users WHERE id = :id LIMIT 1");
$mgrStmt->execute([':id' => $managerId]);
$mgr = $mgrStmt->fetch(PDO::FETCH_ASSOC);
$mgrName    = ($mgr['first_name'] ?? '') . ' ' . ($mgr['last_name'] ?? '');
$mgrInitials = strtoupper(substr($mgr['first_name'] ?? 'M', 0, 1) . substr($mgr['last_name'] ?? 'G', 0, 1));
$roleLabel  = getCsrRoleLabelForReport($role);

// Notification count
$notifStmt = $db->prepare("SELECT COUNT(*) FROM csr_notifications WHERE csr_id = :id AND is_read = 0");
$notifStmt->execute([':id' => $managerId]);
$notifCount = (int)$notifStmt->fetchColumn();

$today = date('n/j/y');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSR Manager Dashboard</title>

<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://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://code.jquery.com/jquery-3.6.0.min.js"></script>
<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>
/* =====================================================
   Manager Dashboard Layout
===================================================== */
:root {
  --md-bg:      oklch(0.13 0.035 260);
  --md-card:    oklch(0.18 0.038 262);
  --md-card2:   oklch(0.16 0.035 261);
  --md-border:  oklch(0.98 0.005 250 / 0.12);
  --md-border2: oklch(0.98 0.005 250 / 0.20);
  --md-text:    oklch(0.98 0.005 250);
  --md-muted:   oklch(0.72 0.02 260);
  --md-cyan:    oklch(0.72 0.18 195);
  --md-green:   oklch(0.72 0.18 155);
  --md-purple:  oklch(0.72 0.18 300);
  --md-yellow:  oklch(0.82 0.16 85);
  --md-red:     oklch(0.68 0.22 27);
  --md-blue:    oklch(0.62 0.22 255);
}

*{box-sizing:border-box;}

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

/* page wrapper */
.mgr-wrapper{
  padding: 20px 20px 80px;
}

/* ---- Stat bar ---- */
.stat-bar{
  display:grid;
  grid-template-columns: repeat(7, 1fr);
  gap:10px;
  margin-bottom:20px;
}

.stat-tile{
  background: var(--md-card);
  border:1px solid var(--md-border);
  border-radius:14px;
  padding:16px 14px 12px;
  text-align:center;
  transition: border-color .2s, transform .2s;
  cursor:default;
}

.stat-tile:hover{
  border-color: var(--md-border2);
  transform: translateY(-2px);
}

.stat-tile__icon{
  font-size:20px;
  margin-bottom:6px;
  color: var(--md-muted);
}

.stat-tile__val{
  font-family:'Space Grotesk',system-ui,sans-serif;
  font-size:2rem;
  font-weight:800;
  line-height:1;
  margin-bottom:4px;
}

.stat-tile__lbl{
  font-size:.66rem;
  font-weight:700;
  text-transform:uppercase;
  letter-spacing:.06em;
  color:var(--md-muted);
}

/* colour accents */
.stat-tile--agents .stat-tile__val   { color: var(--md-text); }
.stat-tile--gh     .stat-tile__val   { color: var(--md-text); }
.stat-tile--sched  .stat-tile__val   { color: var(--md-cyan); }
.stat-tile--attempt .stat-tile__val  { color: var(--md-blue); }
.stat-tile--update  .stat-tile__val  { color: var(--md-purple); }
.stat-tile--warn    .stat-tile__val  { color: var(--md-yellow); }
.stat-tile--mistakes .stat-tile__val { color: var(--md-red); }

/* ---- Action buttons ---- */
.mgr-actions{
  display:flex;
  gap:8px;
  margin-bottom:20px;
  flex-wrap:wrap;
}

.mgr-btn{
  display:inline-flex;
  align-items:center;
  gap:7px;
  padding:8px 14px;
  border-radius:10px;
  border:1px solid var(--md-border);
  background: var(--md-card);
  color: var(--md-text) !important;
  font-size:.82rem;
  font-weight:700;
  text-decoration:none !important;
  cursor:pointer;
  transition: background .18s, border-color .18s;
}

.mgr-btn:hover{
  background: oklch(0.62 0.22 255 / 0.16);
  border-color: oklch(0.62 0.22 255 / 0.45);
}

.mgr-btn--active, .mgr-btn[data-view].active{
  background: oklch(0.62 0.22 255 / 0.22);
  border-color: oklch(0.62 0.22 255 / 0.55);
}

/* ---- Charts row ---- */
.charts-row{
  display:grid;
  grid-template-columns: 2fr 1fr;
  gap:16px;
  margin-bottom:16px;
}

/* ---- Panel card ---- */
.mgr-panel{
  background: var(--md-card);
  border:1px solid var(--md-border);
  border-radius:16px;
  padding:16px;
  position:relative;
}

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

/* ---- 10-day trend ---- */
.trend-panel{
  margin-bottom:16px;
}

/* ---- Bottom row ---- */
.bottom-row{
  display:grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap:16px;
}

/* Team summary card */
.team-card{
  background: var(--md-card);
  border:1px solid var(--md-border);
  border-radius:14px;
  padding:14px 16px;
}

.team-card__name{
  font-size:.72rem;
  font-weight:800;
  text-transform:uppercase;
  letter-spacing:.08em;
  margin-bottom:10px;
}

.team-stat-row{
  display:flex;
  justify-content:space-between;
  align-items:center;
  padding:3px 0;
  font-size:.8rem;
  border-bottom:1px solid var(--md-border);
}

.team-stat-row:last-child{border-bottom:none;}
.team-stat-row__lbl{color:var(--md-muted);}
.team-stat-row__val{font-weight:700;}

/* Mistakes board */
.mistakes-panel{
  background: var(--md-card);
  border:1px solid var(--md-border);
  border-radius:14px;
  padding:14px 16px;
}

.mistakes-panel__header{
  display:flex;
  align-items:center;
  gap:8px;
  margin-bottom:12px;
}

.mistakes-panel__title{
  font-family:'Space Grotesk',system-ui,sans-serif;
  font-size:.95rem;
  font-weight:800;
}

.mistake-row{
  display:flex;
  align-items:center;
  gap:10px;
  padding:8px 0;
  border-bottom:1px solid var(--md-border);
}

.mistake-row:last-child{border-bottom:none;}

.mistake-team-lbl{
  font-size:.64rem;
  font-weight:800;
  text-transform:uppercase;
  letter-spacing:.06em;
  color: var(--md-blue);
  display:block;
  margin-bottom:1px;
}

.mistake-name{
  font-size:.84rem;
  font-weight:700;
}

.mistake-metric{
  font-size:.75rem;
  color:var(--md-muted);
}

.mistake-badge{
  margin-left:auto;
  background: oklch(0.82 0.16 85 / 0.18);
  border:1px solid oklch(0.82 0.16 85 / 0.45);
  color: var(--md-yellow);
  font-size:.72rem;
  font-weight:800;
  padding:3px 8px;
  border-radius:8px;
  white-space:nowrap;
  flex-shrink:0;
}

.mistake-badge.danger{
  background: oklch(0.68 0.22 27 / 0.18);
  border-color: oklch(0.68 0.22 27 / 0.45);
  color: var(--md-red);
}

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

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

/* Bottom nav */
.mgr-bottom-nav{
  position:fixed;
  bottom:0;left:0;right:0;
  height:58px;
  background: oklch(0.16 0.038 262 / 0.96);
  border-top:1px solid var(--md-border);
  backdrop-filter:blur(18px);
  display:flex;
  align-items:center;
  justify-content:space-around;
  z-index:1000;
}

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

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

/* Slide-out sidebar */
.mgr-sidebar-overlay{
  display:none;
  position:fixed;inset:0;
  background:oklch(0 0 0 / .55);
  backdrop-filter:blur(2px);
  z-index:2000;
}

.mgr-sidebar{
  position:fixed;
  top:0;left:-310px;
  width:min(290px,86vw);height:100%;
  background: linear-gradient(180deg, oklch(0.18 0.04 262), oklch(0.13 0.035 261));
  border-right:1px solid var(--md-border2);
  box-shadow:18px 0 55px oklch(0 0 0 / .40);
  z-index:2001;
  transition:left .26s ease;
  overflow-y:auto;
}

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

.mgr-sidebar__header{
  padding:20px 18px 16px;
  border-bottom:1px solid var(--md-border);
  display:flex;
  justify-content:space-between;
  align-items:center;
}

.mgr-sidebar__header h5{
  margin:0;
  font-family:'Space Grotesk',system-ui,sans-serif;
  font-weight:800;
  font-size:1rem;
}

.mgr-sidebar__body{padding:12px;}

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

.mgr-sidebar__item i{color:var(--md-blue);width:20px;text-align:center;}
.mgr-sidebar__item:hover,.mgr-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);
}

/* Responsive */
@media(max-width:900px){
  .stat-bar{grid-template-columns:repeat(4,1fr);}
  .charts-row{grid-template-columns:1fr;}
  .bottom-row{grid-template-columns:1fr;}
}

@media(max-width:540px){
  .stat-bar{grid-template-columns:repeat(2,1fr);}
  .mgr-wrapper{padding:14px 12px 76px;}
}
</style>
</head>
<body>

<!-- ===== HEADER ===== -->
<header class="ushs-header">
  <!-- Menu toggle -->
  <button class="ushs-header__menu-btn" onclick="openMgrSidebar()" aria-label="Open menu">
    <i class="fas fa-bars"></i>
  </button>

  <!-- Back button -->
  <a href="dashboard.php" class="ushs-header__back-btn" title="Regular Dashboard">
    <i class="fas fa-chevron-left"></i>
  </a>

  <!-- Brand -->
  <a class="ushs-header__brand" href="manager_dashboard.php">
    <div class="ushs-header__logo">
      <i class="fas fa-chart-pie" style="font-size:16px;"></i>
    </div>
    <div class="ushs-header__brand-text">
      <span class="ushs-header__brand-name">CSR Dashboard</span>
      <span class="ushs-header__brand-sub">Latest: <?= htmlspecialchars($today, ENT_QUOTES, 'UTF-8') ?> &middot; <span id="hdrAgentCount">—</span> agents active</span>
    </div>
  </a>

  <!-- Actions -->
  <div class="ushs-header__actions">
    <!-- Notification -->
    <div class="dropdown">
      <button class="ushs-header__icon-btn" data-bs-toggle="dropdown" aria-label="Notifications">
        <i class="fas fa-bell"></i>
        <?php if ($notifCount > 0): ?>
          <span class="ushs-header__badge"><?= $notifCount ?></span>
        <?php endif; ?>
      </button>
      <div class="dropdown-menu dropdown-menu-end ushs-notif-panel" id="mgrNotifPanel">
        <div class="dropdown-header">
          <span>Notifications</span>
          <a href="notifications.php" style="font-size:.75rem;color:oklch(0.62 0.22 255) !important;">View all</a>
        </div>
        <div id="mgrNotifList" style="padding:12px;text-align:center;color:var(--md-muted);font-size:.8rem;">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">
        <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($mgrName, ENT_QUOTES, 'UTF-8') ?></span>
          <span class="ushs-header__user-role"><?= htmlspecialchars($roleLabel, 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="report.php"><i class="fas fa-file-alt me-2"></i>Reports</a>
        <a class="dropdown-item" href="ranking.php"><i class="fas fa-ranking-star me-2"></i>Ranking</a>
        <a class="dropdown-item" href="manager_announcements.php"><i class="fas fa-bullhorn me-2"></i>Announcements</a>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item text-danger" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a>
      </div>
    </div>
  </div>
</header>

<!-- ===== SIDEBAR ===== -->
<div class="mgr-sidebar-overlay" id="mgrSidebarOverlay" onclick="closeMgrSidebar()"></div>
<aside class="mgr-sidebar" id="mgrSidebar">
  <div class="mgr-sidebar__header">
    <h5>Manager Menu</h5>
    <button class="btn-close" onclick="closeMgrSidebar()"></button>
  </div>
  <nav class="mgr-sidebar__body">
    <a href="manager_dashboard.php" class="mgr-sidebar__item active"><i class="fas fa-chart-pie"></i><span>Manager Dashboard</span></a>
    <a href="dashboard.php"         class="mgr-sidebar__item"><i class="fas fa-home"></i><span>CSR Dashboard</span></a>
    <a href="requests.php"          class="mgr-sidebar__item"><i class="fas fa-clipboard-list"></i><span>Tickets</span></a>
    <a href="report.php"            class="mgr-sidebar__item"><i class="fas fa-chart-line"></i><span>Report</span></a>
    <a href="ranking.php"           class="mgr-sidebar__item"><i class="fas fa-ranking-star"></i><span>Ranking</span></a>
    <a href="manager_announcements.php" class="mgr-sidebar__item"><i class="fas fa-bullhorn"></i><span>Announcements</span></a>
    <a href="technicians.php"       class="mgr-sidebar__item"><i class="fas fa-users-cog"></i><span>Technicians</span></a>
    <a href="calls.php"             class="mgr-sidebar__item"><i class="fas fa-phone-volume"></i><span>Calls</span></a>
    <a href="messages.php"          class="mgr-sidebar__item"><i class="fas fa-comments"></i><span>Messages</span></a>
    <hr style="border-color:var(--md-border);margin:8px 0;">
    <a href="logout.php" class="mgr-sidebar__item" style="color:oklch(0.68 0.22 27) !important;"><i class="fas fa-sign-out-alt" style="color:oklch(0.68 0.22 27) !important;"></i><span>Logout</span></a>
  </nav>
</aside>

<!-- ===== MAIN ===== -->
<main class="mgr-wrapper">

  <!-- Action buttons -->
  <div class="mgr-actions">
    <a href="requests.php" class="mgr-btn">
      <i class="fas fa-clipboard-list"></i> Tickets
    </a>
    <a href="calls.php" class="mgr-btn">
      <i class="fas fa-phone-volume"></i> Calls
    </a>
    <a href="messages.php" class="mgr-btn">
      <i class="fas fa-comments"></i> Messages
    </a>
    <a href="ticket.php" class="mgr-btn">
      <i class="fas fa-ticket-alt"></i> Manual Ticket
    </a>
    <button class="mgr-btn mgr-btn--active" id="btnDailyReport" onclick="openView('daily_report')" style="margin-left:auto;">
      <i class="fas fa-calendar-day"></i> CSR Daily Report
    </button>
    <button class="mgr-btn" id="btnCallTracker" onclick="window.location.href='calls.php'">
      <i class="fas fa-phone-volume"></i> Call Tracker
    </button>
    <button class="mgr-btn" id="btnStatusSummary" onclick="openView('status_summary')">
      <i class="fas fa-chart-bar"></i> Status Summary
    </button>
    <button class="mgr-btn" id="btnRefresh" onclick="loadDashboard()">
      <i class="fas fa-sync-alt" id="refreshIcon"></i> Refresh
    </button>
  </div>

  <!-- ===== STAT BAR ===== -->
  <div class="stat-bar" id="statBar">
    <div class="stat-tile stat-tile--agents">
      <div class="stat-tile__icon"><i class="fas fa-users"></i></div>
      <div class="stat-tile__val" id="statAgents">—</div>
      <div class="stat-tile__lbl">Agents</div>
    </div>
    <div class="stat-tile stat-tile--gh">
      <div class="stat-tile__icon"><i class="fas fa-arrow-trend-up"></i></div>
      <div class="stat-tile__val" id="statGh">—</div>
      <div class="stat-tile__lbl">GH Total</div>
    </div>
    <div class="stat-tile stat-tile--sched">
      <div class="stat-tile__icon"><i class="fas fa-clock"></i></div>
      <div class="stat-tile__val" id="statSchedule">—</div>
      <div class="stat-tile__lbl">Schedule</div>
    </div>
    <div class="stat-tile stat-tile--attempt">
      <div class="stat-tile__icon"><i class="fas fa-phone"></i></div>
      <div class="stat-tile__val" id="statAttempt">—</div>
      <div class="stat-tile__lbl">Attempt</div>
    </div>
    <div class="stat-tile stat-tile--update">
      <div class="stat-tile__icon"><i class="fas fa-comment-dots"></i></div>
      <div class="stat-tile__val" id="statUpdate">—</div>
      <div class="stat-tile__lbl">Update</div>
    </div>
    <div class="stat-tile stat-tile--warn">
      <div class="stat-tile__icon"><i class="fas fa-triangle-exclamation"></i></div>
      <div class="stat-tile__val" id="statWarn">—</div>
      <div class="stat-tile__lbl">Warnings</div>
    </div>
    <div class="stat-tile stat-tile--mistakes">
      <div class="stat-tile__icon"><i class="fas fa-clock-rotate-left"></i></div>
      <div class="stat-tile__val" id="statMistakes">—</div>
      <div class="stat-tile__lbl">Mistakes</div>
    </div>
  </div>

  <!-- ===== CHARTS ROW ===== -->
  <div class="charts-row">
    <!-- Team Performance bar chart -->
    <div class="mgr-panel">
      <div class="mgr-panel__title">Team Performance</div>
      <div style="position:relative;height:220px;">
        <canvas id="teamPerfChart"></canvas>
      </div>
    </div>

    <!-- Task Status pie chart -->
    <div class="mgr-panel">
      <div class="mgr-panel__title">Task Status</div>
      <div style="position:relative;height:220px;">
        <canvas id="taskStatusChart"></canvas>
      </div>
    </div>
  </div>

  <!-- ===== 10-DAY TREND ===== -->
  <div class="mgr-panel trend-panel">
    <div class="mgr-panel__title">10-Day Trend</div>
    <div style="position:relative;height:200px;">
      <canvas id="trendChart"></canvas>
    </div>
  </div>

  <!-- ===== BOTTOM ROW ===== -->
  <div class="bottom-row" id="bottomRow">
    <!-- Team cards injected by JS -->
    <div class="col-span-2" id="teamCardsArea" style="grid-column:span 2;display:grid;grid-template-columns:1fr 1fr;gap:16px;">
      <div class="team-card skeleton" style="height:160px;"></div>
      <div class="team-card skeleton" style="height:160px;"></div>
    </div>

    <!-- Recent Mistakes -->
    <div class="mistakes-panel">
      <div class="mistakes-panel__header">
        <i class="fas fa-triangle-exclamation" style="color:oklch(0.82 0.16 85);"></i>
        <span class="mistakes-panel__title">Recent Mistakes</span>
        <span class="ushs-header__badge" id="mistakeBadge" style="position:static;background:oklch(0.82 0.16 85 / 0.22);border:1px solid oklch(0.82 0.16 85 / 0.45);color:var(--md-yellow);">0</span>
      </div>
      <div id="mistakesBoard">
        <div style="text-align:center;color:var(--md-muted);font-size:.8rem;padding:20px 0;">Loading…</div>
      </div>
    </div>
  </div>

</main>

<!-- ===== BOTTOM NAV ===== -->
<nav class="mgr-bottom-nav">
  <a href="manager_dashboard.php" class="mgr-nav-item active"><i class="fas fa-chart-pie"></i><span>Overview</span></a>
  <a href="report.php"            class="mgr-nav-item"><i class="fas fa-chart-line"></i><span>Report</span></a>
  <a href="ranking.php"           class="mgr-nav-item"><i class="fas fa-ranking-star"></i><span>Ranking</span></a>
  <a href="requests.php"          class="mgr-nav-item"><i class="fas fa-clipboard-list"></i><span>Tickets</span></a>
  <a href="manager_announcements.php" class="mgr-nav-item"><i class="fas fa-bullhorn"></i><span>Announce</span></a>
</nav>

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

<script>
/* =====================================================
   Manager Dashboard JS
===================================================== */
const CHART_CFG = {
  ghColor:       'rgba(96,165,250,.85)',
  schedColor:    'rgba(52,211,153,.90)',
  attemptColor:  'rgba(167,139,250,.85)',
  updateColor:   'rgba(251,146,60,.85)',
  mistakeColor:  'rgba(248,113,113,.85)',
  gridColor:     'rgba(255,255,255,.06)',
  tickColor:     'rgba(255,255,255,.55)',
  fontSize:      11,
};

let teamPerfChart = null, taskStatusChart = null, trendChart = null;

// ---- Sidebar ----
function openMgrSidebar(){
  document.getElementById('mgrSidebar').classList.add('open');
  document.getElementById('mgrSidebarOverlay').style.display = 'block';
}
function closeMgrSidebar(){
  document.getElementById('mgrSidebar').classList.remove('open');
  document.getElementById('mgrSidebarOverlay').style.display = 'none';
}
document.addEventListener('keydown', e => { if(e.key==='Escape') closeMgrSidebar(); });

// ---- View routing ----
function openView(view) {
  if (view === 'daily_report')   window.location.href = 'report.php';
  if (view === 'status_summary') window.location.href = 'requests.php';
}

// ---- Load dashboard data ----
function loadDashboard() {
  const icon = document.getElementById('refreshIcon');
  icon.classList.add('fa-spin');

  $.ajax({
    url: 'ajax/get_manager_dashboard.php',
    method: 'GET',
    dataType: 'json',
    success: function(res) {
      if (!res.success) { console.error(res.message); return; }
      renderStats(res.summary);
      renderTeamPerf(res.team_stats);
      renderTaskStatus(res.task_status);
      renderTrend(res.trend);
      renderTeamCards(res.team_stats);
      renderMistakes(res.mistakes);
      document.getElementById('hdrAgentCount').textContent = res.summary.agents || 0;
    },
    error: function(e){ console.error(e); },
    complete: function(){ icon.classList.remove('fa-spin'); }
  });
}

// ---- Stats ----
function renderStats(s) {
  animateCount('statAgents',   s.agents   || 0);
  animateCount('statGh',       s.gh       || 0);
  animateCount('statSchedule', s.schedule || 0);
  animateCount('statAttempt',  s.attempt  || 0);
  animateCount('statUpdate',   s.update   || 0);
  animateCount('statWarn',     s.warnings || 0);
  animateCount('statMistakes', s.mistakes || 0);
}

function animateCount(id, target) {
  const el = document.getElementById(id);
  if (!el) return;
  const start = parseInt(el.textContent) || 0;
  const steps = 20;
  let i = 0;
  const step = () => {
    i++;
    el.textContent = Math.round(start + (target - start) * (i / steps));
    if (i < steps) requestAnimationFrame(step);
    else el.textContent = target;
  };
  requestAnimationFrame(step);
}

// ---- Team Performance chart ----
function renderTeamPerf(teamStats) {
  const labels = teamStats.map(t => t.team_name.replace('Team ', '').replace('TEAM ', ''));
  const ghData      = teamStats.map(t => t.gh);
  const schedData   = teamStats.map(t => t.schedule);
  const attemptData = teamStats.map(t => t.attempt);

  const ctx = document.getElementById('teamPerfChart').getContext('2d');
  if (teamPerfChart) teamPerfChart.destroy();

  teamPerfChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels,
      datasets: [
        { label: 'GH',       data: ghData,      backgroundColor: CHART_CFG.ghColor,      borderRadius: 4, barPercentage: 0.25 },
        { label: 'Schedule', data: schedData,   backgroundColor: CHART_CFG.schedColor,   borderRadius: 4, barPercentage: 0.25 },
        { label: 'Attempt',  data: attemptData, backgroundColor: CHART_CFG.attemptColor, borderRadius: 4, barPercentage: 0.25 },
      ]
    },
    options: chartOptions()
  });
}

// ---- Task Status donut ----
function renderTaskStatus(taskStatus) {
  if (!taskStatus || !taskStatus.length) return;

  const labels = taskStatus.map(t => t.status_name);
  const data   = taskStatus.map(t => parseInt(t.cnt) || 0);
  const colors = taskStatus.map(t => t.color_code || '#4fc3f7');

  const ctx = document.getElementById('taskStatusChart').getContext('2d');
  if (taskStatusChart) taskStatusChart.destroy();

  taskStatusChart = new Chart(ctx, {
    type: 'doughnut',
    data: { labels, datasets: [{ data, backgroundColor: colors, borderWidth: 1, borderColor: 'oklch(0.18 0.04 262)' }] },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      cutout: '60%',
      plugins: {
        legend: {
          position: 'right',
          labels: {
            color: CHART_CFG.tickColor,
            font: { size: CHART_CFG.fontSize - 1, family: 'Inter' },
            boxWidth: 10,
            padding: 6,
          }
        },
        tooltip: tooltipPlugin()
      }
    }
  });
}

// ---- 10-day trend chart ----
function renderTrend(trend) {
  const labels   = trend.map(t => t.label);
  const ghData   = trend.map(t => t.gh);
  const schedData= trend.map(t => t.schedule);
  const mistData = trend.map(t => t.mistakes);

  const ctx = document.getElementById('trendChart').getContext('2d');
  if (trendChart) trendChart.destroy();

  trendChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels,
      datasets: [
        { label: 'GH',       data: ghData,    backgroundColor: CHART_CFG.schedColor,  borderRadius: 4, barPercentage: 0.3 },
        { label: 'Schedule', data: schedData, backgroundColor: CHART_CFG.ghColor,     borderRadius: 4, barPercentage: 0.3 },
        { label: 'Mistakes', data: mistData,  backgroundColor: CHART_CFG.mistakeColor,borderRadius: 4, barPercentage: 0.3 },
      ]
    },
    options: chartOptions()
  });
}

// ---- Team cards ----
function renderTeamCards(teamStats) {
  const area = document.getElementById('teamCardsArea');
  if (!teamStats.length) { area.innerHTML = '<div style="color:var(--md-muted);font-size:.8rem;">No teams found.</div>'; return; }

  const cols = teamStats.length <= 2 ? 2 : Math.min(teamStats.length, 4);
  area.style.gridTemplateColumns = `repeat(${Math.min(cols, 2)}, 1fr)`;

  area.innerHTML = teamStats.map(t => {
    const nameColor = ['var(--md-cyan)','var(--md-green)','var(--md-purple)','var(--md-yellow)'];
    const teamIdx = teamStats.indexOf(t) % nameColor.length;
    return `
      <div class="team-card">
        <div class="team-card__name" style="color:${nameColor[teamIdx]}">${escHtml(t.team_name)}</div>
        <div class="team-stat-row"><span class="team-stat-row__lbl">Agents</span><span class="team-stat-row__val">${t.agents}</span></div>
        <div class="team-stat-row"><span class="team-stat-row__lbl">GH</span><span class="team-stat-row__val">${t.gh}</span></div>
        <div class="team-stat-row"><span class="team-stat-row__lbl">Schedule</span><span class="team-stat-row__val" style="color:var(--md-cyan)">${t.schedule}</span></div>
        <div class="team-stat-row"><span class="team-stat-row__lbl">Attempt</span><span class="team-stat-row__val">${t.attempt}</span></div>
        <div class="team-stat-row"><span class="team-stat-row__lbl">Warnings</span><span class="team-stat-row__val" style="color:var(--md-yellow)">${t.warnings}</span></div>
        <div class="team-stat-row"><span class="team-stat-row__lbl">Mistakes</span><span class="team-stat-row__val" style="color:var(--md-red)">${t.mistakes}</span></div>
      </div>`;
  }).join('');
}

// ---- Mistakes board ----
function renderMistakes(mistakes) {
  const board  = document.getElementById('mistakesBoard');
  const badge  = document.getElementById('mistakeBadge');
  const total  = mistakes.reduce((s,m) => s + m.mistakes, 0);
  badge.textContent = total;

  if (!mistakes.length) {
    board.innerHTML = '<div style="text-align:center;color:var(--md-muted);font-size:.8rem;padding:20px 0;">No mistakes recorded.</div>';
    return;
  }

  board.innerHTML = mistakes.map(m => {
    const cls = m.mistakes >= 5 ? 'danger' : '';
    const metric = m.schedule || m.attempt
      ? `${m.schedule || 0}/${m.attempt || 0}`
      : '—';
    return `
      <div class="mistake-row">
        <div>
          <span class="mistake-team-lbl">${escHtml(m.team)}</span>
          <span class="mistake-name">${escHtml(m.name)}</span>
          <span class="mistake-metric">${metric}</span>
        </div>
        <span class="mistake-badge ${cls}"><i class="fas fa-triangle-exclamation me-1"></i>${m.mistakes}</span>
      </div>`;
  }).join('');
}

// ---- Chart helpers ----
function chartOptions() {
  return {
    responsive: true,
    maintainAspectRatio: false,
    plugins: {
      legend: {
        labels: {
          color: CHART_CFG.tickColor,
          font: { size: CHART_CFG.fontSize, family: 'Inter' },
          boxWidth: 10,
          padding: 10,
        }
      },
      tooltip: tooltipPlugin()
    },
    scales: {
      x: {
        grid: { color: CHART_CFG.gridColor },
        ticks: { color: CHART_CFG.tickColor, font: { size: CHART_CFG.fontSize - 1 } }
      },
      y: {
        beginAtZero: true,
        grid: { color: CHART_CFG.gridColor },
        ticks: { color: CHART_CFG.tickColor, font: { size: CHART_CFG.fontSize - 1 } }
      }
    }
  };
}

function tooltipPlugin() {
  return {
    backgroundColor: 'oklch(0.18 0.04 262)',
    borderColor: 'oklch(0.98 0.005 250 / 0.18)',
    borderWidth: 1,
    titleColor: '#fff',
    bodyColor: 'rgba(255,255,255,.75)',
    padding: 10,
    cornerRadius: 10,
  };
}

// ---- Notifications ----
function loadNotifications() {
  $.ajax({
    url: 'ajax/get_notifications.php',
    method: 'GET',
    data: { limit: 5 },
    dataType: 'json',
    success: function(res) {
      if (!res.success) return;
      const list = document.getElementById('mgrNotifList');
      if (!res.notifications || !res.notifications.length) {
        list.innerHTML = '<div style="padding:10px 0;color:var(--md-muted);">No new notifications</div>';
        return;
      }
      list.innerHTML = res.notifications.map(n => `
        <div class="notif-item ${n.is_read ? '' : 'unread'}" onclick="markNotifRead(${n.id}, '${escHtml(n.link || '')}')">
          <div class="notif-icon" style="background:oklch(0.62 0.22 255 / 0.15)"><i class="fas fa-bell" style="color:oklch(0.62 0.22 255);"></i></div>
          <div class="notif-body">
            <strong>${escHtml(n.title)}</strong>
            <small>${escHtml((n.message || '').substring(0, 80))}${(n.message || '').length > 80 ? '…' : ''}</small>
          </div>
        </div>`).join('');
    }
  });
}

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

// ---- Utils ----
function escHtml(str) {
  return String(str || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
}

// ---- Boot ----
$(document).ready(function() {
  loadDashboard();
  loadNotifications();
  setInterval(loadDashboard, 60000);
  setInterval(loadNotifications, 15000);
});
</script>
</body>
</html>
