<?php
// team_leader/dashboard.php — Team Leader dashboard using CSR Agent/Manager theme
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['csr_id'])) { header('Location: ../login.php'); exit(); }
if (($_SESSION['csr_role'] ?? 'csr') !== 'team_leader') {
    if (($_SESSION['csr_role'] ?? 'csr') === 'csr_manager') { header('Location: ../csr_manager/dashboard.php'); exit(); }
    header('Location: ../csr/dashboard.php');
    exit();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/app_helpers.php';
require_once __DIR__ . '/../includes/discipline_system.php';
$db = (new Database())->getConnection();
discEnsureTables($db);
$leaderId = (int)$_SESSION['csr_id'];
$title = 'Dashboard';

function tlCount(PDO $db, string $sql, array $params = []): int {
    try { $s = $db->prepare($sql); $s->execute($params); return (int)$s->fetchColumn(); }
    catch(Exception $e) { return 0; }
}
function tlRows(PDO $db, string $sql, array $params = []): array {
    try { $s = $db->prepare($sql); $s->execute($params); return $s->fetchAll(PDO::FETCH_ASSOC); }
    catch(Exception $e) { return []; }
}
function tlDate($v): string { return $v ? date('M j, Y g:i A', strtotime($v)) : '—'; }
function tlStatusBadge($status): string {
    $s = strtolower((string)$status);
    $cls = str_contains($s,'complete') ? 'success' : (str_contains($s,'progress') ? 'primary' : (str_contains($s,'cancel') ? 'danger' : (str_contains($s,'assign') ? 'info' : 'secondary')));
    return '<span class="badge bg-'.$cls.'">'.htmlspecialchars($status ?: 'New', ENT_QUOTES, 'UTF-8').'</span>';
}
function tlCallStatusBadge($status): string {
    $s = strtolower((string)$status);
    $cls = in_array($s, ['accepted','completed','connected'], true) ? 'success' : (in_array($s, ['missed','cancelled','no_answer'], true) ? 'warning' : 'info');
    return '<span class="badge bg-'.$cls.'">'.htmlspecialchars(ucwords(str_replace('_',' ', $status ?: 'Pending')), ENT_QUOTES, 'UTF-8').'</span>';
}
function tlInClause(string $field, array $ids, string $prefix, array &$params): string {
    $placeholders = [];
    foreach (array_values(array_unique(array_map('intval', $ids))) as $i => $id) {
        $ph = ':' . $prefix . $i;
        $placeholders[] = $ph;
        $params[$ph] = $id;
    }
    return $field . ' IN (' . implode(',', $placeholders ?: ['NULL']) . ')';
}

function tlDashboardStats(PDO $db, array $ids, string $prefix): array {
    $ids = array_values(array_unique(array_map('intval', $ids)));
    $zero = [
        'handled_today'=>0, 'assigned'=>0, 'in_progress'=>0, 'completed'=>0, 'cancelled'=>0,
        'total_calls'=>0, 'scheduled_calls'=>0, 'connected_calls'=>0, 'missed_calls'=>0,
        'updates'=>0, 'warnings'=>0, 'mistakes'=>0
    ];
    if (!$ids) return $zero;

    $params = [];
    $requestClause = '(' . tlInClause('assigned_csr_id', $ids, $prefix.'ra', $params) . ' OR ' . tlInClause('handled_by_csr_id', $ids, $prefix.'rh', $params) . ' OR ' . tlInClause('created_by_csr_id', $ids, $prefix.'rc', $params) . ')';
    $stats = $zero;
    $stats['handled_today'] = tlCount($db, "SELECT COUNT(*) FROM service_requests WHERE $requestClause AND DATE(COALESCE(last_updated_at, completed_date, requested_at)) = CURDATE()", $params);
    $stats['assigned'] = tlCount($db, "SELECT COUNT(*) FROM service_requests WHERE $requestClause AND COALESCE(job_status_id, 1) NOT IN (4, 5)", $params);
    $stats['in_progress'] = tlCount($db, "SELECT COUNT(*) FROM service_requests WHERE $requestClause AND job_status_id = 3", $params);
    $stats['completed'] = tlCount($db, "SELECT COUNT(*) FROM service_requests WHERE $requestClause AND job_status_id = 4 AND DATE(COALESCE(completed_date, last_updated_at, requested_at)) = CURDATE()", $params);
    $stats['cancelled'] = tlCount($db, "SELECT COUNT(*) FROM service_requests WHERE $requestClause AND job_status_id = 5 AND DATE(COALESCE(last_updated_at, requested_at)) = CURDATE()", $params);

    $callParams = [];
    $callClause = '(' . tlInClause('assigned_csr_id', $ids, $prefix.'ca', $callParams) . ' OR ' . tlInClause('accepted_by', $ids, $prefix.'cb', $callParams) . ')';
    $stats['total_calls'] = tlCount($db, "SELECT COUNT(*) FROM call_requests WHERE $callClause AND DATE(queued_at) = CURDATE()", $callParams);
    $stats['scheduled_calls'] = tlCount($db, "SELECT COUNT(*) FROM call_requests WHERE $callClause AND status IN ('assigned','manager_queue','scheduled','pending') AND DATE(queued_at) = CURDATE()", $callParams);
    $stats['connected_calls'] = tlCount($db, "SELECT COUNT(*) FROM call_requests WHERE $callClause AND status IN ('accepted','completed','connected') AND DATE(queued_at) = CURDATE()", $callParams);
    $stats['missed_calls'] = tlCount($db, "SELECT COUNT(*) FROM call_requests WHERE $callClause AND status IN ('missed','no_answer','no answer','cancelled') AND DATE(queued_at) = CURDATE()", $callParams);

    $activityParams = [];
    $activityClause = tlInClause('csr_id', $ids, $prefix.'act', $activityParams);
    $stats['updates'] = tlCount($db, "SELECT COUNT(*) FROM csr_activity WHERE $activityClause AND (action IN ('status_change','note_added','request_claimed','manual_ticket_created') OR action LIKE '%update%') AND DATE(created_at) = CURDATE()", $activityParams);
    $stats['warnings'] = tlCount($db, "SELECT COUNT(*) FROM csr_activity WHERE $activityClause AND (action LIKE '%warning%' OR details LIKE '%warning%') AND DATE(created_at) = CURDATE()", $activityParams);
    $discWarnParams = [];
    $discWarnClause = tlInClause('recipient_id', $ids, $prefix.'dw', $discWarnParams);
    $stats['warnings'] += tlCount($db, "SELECT COUNT(*) FROM csr_discipline_records WHERE $discWarnClause AND record_type='warning' AND DATE(created_at) = CURDATE()", $discWarnParams);

    $stats['mistakes'] = tlCount($db, "SELECT COUNT(*) FROM csr_activity WHERE $activityClause AND (action LIKE '%mistake%' OR action LIKE '%error%' OR details LIKE '%mistake%' OR details LIKE '%error%') AND DATE(created_at) = CURDATE()", $activityParams);
    $discMistParams = [];
    $discMistClause = tlInClause('recipient_id', $ids, $prefix.'dm', $discMistParams);
    $stats['mistakes'] += tlCount($db, "SELECT COUNT(*) FROM csr_discipline_records WHERE $discMistClause AND record_type='mistake' AND DATE(created_at) = CURDATE()", $discMistParams);
    return $stats;
}

$leader = tlRows($db, "SELECT * FROM csr_users WHERE id = :id LIMIT 1", [':id' => $leaderId]);
$leader = $leader[0] ?? [];
$name = trim(($leader['first_name'] ?? '').' '.($leader['last_name'] ?? '')) ?: ($_SESSION['csr_name'] ?? 'Team Leader');
$email = $leader['email'] ?? ($_SESSION['csr_email'] ?? '—');
$phone = $leader['phone_number'] ?? '—';
$lastLogin = $leader['last_login'] ?? null;
$roleDisplay = 'Team Leader';

$team = tlRows($db, "SELECT * FROM csr_teams WHERE manager_id = :leader_id AND is_active = 1 ORDER BY id ASC LIMIT 1", [':leader_id' => $leaderId]);
$team = $team[0] ?? null;
$teamId = (int)($team['id'] ?? 0);
$teamLabel = 'Team ' . $name;

$agents = [];
if ($teamId > 0) {
    $agents = tlRows($db, "
        SELECT cu.id, cu.first_name, cu.last_name, cu.email, cu.phone_number, cu.role, cu.is_active, cu.last_login
        FROM csr_team_members ctm
        INNER JOIN csr_users cu ON cu.id = ctm.csr_id
        WHERE ctm.team_id = :team_id
        ORDER BY cu.first_name, cu.last_name
    ", [':team_id' => $teamId]);
}
$agentIds = array_map(fn($a) => (int)$a['id'], $agents);
$myStats = tlDashboardStats($db, [$leaderId], 'my');
$teamStats = tlDashboardStats($db, $agentIds, 'team');

// Combined scope is used only for recent activity lists.
$scopeIds = array_values(array_unique(array_merge([$leaderId], $agentIds)));
$params = [];
$assignedClause = '(' . tlInClause('assigned_csr_id', $scopeIds, 'a', $params) . ' OR ' . tlInClause('handled_by_csr_id', $scopeIds, 'h', $params) . ' OR ' . tlInClause('created_by_csr_id', $scopeIds, 'c', $params) . ')';
$callParams = [];
$callClause = '(' . tlInClause('assigned_csr_id', $scopeIds, 'ca', $callParams) . ' OR ' . tlInClause('accepted_by', $scopeIds, 'cb', $callParams) . ')';
$activityParams = [];
$activityClause = tlInClause('ca.csr_id', $scopeIds, 'act', $activityParams);

$recentTickets = tlRows($db, "
    SELECT ca.created_at AS activity_at, ca.action, ca.details, sr.id, sr.request_number, sr.full_name,
           COALESCE(b.name, sr.manual_brand, '—') AS brand,
           COALESCE(c.city_name, sr.service_address, '—') AS city,
           COALESCE(js.status_name, 'New Request') AS status_name,
           CONCAT(cu.first_name, ' ', cu.last_name) AS csr_name
    FROM csr_activity ca
    LEFT JOIN csr_users cu ON cu.id = ca.csr_id
    LEFT JOIN service_requests sr ON sr.id = ca.request_id
    LEFT JOIN brands b ON b.id = sr.brand_id
    LEFT JOIN cities c ON c.id = sr.city_id
    LEFT JOIN job_statuses js ON js.id = sr.job_status_id
    WHERE $activityClause
    ORDER BY ca.created_at DESC
    LIMIT 8
", $activityParams);

if (!$recentTickets) {
    $recentTickets = tlRows($db, "
        SELECT COALESCE(sr.last_updated_at, sr.requested_at) AS activity_at, sr.id, sr.request_number, sr.full_name,
               COALESCE(b.name, sr.manual_brand, '—') AS brand,
               COALESCE(c.city_name, sr.service_address, '—') AS city,
               COALESCE(js.status_name, 'New Request') AS status_name,
               '—' AS csr_name
        FROM service_requests sr
        LEFT JOIN brands b ON b.id = sr.brand_id
        LEFT JOIN cities c ON c.id = sr.city_id
        LEFT JOIN job_statuses js ON js.id = sr.job_status_id
        WHERE $assignedClause
        ORDER BY COALESCE(sr.last_updated_at, sr.requested_at) DESC
        LIMIT 8
    ", $params);
}

$recentCalls = tlRows($db, "
    SELECT cr.*, COALESCE(sr.request_number, '—') AS request_number,
           COALESCE(b.name, sr.manual_brand, '—') AS brand,
           COALESCE(c.city_name, sr.service_address, '—') AS city,
           CONCAT(cu.first_name, ' ', cu.last_name) AS csr_name
    FROM call_requests cr
    LEFT JOIN csr_users cu ON cu.id = COALESCE(cr.accepted_by, cr.assigned_csr_id)
    LEFT JOIN service_requests sr ON sr.id = cr.request_id
    LEFT JOIN brands b ON b.id = sr.brand_id
    LEFT JOIN cities c ON c.id = sr.city_id
    WHERE $callClause
    ORDER BY cr.queued_at DESC
    LIMIT 8
", $callParams);

$discParams = [];
$discScopeClause = tlInClause('dr.recipient_id', $scopeIds, 'disc', $discParams);
$recentWarnings = tlRows($db, "
    SELECT dr.*, CONCAT(r.first_name, ' ', r.last_name) AS recipient_name,
           CASE WHEN dr.sender_role = 'admin'
                THEN TRIM(CONCAT(COALESCE(au.first_name,''),' ',COALESCE(au.last_name,'')))
                ELSE TRIM(CONCAT(COALESCE(s.first_name,''),' ',COALESCE(s.last_name,'')))
           END AS sender_name
    FROM csr_discipline_records dr
    LEFT JOIN csr_users r ON r.id = dr.recipient_id
    LEFT JOIN csr_users s ON s.id = dr.sender_id AND dr.sender_role <> 'admin'
    LEFT JOIN admin_users au ON au.id = dr.sender_id AND dr.sender_role = 'admin'
    WHERE $discScopeClause AND dr.record_type = 'warning'
    ORDER BY dr.created_at DESC
    LIMIT 8
", $discParams);

$discMistParams = [];
$discMistScopeClause = tlInClause('dr.recipient_id', $scopeIds, 'discm', $discMistParams);
$recentMistakes = tlRows($db, "
    SELECT dr.*, CONCAT(r.first_name, ' ', r.last_name) AS recipient_name,
           CASE WHEN dr.sender_role = 'admin'
                THEN TRIM(CONCAT(COALESCE(au.first_name,''),' ',COALESCE(au.last_name,'')))
                ELSE TRIM(CONCAT(COALESCE(s.first_name,''),' ',COALESCE(s.last_name,'')))
           END AS sender_name
    FROM csr_discipline_records dr
    LEFT JOIN csr_users r ON r.id = dr.recipient_id
    LEFT JOIN csr_users s ON s.id = dr.sender_id AND dr.sender_role <> 'admin'
    LEFT JOIN admin_users au ON au.id = dr.sender_id AND dr.sender_role = 'admin'
    WHERE $discMistScopeClause AND dr.record_type = 'mistake'
    ORDER BY dr.created_at DESC
    LIMIT 8
", $discMistParams);


ob_start();
?>
<style>
.tl-disc-row{cursor:pointer;}
.tl-disc-row:hover{background:rgba(255,255,255,.045);}
.tl-disc-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.62);display:none;align-items:center;justify-content:center;z-index:9999;padding:18px;}
.tl-disc-backdrop.is-open{display:flex;}
.tl-disc-modal{width:min(680px,96vw);max-height:86vh;overflow:auto;background:var(--cm-card,#111827);border:1px solid var(--cm-border,rgba(255,255,255,.14));border-radius:18px;box-shadow:0 22px 80px rgba(0,0,0,.5);color:var(--cm-text,#fff);}
.tl-disc-head{display:flex;justify-content:space-between;gap:12px;padding:16px 18px;border-bottom:1px solid var(--cm-border,rgba(255,255,255,.14));}
.tl-disc-title{font-weight:900;font-size:1.05rem;margin:0;}
.tl-disc-sub{font-size:.78rem;color:var(--cm-muted,#94a3b8);font-weight:700;margin-top:4px;}
.tl-disc-close{border:1px solid var(--cm-border,rgba(255,255,255,.14));background:transparent;color:inherit;border-radius:10px;width:34px;height:34px;font-weight:900;}
.tl-disc-body{padding:16px 18px;}
.tl-disc-message{white-space:pre-wrap;line-height:1.45;font-size:.9rem;}
.tl-disc-meta{margin-top:12px;color:var(--cm-muted,#94a3b8);font-size:.75rem;font-weight:700;}
.tl-disc-filter{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0 10px;}
.tl-disc-filter select,.tl-disc-filter input{height:32px;border:1px solid var(--cm-border,#334155);border-radius:10px;background:#0f172a;color:#e5e7eb!important;-webkit-text-fill-color:#e5e7eb!important;font-size:.74rem;font-weight:800;padding:0 10px;outline:none;}
.tl-disc-filter input{min-width:150px;flex:1;}
.tl-disc-empty{display:none;}
</style>

<div class="ca-quick-bar">
  <a class="cm-btn" href="dashboard.php"><i class="fas fa-chart-pie"></i> Dashboard</a>
  <a class="cm-btn" href="team_agents.php"><i class="fas fa-user-group"></i> Team Agents</a>
  <a class="cm-btn" href="team_requests.php"><i class="fas fa-users-gear"></i> Team Requests</a>
  <a class="cm-btn" href="team_performance.php"><i class="fas fa-chart-line"></i> Team Performance</a>
  <a class="cm-btn" href="messages.php"><i class="fas fa-comments"></i> Messages</a>
  <a class="cm-btn" href="mistake.php"><i class="fas fa-circle-exclamation"></i> Mistake</a>
  <a class="cm-btn" href="warning.php"><i class="fas fa-triangle-exclamation"></i> Warning</a>
</div>

<div class="cm-card mb-3">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3">
    <div class="flex-grow-1">
      <div class="cm-card__title mb-1">Profile</div>
      <h2 class="mb-2" style="font-family:'Space Grotesk',system-ui,sans-serif;font-weight:900;">Welcome, <?= htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?></h2>
      <div class="row g-2">
        <div class="col-md-6 col-xl-3"><div class="ca-profile-chip"><i class="fas fa-id-badge"></i><span>Position</span><strong><?= htmlspecialchars($roleDisplay, ENT_QUOTES, 'UTF-8') ?></strong></div></div>
        <div class="col-md-6 col-xl-3"><div class="ca-profile-chip"><i class="fas fa-envelope"></i><span>Email</span><strong><?= htmlspecialchars($email, ENT_QUOTES, 'UTF-8') ?></strong></div></div>
        <div class="col-md-6 col-xl-3"><div class="ca-profile-chip"><i class="fas fa-phone"></i><span>Phone</span><strong><?= htmlspecialchars($phone ?: '—', ENT_QUOTES, 'UTF-8') ?></strong></div></div>
        <div class="col-md-6 col-xl-3"><div class="ca-profile-chip"><i class="fas fa-clock"></i><span>Last login</span><strong><?= htmlspecialchars(tlDate($lastLogin), ENT_QUOTES, 'UTF-8') ?></strong></div></div>
      </div>
    </div>
    <span class="badge bg-primary">Team Leader Workspace</span>
  </div>
</div>

<div class="cm-card mb-3">
  <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
    <div>
      <div class="cm-card__title mb-1"><?= htmlspecialchars($teamLabel, ENT_QUOTES, 'UTF-8') ?></div>
      <div class="text-muted">CSR agents that belong to this Team Leader</div>
    </div>
    <span class="badge bg-info"><?= count($agents) ?> Agent<?= count($agents) === 1 ? '' : 's' ?></span>
  </div>
  <div class="table-responsive">
    <table class="table table-sm align-middle mb-0">
      <thead><tr><th>CSR Agent</th><th>Email</th><th>Phone</th><th>Status</th><th>Recent Login</th></tr></thead>
      <tbody>
      <?php if (!$agents): ?><tr><td colspan="5" class="text-center text-muted py-4">No CSR agents assigned to this team yet.</td></tr><?php endif; ?>
      <?php foreach ($agents as $agent): ?>
        <tr>
          <td><strong><?= htmlspecialchars(trim(($agent['first_name'] ?? '').' '.($agent['last_name'] ?? '')) ?: 'CSR Agent', ENT_QUOTES, 'UTF-8') ?></strong><br><small class="text-muted">CSR Agent</small></td>
          <td><?= htmlspecialchars($agent['email'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($agent['phone_number'] ?: '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= ((int)($agent['is_active'] ?? 0) === 1) ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>' ?></td>
          <td><?= htmlspecialchars(tlDate($agent['last_login'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<div class="cm-card mb-3">
  <div class="cm-card__title mb-3">My Activity Today</div>
  <div class="ca-stat-grid">
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-headset"></i></div><div class="ca-stat__value"><?= (int)$myStats['handled_today'] ?></div><div class="ca-stat__label">Handled Today</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-user-check"></i></div><div class="ca-stat__value" style="color:var(--cm-cyan)"><?= (int)$myStats['assigned'] ?></div><div class="ca-stat__label">Assigned Tickets</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-spinner"></i></div><div class="ca-stat__value" style="color:var(--cm-blue)"><?= (int)$myStats['in_progress'] ?></div><div class="ca-stat__label">In Progress</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-check-circle"></i></div><div class="ca-stat__value" style="color:var(--cm-green)"><?= (int)$myStats['completed'] ?></div><div class="ca-stat__label">Completed Today</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-ban"></i></div><div class="ca-stat__value" style="color:var(--cm-red)"><?= (int)$myStats['cancelled'] ?></div><div class="ca-stat__label">Cancelled Today</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-phone"></i></div><div class="ca-stat__value"><?= (int)$myStats['total_calls'] ?></div><div class="ca-stat__label">Total Calls</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-calendar-check"></i></div><div class="ca-stat__value" style="color:var(--cm-cyan)"><?= (int)$myStats['scheduled_calls'] ?></div><div class="ca-stat__label">Calls Scheduled</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-phone-volume"></i></div><div class="ca-stat__value" style="color:var(--cm-green)"><?= (int)$myStats['connected_calls'] ?></div><div class="ca-stat__label">Connected</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-phone-slash"></i></div><div class="ca-stat__value" style="color:var(--cm-yellow)"><?= (int)$myStats['missed_calls'] ?></div><div class="ca-stat__label">Missed / Absent</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-pen-to-square"></i></div><div class="ca-stat__value" style="color:var(--cm-blue)"><?= (int)$myStats['updates'] ?></div><div class="ca-stat__label">Updates</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-triangle-exclamation"></i></div><div class="ca-stat__value" style="color:var(--cm-yellow)"><?= (int)$myStats['warnings'] ?></div><div class="ca-stat__label">Warnings</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-circle-exclamation"></i></div><div class="ca-stat__value" style="color:var(--cm-red)"><?= (int)$myStats['mistakes'] ?></div><div class="ca-stat__label">Mistakes</div></div>
  </div>
</div>
<div class="cm-card mb-3">
  <div class="cm-card__title mb-3">Team Activity Today</div>
  <div class="ca-stat-grid">
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-headset"></i></div><div class="ca-stat__value"><?= (int)$teamStats['handled_today'] ?></div><div class="ca-stat__label">Handled Today</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-user-check"></i></div><div class="ca-stat__value" style="color:var(--cm-cyan)"><?= (int)$teamStats['assigned'] ?></div><div class="ca-stat__label">Assigned Tickets</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-spinner"></i></div><div class="ca-stat__value" style="color:var(--cm-blue)"><?= (int)$teamStats['in_progress'] ?></div><div class="ca-stat__label">In Progress</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-check-circle"></i></div><div class="ca-stat__value" style="color:var(--cm-green)"><?= (int)$teamStats['completed'] ?></div><div class="ca-stat__label">Completed Today</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-ban"></i></div><div class="ca-stat__value" style="color:var(--cm-red)"><?= (int)$teamStats['cancelled'] ?></div><div class="ca-stat__label">Cancelled Today</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-phone"></i></div><div class="ca-stat__value"><?= (int)$teamStats['total_calls'] ?></div><div class="ca-stat__label">Total Calls</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-calendar-check"></i></div><div class="ca-stat__value" style="color:var(--cm-cyan)"><?= (int)$teamStats['scheduled_calls'] ?></div><div class="ca-stat__label">Calls Scheduled</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-phone-volume"></i></div><div class="ca-stat__value" style="color:var(--cm-green)"><?= (int)$teamStats['connected_calls'] ?></div><div class="ca-stat__label">Connected</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-phone-slash"></i></div><div class="ca-stat__value" style="color:var(--cm-yellow)"><?= (int)$teamStats['missed_calls'] ?></div><div class="ca-stat__label">Missed / Absent</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-pen-to-square"></i></div><div class="ca-stat__value" style="color:var(--cm-blue)"><?= (int)$teamStats['updates'] ?></div><div class="ca-stat__label">Updates</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-triangle-exclamation"></i></div><div class="ca-stat__value" style="color:var(--cm-yellow)"><?= (int)$teamStats['warnings'] ?></div><div class="ca-stat__label">Warnings</div></div>
    <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-circle-exclamation"></i></div><div class="ca-stat__value" style="color:var(--cm-red)"><?= (int)$teamStats['mistakes'] ?></div><div class="ca-stat__label">Mistakes</div></div>
  </div>
</div>
<div class="ca-grid-2 mb-3">
  <div class="cm-card">
    <div class="cm-card__title"><i class="fas fa-triangle-exclamation me-1" style="color:var(--cm-yellow)"></i>Recent Warnings</div>
    <div class="tl-disc-filter">
      <select class="tl-disc-date" data-target="warning"><option value="all">All dates</option><option value="today">Today</option><option value="7">Last 7 days</option><option value="30">Last 30 days</option></select>
      <input class="tl-disc-search" data-target="warning" type="search" placeholder="Search to / from / title">
    </div>
    <div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Date</th><th>To</th><th>From</th><th>Title</th><th>Level</th><th>Status</th></tr></thead><tbody>
      <?php if (!$recentWarnings): ?><tr><td colspan="6" class="text-center text-muted py-4">No warnings recorded.</td></tr><?php endif; ?>
      <?php foreach ($recentWarnings as $w): $wJson = htmlspecialchars(json_encode([
            'type'=>'Warning', 'title'=>$w['title'] ?? 'Warning', 'message'=>$w['message'] ?? '', 'to'=>trim($w['recipient_name'] ?? '') ?: '—', 'from'=>trim($w['sender_name'] ?? '') ?: discRoleLabel($w['sender_role'] ?? ''), 'severity'=>strtoupper($w['severity'] ?? 'NORMAL'), 'date'=>tlDate($w['created_at'] ?? null)
          ], JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), ENT_QUOTES, 'UTF-8'); ?>
        <tr class="tl-disc-row" data-disc-type="warning" data-disc-date="<?= htmlspecialchars((string)($w['created_at'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" data-disc-search="<?= htmlspecialchars(strtolower(trim(($w['recipient_name'] ?? '').' '.($w['sender_name'] ?? '').' '.($w['title'] ?? '').' '.($w['message'] ?? '').' '.($w['severity'] ?? ''))), ENT_QUOTES, 'UTF-8') ?>" onclick="tlOpenDiscModal(this.dataset.detail)" data-detail="<?= $wJson ?>" title="Click to show warning details">
          <td><?= htmlspecialchars(tlDate($w['created_at'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars(trim($w['recipient_name'] ?? '') ?: '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars(trim($w['sender_name'] ?? '') ?: discRoleLabel($w['sender_role'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
          <td><strong><?= htmlspecialchars($w['title'] ?? 'Warning', ENT_QUOTES, 'UTF-8') ?></strong></td>
          <td><span class="badge bg-warning text-dark"><?= htmlspecialchars(strtoupper($w['severity'] ?? 'NORMAL'), ENT_QUOTES, 'UTF-8') ?></span></td>
          <td><?= !empty($w['is_read']) ? '<span class="badge bg-success">Read</span>' : '<span class="badge bg-secondary">Unread</span>' ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody></table></div>
  </div>
  <div class="cm-card">
    <div class="cm-card__title"><i class="fas fa-circle-exclamation me-1" style="color:var(--cm-red)"></i>Recent Mistakes</div>
    <div class="tl-disc-filter">
      <select class="tl-disc-date" data-target="mistake"><option value="all">All dates</option><option value="today">Today</option><option value="7">Last 7 days</option><option value="30">Last 30 days</option></select>
      <input class="tl-disc-search" data-target="mistake" type="search" placeholder="Search to / from / title">
    </div>
    <div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Date</th><th>To</th><th>From</th><th>Title</th><th>Level</th><th>Status</th></tr></thead><tbody>
      <?php if (!$recentMistakes): ?><tr><td colspan="6" class="text-center text-muted py-4">No mistakes recorded.</td></tr><?php endif; ?>
      <?php foreach ($recentMistakes as $m): $mJson = htmlspecialchars(json_encode([
            'type'=>'Mistake', 'title'=>$m['title'] ?? 'Mistake', 'message'=>$m['message'] ?? '', 'to'=>trim($m['recipient_name'] ?? '') ?: '—', 'from'=>trim($m['sender_name'] ?? '') ?: discRoleLabel($m['sender_role'] ?? ''), 'severity'=>strtoupper($m['severity'] ?? 'NORMAL'), 'date'=>tlDate($m['created_at'] ?? null)
          ], JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), ENT_QUOTES, 'UTF-8'); ?>
        <tr class="tl-disc-row" data-disc-type="mistake" data-disc-date="<?= htmlspecialchars((string)($m['created_at'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" data-disc-search="<?= htmlspecialchars(strtolower(trim(($m['recipient_name'] ?? '').' '.($m['sender_name'] ?? '').' '.($m['title'] ?? '').' '.($m['message'] ?? '').' '.($m['severity'] ?? ''))), ENT_QUOTES, 'UTF-8') ?>" onclick="tlOpenDiscModal(this.dataset.detail)" data-detail="<?= $mJson ?>" title="Click to show mistake details">
          <td><?= htmlspecialchars(tlDate($m['created_at'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars(trim($m['recipient_name'] ?? '') ?: '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars(trim($m['sender_name'] ?? '') ?: discRoleLabel($m['sender_role'] ?? ''), ENT_QUOTES, 'UTF-8') ?></td>
          <td><strong><?= htmlspecialchars($m['title'] ?? 'Mistake', ENT_QUOTES, 'UTF-8') ?></strong></td>
          <td><span class="badge bg-danger"><?= htmlspecialchars(strtoupper($m['severity'] ?? 'NORMAL'), ENT_QUOTES, 'UTF-8') ?></span></td>
          <td><?= !empty($m['is_read']) ? '<span class="badge bg-success">Read</span>' : '<span class="badge bg-secondary">Unread</span>' ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody></table></div>
  </div>
</div>

<div class="ca-grid-2">
  <div class="cm-card">
    <div class="cm-card__title">Recent Team Ticket Activity</div>
    <div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Date / Time</th><th>CSR</th><th>Request #</th><th>Customer</th><th>City</th><th>Status</th></tr></thead><tbody>
      <?php if (!$recentTickets): ?><tr><td colspan="6" class="text-center text-muted py-4">No team ticket activity yet.</td></tr><?php endif; ?>
      <?php foreach ($recentTickets as $r): ?>
        <tr>
          <td><?= htmlspecialchars(tlDate($r['activity_at'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($r['csr_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($r['request_number'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($r['full_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($r['city'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= tlStatusBadge($r['status_name'] ?? 'New') ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody></table></div>
  </div>
  <div class="cm-card">
    <div class="cm-card__title">Recent Team Call Activity</div>
    <div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Date</th><th>CSR</th><th>Customer / City</th><th>Status</th><th>Duration</th></tr></thead><tbody>
      <?php if (!$recentCalls): ?><tr><td colspan="5" class="text-center text-muted py-4">No team call activity yet.</td></tr><?php endif; ?>
      <?php foreach ($recentCalls as $c): $dur = (int)($c['call_duration_seconds'] ?? 0); ?>
        <tr>
          <td><?= htmlspecialchars(tlDate($c['queued_at'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($c['csr_name'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars(($c['customer_name'] ?? '—').' / '.($c['city'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= tlCallStatusBadge($c['status'] ?? 'pending') ?></td>
          <td><?= $dur ? gmdate('i:s', $dur) : '—' ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody></table></div>
  </div>
</div>

<div class="tl-disc-backdrop" id="tlDiscModal" onclick="tlCloseDiscModal(event)">
  <div class="tl-disc-modal" onclick="event.stopPropagation()">
    <div class="tl-disc-head">
      <div><h3 class="tl-disc-title" id="tlDiscTitle">Details</h3><div class="tl-disc-sub" id="tlDiscSub"></div></div>
      <button type="button" class="tl-disc-close" onclick="tlCloseDiscModal()">×</button>
    </div>
    <div class="tl-disc-body" id="tlDiscBody"></div>
  </div>
</div>
<script>
function tlEsc(s){return String(s||'').replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c];});}
function tlOpenDiscModal(raw){
  let d={}; try{d=JSON.parse(raw||'{}');}catch(e){}
  document.getElementById('tlDiscTitle').textContent=(d.type||'Record')+' Details — '+(d.to||'User');
  document.getElementById('tlDiscSub').textContent='From '+(d.from||'Unknown')+' • '+(d.date||'')+' • '+(d.severity||'NORMAL');
  document.getElementById('tlDiscBody').innerHTML='<strong>'+tlEsc(d.title||d.type||'Record')+'</strong><div class="tl-disc-message mt-2">'+tlEsc(d.message||'No message provided.')+'</div><div class="tl-disc-meta">Click outside to close.</div>';
  document.getElementById('tlDiscModal').classList.add('is-open');
}
function tlCloseDiscModal(e){ if(e && e.target && e.target.id!=='tlDiscModal') return; document.getElementById('tlDiscModal').classList.remove('is-open'); }

function tlDiscDatePass(raw, filter){
  if(!filter || filter==='all') return true;
  if(!raw) return true;
  const d=new Date(String(raw).replace(' ','T'));
  if(isNaN(d.getTime())) return false;
  const now=new Date();
  const startToday=new Date(now.getFullYear(),now.getMonth(),now.getDate());
  if(filter==='today') return d>=startToday;
  const days=parseInt(filter)||0;
  if(!days) return true;
  const start=new Date(startToday); start.setDate(start.getDate()-(days-1));
  return d>=start;
}
function tlApplyDiscFilters(type){
  const dateEl=document.querySelector('.tl-disc-date[data-target="'+type+'"]');
  const searchEl=document.querySelector('.tl-disc-search[data-target="'+type+'"]');
  const dateFilter=dateEl ? dateEl.value : 'all';
  const q=(searchEl ? searchEl.value : '').trim().toLowerCase();
  document.querySelectorAll('.tl-disc-row[data-disc-type="'+type+'"]').forEach(row=>{
    const okDate=tlDiscDatePass(row.dataset.discDate||'', dateFilter);
    const okSearch=!q || String(row.dataset.discSearch||row.textContent||'').toLowerCase().includes(q);
    row.style.display=(okDate && okSearch)?'':'none';
  });
}
document.querySelectorAll('.tl-disc-date,.tl-disc-search').forEach(el=>{
  const type=el.dataset.target;
  el.addEventListener('input',()=>tlApplyDiscFilters(type));
  el.addEventListener('change',()=>tlApplyDiscFilters(type));
});

</script>

<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
