<?php
// csr_manager/report.php — CSR Manager report with all teams + team leader data
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['csr_id'])) { header('Location: ../login.php'); exit(); }

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

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

$managerId = (int)$_SESSION['csr_id'];
if (getCsrRoleForReport($db, $managerId) !== 'csr_manager') { header('Location: dashboard.php'); exit(); }

$title = 'CSR Daily Report';

function mgr_h($v): string { return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function mgr_date_ok(string $v): bool { return (bool)preg_match('/^\d{4}-\d{2}-\d{2}$/', $v); }
function mgr_fmt_date(string $v): string { return $v ? date('m/d/y', strtotime($v)) : '—'; }
function mgr_count(PDO $db, string $sql, array $params = []): int {
    try { $s = $db->prepare($sql); $s->execute($params); return (int)$s->fetchColumn(); }
    catch (Throwable $e) { return 0; }
}
function mgr_has_table(PDO $db, string $table): bool {
    try {
        $stmt = $db->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table");
        $stmt->execute([':table' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    } catch (Throwable $e) { return false; }
}
function mgr_has_column(PDO $db, string $table, string $column): bool {
    try {
        $stmt = $db->prepare("SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = :table AND COLUMN_NAME = :column");
        $stmt->execute([':table' => $table, ':column' => $column]);
        return (int)$stmt->fetchColumn() > 0;
    } catch (Throwable $e) { return false; }
}
function mgr_make_in(array $ids, string $prefix, array &$params): string {
    $holders = [];
    foreach (array_values(array_unique(array_filter(array_map('intval', $ids)))) as $i => $id) {
        $ph = ':' . $prefix . $i;
        $holders[] = $ph;
        $params[$ph] = $id;
    }
    return $holders ? implode(',', $holders) : 'NULL';
}
function mgr_date_expr(PDO $db, string $table, array $preferred): string {
    $cols = [];
    foreach ($preferred as $col) if (mgr_has_column($db, $table, $col)) $cols[] = $col;
    if (!$cols) return 'NOW()';
    return count($cols) === 1 ? $cols[0] : 'COALESCE(' . implode(',', $cols) . ')';
}
function mgr_service_owner_condition(PDO $db, array $csrIds, string $prefix, array &$params): string {
    if (!mgr_has_table($db, 'service_requests')) return '1=0';
    $ors = [];
    foreach (['assigned_csr_id','handled_by_csr_id','created_by_csr_id'] as $idx => $col) {
        if (mgr_has_column($db, 'service_requests', $col)) {
            $in = mgr_make_in($csrIds, $prefix . $idx . '_', $params);
            $ors[] = "$col IN ($in)";
        }
    }
    return $ors ? '(' . implode(' OR ', $ors) . ')' : '1=0';
}
function mgr_empty_ops(): array {
    return [
        'handled_today'=>0,
        'assigned_tickets'=>0,
        'in_progress'=>0,
        'completed_today'=>0,
        'cancelled_today'=>0,
        'total_calls'=>0,
        'calls_scheduled'=>0,
        'connected'=>0,
        'missed_absent'=>0,
        'updates'=>0,
        'warnings'=>0,
        'mistakes'=>0,
        'gh'=>0,
        'schedule'=>0,
        'attempt'=>0,
        'update'=>0,
    ];
}
function mgr_ops_for_scope(PDO $db, array $csrIds, string $startDate, string $endDate): array {
    $out = mgr_empty_ops();
    $csrIds = array_values(array_unique(array_filter(array_map('intval', $csrIds))));
    if (!$csrIds) return $out;

    $union = [];
    $params = [':handled_from'=>$startDate, ':handled_to'=>$endDate];

    if (mgr_has_table($db, 'service_requests')) {
        $dateExpr = mgr_date_expr($db, 'service_requests', ['last_updated_at','completed_date','requested_at','created_at']);
        $ownerCond = mgr_service_owner_condition($db, $csrIds, 'handled_sr', $params);
        if ($ownerCond !== '1=0') {
            $union[] = "SELECT id AS request_id FROM service_requests WHERE $ownerCond AND DATE($dateExpr) BETWEEN :handled_from AND :handled_to";
        }
    }
    if (mgr_has_table($db, 'csr_activity') && mgr_has_column($db, 'csr_activity', 'csr_id') && mgr_has_column($db, 'csr_activity', 'request_id')) {
        $in = mgr_make_in($csrIds, 'handled_ca', $params);
        $union[] = "SELECT request_id FROM csr_activity WHERE csr_id IN ($in) AND request_id IS NOT NULL AND DATE(created_at) BETWEEN :handled_from AND :handled_to";
    }
    if (mgr_has_table($db, 'request_logs') && mgr_has_column($db, 'request_logs', 'user_id') && mgr_has_column($db, 'request_logs', 'request_id')) {
        $in = mgr_make_in($csrIds, 'handled_rl', $params);
        $union[] = "SELECT request_id FROM request_logs WHERE user_id IN ($in) AND user_role IN ('csr','team_leader','csr_manager') AND request_id IS NOT NULL AND DATE(created_at) BETWEEN :handled_from AND :handled_to";
    }
    if (mgr_has_table($db, 'csr_request_locks') && mgr_has_column($db, 'csr_request_locks', 'csr_id')) {
        $in = mgr_make_in($csrIds, 'handled_lk', $params);
        $dateExpr = mgr_date_expr($db, 'csr_request_locks', ['locked_at','created_at']);
        $union[] = "SELECT request_id FROM csr_request_locks WHERE csr_id IN ($in) AND request_id IS NOT NULL AND DATE($dateExpr) BETWEEN :handled_from AND :handled_to";
    }
    if (mgr_has_table($db, 'service_assignments') && mgr_has_column($db, 'service_assignments', 'assigned_by')) {
        $in = mgr_make_in($csrIds, 'handled_sa', $params);
        $dateExpr = mgr_date_expr($db, 'service_assignments', ['assigned_at','created_at']);
        $union[] = "SELECT request_id FROM service_assignments WHERE assigned_by IN ($in) AND request_id IS NOT NULL AND DATE($dateExpr) BETWEEN :handled_from AND :handled_to";
    }
    if ($union) $out['handled_today'] = mgr_count($db, "SELECT COUNT(DISTINCT request_id) FROM (" . implode(' UNION ', $union) . ") x", $params);

    if (mgr_has_table($db, 'service_requests')) {
        $params = [':sr_from'=>$startDate, ':sr_to'=>$endDate];
        $ownerCond = mgr_service_owner_condition($db, $csrIds, 'sr_owner', $params);
        if ($ownerCond !== '1=0' && mgr_has_column($db, 'service_requests', 'job_status_id')) {
            $dateExpr = mgr_date_expr($db, 'service_requests', ['last_updated_at','completed_date','requested_at','created_at']);
            $statusJoin = mgr_has_table($db, 'job_statuses') ? " LEFT JOIN job_statuses js ON js.id = sr.job_status_id " : "";
            $statusNameExpr = mgr_has_table($db, 'job_statuses') ? "LOWER(COALESCE(js.status_name,''))" : "''";
            $sql = "SELECT
                        COALESCE(SUM((COALESCE(sr.job_status_id,1) NOT IN (4,5)) AND $statusNameExpr NOT LIKE '%complete%' AND $statusNameExpr NOT LIKE '%cancel%'),0) AS assigned_tickets,
                        COALESCE(SUM(COALESCE(sr.job_status_id,0) = 3 OR $statusNameExpr LIKE '%progress%'),0) AS in_progress,
                        COALESCE(SUM((COALESCE(sr.job_status_id,0) = 4 OR $statusNameExpr LIKE '%complete%') AND DATE($dateExpr) BETWEEN :sr_from AND :sr_to),0) AS completed_today,
                        COALESCE(SUM((COALESCE(sr.job_status_id,0) = 5 OR $statusNameExpr LIKE '%cancel%') AND DATE($dateExpr) BETWEEN :sr_from AND :sr_to),0) AS cancelled_today
                    FROM service_requests sr
                    $statusJoin
                    WHERE $ownerCond";
            try {
                $stmt = $db->prepare($sql); $stmt->execute($params); $r = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
                foreach (['assigned_tickets','in_progress','completed_today','cancelled_today'] as $k) $out[$k] = (int)($r[$k] ?? 0);
            } catch (Throwable $e) {}

            // Extra fallback for current In Progress tickets, regardless of activity date.
            if ($out['in_progress'] === 0) {
                $fallbackParams = [];
                $fallbackOwner = mgr_service_owner_condition($db, $csrIds, 'ip_owner', $fallbackParams);
                if ($fallbackOwner !== '1=0') {
                    $join = mgr_has_table($db, 'job_statuses') ? " LEFT JOIN job_statuses js ON js.id = sr.job_status_id " : "";
                    $nameExpr = mgr_has_table($db, 'job_statuses') ? "LOWER(COALESCE(js.status_name,''))" : "''";
                    $out['in_progress'] = mgr_count($db, "SELECT COUNT(DISTINCT sr.id) FROM service_requests sr $join WHERE $fallbackOwner AND (COALESCE(sr.job_status_id,0)=3 OR $nameExpr LIKE '%progress%')", $fallbackParams);
                }
            }
        }
    }

    if ($out['completed_today'] === 0 && mgr_has_table($db, 'request_logs')) {
        $params = [':sd'=>$startDate, ':ed'=>$endDate];
        $in = mgr_make_in($csrIds, 'comp_rl', $params);
        $out['completed_today'] = mgr_count($db, "SELECT COUNT(DISTINCT request_id) FROM request_logs WHERE user_id IN ($in) AND user_role IN ('csr','team_leader','csr_manager') AND action='status_change' AND CAST(new_value AS CHAR)='4' AND DATE(created_at) BETWEEN :sd AND :ed", $params);
    }
    if ($out['cancelled_today'] === 0 && mgr_has_table($db, 'request_logs')) {
        $params = [':sd'=>$startDate, ':ed'=>$endDate];
        $in = mgr_make_in($csrIds, 'can_rl', $params);
        $out['cancelled_today'] = mgr_count($db, "SELECT COUNT(DISTINCT request_id) FROM request_logs WHERE user_id IN ($in) AND user_role IN ('csr','team_leader','csr_manager') AND action='status_change' AND CAST(new_value AS CHAR)='5' AND DATE(created_at) BETWEEN :sd AND :ed", $params);
    }

    if (mgr_has_table($db, 'call_requests')) {
        $params = [':cr_from'=>$startDate, ':cr_to'=>$endDate];
        $ors = [];
        if (mgr_has_column($db, 'call_requests', 'assigned_csr_id')) { $in = mgr_make_in($csrIds, 'cra', $params); $ors[] = "assigned_csr_id IN ($in)"; }
        if (mgr_has_column($db, 'call_requests', 'accepted_by')) { $in = mgr_make_in($csrIds, 'crb', $params); $ors[] = "accepted_by IN ($in)"; }
        if ($ors) {
            $dateExpr = mgr_date_expr($db, 'call_requests', ['accepted_at','completed_at','queued_at','created_at']);
            $sql = "SELECT
                        COUNT(*) AS total_calls,
                        COALESCE(SUM(LOWER(COALESCE(status,'')) IN ('assigned','manager_queue','scheduled','pending')),0) AS calls_scheduled,
                        COALESCE(SUM(LOWER(COALESCE(status,'')) IN ('accepted','completed','connected')),0) AS connected,
                        COALESCE(SUM(LOWER(COALESCE(status,'')) IN ('missed','cancelled','canceled','no_answer','no answer','absent')),0) AS missed_absent
                    FROM call_requests
                    WHERE (" . implode(' OR ', $ors) . ")
                      AND DATE($dateExpr) BETWEEN :cr_from AND :cr_to";
            try {
                $stmt = $db->prepare($sql); $stmt->execute($params); $r = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
                foreach (['total_calls','calls_scheduled','connected','missed_absent'] as $k) $out[$k] = (int)($r[$k] ?? 0);
            } catch (Throwable $e) {}
        }
    }

    if (mgr_has_table($db, 'csr_activity') && mgr_has_column($db, 'csr_activity', 'csr_id')) {
        $params = [':act_from'=>$startDate, ':act_to'=>$endDate];
        $in = mgr_make_in($csrIds, 'act', $params);
        $sql = "SELECT
                    COALESCE(SUM(action IN ('status_change','note_added','request_claimed','manual_ticket_created') OR action LIKE '%update%'),0) AS updates,
                    COALESCE(SUM(action LIKE '%warning%' OR details LIKE '%warning%'),0) AS warnings,
                    COALESCE(SUM(action LIKE '%mistake%' OR action LIKE '%error%' OR details LIKE '%mistake%' OR details LIKE '%error%'),0) AS mistakes
                FROM csr_activity
                WHERE csr_id IN ($in)
                  AND DATE(created_at) BETWEEN :act_from AND :act_to";
        try {
            $stmt = $db->prepare($sql); $stmt->execute($params); $r = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
            foreach (['updates','warnings','mistakes'] as $k) $out[$k] = (int)($r[$k] ?? 0);
        } catch (Throwable $e) {}
    }

    // Add records created from the new Mistake / Warning pages.
    if (mgr_has_table($db, 'csr_discipline_records')) {
        $params = [':disc_from'=>$startDate, ':disc_to'=>$endDate];
        $in = mgr_make_in($csrIds, 'disc', $params);
        $sql = "SELECT
                    COALESCE(SUM(record_type='warning'),0) AS warnings,
                    COALESCE(SUM(record_type='mistake'),0) AS mistakes
                FROM csr_discipline_records
                WHERE recipient_id IN ($in)
                  AND DATE(created_at) BETWEEN :disc_from AND :disc_to";
        try {
            $stmt = $db->prepare($sql); $stmt->execute($params); $r = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
            $out['warnings'] += (int)($r['warnings'] ?? 0);
            $out['mistakes'] += (int)($r['mistakes'] ?? 0);
        } catch (Throwable $e) {}
    }

    $out['gh'] = $out['handled_today'];
    $out['schedule'] = $out['calls_scheduled'];
    $out['attempt'] = $out['total_calls'];
    $out['update'] = $out['updates'];
    return $out;
}

$startDate = isset($_GET['start_date']) && mgr_date_ok($_GET['start_date']) ? $_GET['start_date'] : '2026-01-01';
$endDate   = isset($_GET['end_date']) && mgr_date_ok($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');
if (strtotime($startDate) > strtotime($endDate)) { $tmp = $startDate; $startDate = $endDate; $endDate = $tmp; }
$teamFilter = isset($_GET['team_id']) ? max(0, (int)$_GET['team_id']) : 0;
$agentFilter = isset($_GET['csr_id']) ? max(0, (int)$_GET['csr_id']) : 0;

$teams = [];
try {
    $teamSql = "SELECT t.id, t.team_name, t.manager_id,
                       CONCAT(COALESCE(mgr.first_name,''), ' ', COALESCE(mgr.last_name,'')) AS manager_name,
                       COALESCE(mgr.role, 'team_leader') AS manager_role
                FROM csr_teams t
                LEFT JOIN csr_users mgr ON mgr.id = t.manager_id
                WHERE t.is_active = 1";
    $teamParams = [];
    if ($teamFilter > 0) {
        $teamSql .= " AND t.id = :team_filter";
        $teamParams[':team_filter'] = $teamFilter;
    }
    $teamSql .= " ORDER BY t.team_name";
    $teamStmt = $db->prepare($teamSql);
    $teamStmt->execute($teamParams);
    $teams = $teamStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $teams = []; }

// Full team list for the filter dropdown. Do not use the filtered team list here.
$allTeamsForFilter = [];
try { $allTeamsForFilter = $db->query("SELECT id, team_name FROM csr_teams WHERE is_active = 1 ORDER BY team_name")->fetchAll(PDO::FETCH_ASSOC); }
catch (Throwable $e) { $allTeamsForFilter = $teams; }

function mgr_add_report_user(array &$bucket, array $user, int $teamId, string $teamName): void {
    $uid = (int)($user['id'] ?? 0);
    if ($uid <= 0) return;
    if (isset($bucket[$teamId]['user_ids'][$uid])) return;
    $bucket[$teamId]['user_ids'][$uid] = true;
    $bucket[$teamId]['rows'][] = [
        'id' => $uid,
        'full_name' => trim((string)($user['full_name'] ?? '')),
        'role' => (string)($user['role'] ?? 'csr'),
        'is_active' => (int)($user['is_active'] ?? 1),
        'team_id' => $teamId,
        'team_name' => $teamName,
    ];
}

$teamGroups = [];
$agentDropdown = [];

foreach ($teams as $team) {
    $teamId = (int)$team['id'];
    $teamName = trim((string)$team['team_name']) ?: ('Team #' . $teamId);
    $teamGroups[$teamId] = [
        'team_id' => $teamId,
        'team_name' => $teamName,
        'rows' => [],
        'user_ids' => [],
        'totals' => mgr_empty_ops(),
    ];

    // Add the team leader / team owner first, even if the role value was not converted yet.
    $managerId = (int)($team['manager_id'] ?? 0);
    if ($managerId > 0 && ($agentFilter === 0 || $agentFilter === $managerId)) {
        mgr_add_report_user($teamGroups, [
            'id' => $managerId,
            'full_name' => trim((string)($team['manager_name'] ?? '')) ?: ('CSR #' . $managerId),
            'role' => 'team_leader',
            'is_active' => 1,
        ], $teamId, $teamName);
    }

    // Add every active CSR assigned to this team.
    try {
        $memberSql = "SELECT cu.id,
                             CONCAT(COALESCE(cu.first_name,''), ' ', COALESCE(cu.last_name,'')) AS full_name,
                             COALESCE(cu.role, 'csr') AS role,
                             COALESCE(cu.is_active, 1) AS is_active
                      FROM csr_team_members ctm
                      JOIN csr_users cu ON cu.id = ctm.csr_id
                      WHERE ctm.team_id = :team_id
                        AND COALESCE(cu.is_active, 1) = 1
                        AND COALESCE(cu.role, 'csr') IN ('csr','team_leader','csr_manager')";
        $memberParams = [':team_id' => $teamId];
        if ($agentFilter > 0) {
            $memberSql .= " AND cu.id = :agent_filter";
            $memberParams[':agent_filter'] = $agentFilter;
        }
        $memberSql .= " ORDER BY cu.role DESC, cu.first_name, cu.last_name, cu.id";
        $memberStmt = $db->prepare($memberSql);
        $memberStmt->execute($memberParams);
        foreach ($memberStmt->fetchAll(PDO::FETCH_ASSOC) as $member) {
            mgr_add_report_user($teamGroups, $member, $teamId, $teamName);
        }
    } catch (Throwable $e) {}
}

// Dropdown must include all active agents/team leaders, not only the currently filtered rows.
try {
    $dropStmt = $db->query("SELECT cu.id,
                                   CONCAT(COALESCE(cu.first_name,''), ' ', COALESCE(cu.last_name,'')) AS full_name,
                                   COALESCE(cu.role, 'csr') AS role
                            FROM csr_users cu
                            WHERE COALESCE(cu.is_active, 1) = 1
                              AND COALESCE(cu.role, 'csr') IN ('csr','team_leader','csr_manager')
                              AND (COALESCE(cu.role, 'csr') <> 'csr_manager' OR EXISTS (SELECT 1 FROM csr_teams t WHERE t.manager_id = cu.id AND t.is_active = 1))
                            ORDER BY cu.role DESC, cu.first_name, cu.last_name, cu.id");
    $agentDropdown = $dropStmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) { $agentDropdown = []; }

$rows = [];
$totals = mgr_empty_ops();
foreach ($teamGroups as $teamId => &$group) {
    foreach ($group['rows'] as &$row) {
        $stats = mgr_ops_for_scope($db, [(int)$row['id']], $startDate, $endDate);
        foreach (array_keys($totals) as $k) {
            $row[$k] = (int)($stats[$k] ?? 0);
            $group['totals'][$k] += (int)($stats[$k] ?? 0);
            $totals[$k] += (int)($stats[$k] ?? 0);
        }
        $rows[] = $row;
    }
    unset($row);
}
unset($group);

// Preserve empty teams in the report cards/table, but hide all teams if an agent filter is active and no team contains that person.
if ($agentFilter > 0) {
    $teamGroups = array_filter($teamGroups, function($group) { return !empty($group['rows']); });
}

$metricCards = [
    ['handled_today','Total Handled','var(--cm-cyan)'],
    ['assigned_tickets','Assigned Tickets','var(--cm-blue)'],
    ['in_progress','In Progress','var(--cm-purple)'],
    ['completed_today','Completed Tickets','var(--cm-green)'],
    ['cancelled_today','Cancelled Tickets','var(--cm-red)'],
    ['total_calls','Total Calls','var(--cm-text)'],
    ['calls_scheduled','Calls Scheduled','var(--cm-cyan)'],
    ['connected','Connected','var(--cm-green)'],
    ['missed_absent','Missed / Absent','var(--cm-yellow)'],
    ['updates','Updates','var(--cm-purple)'],
    ['warnings','Warnings','var(--cm-yellow)'],
    ['mistakes','Mistakes','var(--cm-red)'],
];


$dateRangeLabel = mgr_fmt_date($startDate) . ($startDate !== $endDate ? ' - ' . mgr_fmt_date($endDate) : '');

$extra_styles = <<<'CSS'
<style>
.cm-range-note{margin:-2px 0 14px;color:var(--cm-muted);font-size:.78rem;font-weight:700}.cm-range-note strong{color:var(--cm-text)}
.cm-report-metrics{display:grid;grid-template-columns:repeat(6,minmax(120px,1fr));gap:10px;margin-bottom:16px}

.cm-team-summary-grid{display:grid;grid-template-columns:repeat(2,minmax(260px,1fr));gap:14px;margin:0 0 16px}
.cm-team-summary-card{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:14px;padding:14px 16px;transition:.16s ease;cursor:pointer}
.cm-team-summary-card:hover{transform:translateY(-2px);border-color:var(--cm-border2);box-shadow:0 12px 28px rgba(0,0,0,.22)}
.cm-team-summary-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
.cm-team-summary-name{font-size:.72rem;font-weight:900;text-transform:uppercase;letter-spacing:.08em;color:var(--cm-cyan)}
.cm-team-summary-hint{margin-left:auto;font-size:.65rem;color:var(--cm-muted);font-weight:800;text-transform:uppercase;letter-spacing:.05em}
.cm-team-summary-grid-inner{display:grid;grid-template-columns:1fr 1fr;gap:0 14px}
.cm-team-summary-row{display:flex;justify-content:space-between;padding:4px 0;font-size:.76rem;border-bottom:1px solid var(--cm-border)}
.cm-team-summary-row span:first-child{color:var(--cm-muted)}
.cm-team-summary-row span:last-child{font-weight:900}
@media(max-width:800px){.cm-team-summary-grid{grid-template-columns:1fr}.cm-team-summary-grid-inner{grid-template-columns:1fr}}
.cm-report-metric{text-align:center;padding:14px 8px}
.cm-report-metric__label{font-size:.62rem;font-weight:800;text-transform:uppercase;letter-spacing:.06em;color:var(--cm-muted);margin-bottom:6px}
.cm-report-metric__value{font-family:'Space Grotesk',system-ui,sans-serif;font-size:1.65rem;font-weight:900}
.cm-role-pill{font-size:.62rem;margin-left:6px;opacity:.9}
.cm-detail-table-card{padding:0!important;overflow:hidden;border-radius:16px;background:transparent;border:0}
.cm-detail-table-head{display:flex;justify-content:space-between;align-items:center;gap:12px;padding:16px 18px;margin-bottom:14px;border:1px solid var(--cm-border);border-radius:14px;background:var(--cm-card)}
.cm-detail-table-title{font-size:.86rem;font-weight:900;text-transform:uppercase;letter-spacing:.08em;color:var(--cm-cyan)}
.cm-detail-table-sub{font-size:.72rem;color:var(--cm-muted);font-weight:700}
.cm-detail-team-list{display:grid;grid-template-columns:1fr;gap:14px}
.cm-detail-team-card{background:var(--cm-card);border:1px solid var(--cm-border);border-radius:14px;padding:14px 16px;overflow:hidden}
.cm-detail-team-head{display:flex;align-items:center;gap:8px;margin-bottom:10px}
.cm-detail-team-name{font-size:.72rem;font-weight:900;text-transform:uppercase;letter-spacing:.08em;color:var(--cm-cyan)}
.cm-detail-team-meta{margin-left:auto;font-size:.65rem;color:var(--cm-muted);font-weight:800;text-transform:uppercase;letter-spacing:.05em}
.cm-container-table-wrap{overflow:auto;border-top:1px solid var(--cm-border)}
.cm-container-table{width:100%;min-width:1180px;border-collapse:collapse;border-spacing:0;font-size:.78rem}
.cm-container-table th{padding:9px 8px;border-bottom:1px solid var(--cm-border);color:var(--cm-muted);font-size:.62rem;font-weight:900;text-transform:uppercase;letter-spacing:.06em;text-align:left;white-space:nowrap;background:transparent}
.cm-container-table td{padding:8px 8px;border-bottom:1px solid var(--cm-border);color:var(--cm-muted);white-space:nowrap;background:transparent!important}
.cm-container-table th:nth-child(n+3),.cm-container-table td:nth-child(n+3){text-align:right}
.cm-container-table tbody tr:hover td{background:oklch(0.23 0.04 260 / .35)!important}
.cm-container-table td strong{color:var(--cm-text);font-weight:900}
.cm-num{font-weight:900;color:var(--cm-text)}
.cm-num.cyan{color:var(--cm-cyan)}.cm-num.blue{color:var(--cm-blue)}.cm-num.purple{color:var(--cm-purple)}.cm-num.green{color:var(--cm-green)}.cm-num.red{color:var(--cm-red)}.cm-num.yellow{color:var(--cm-yellow)}
.cm-role-pill{font-size:.62rem;margin-left:6px;opacity:.9}
.cm-detail-total-row td{font-weight:900;color:var(--cm-text);border-top:1px solid var(--cm-border2);background:oklch(0.18 0.045 260 / .58)!important}
.cm-detail-total-row td:not(:first-child){text-align:right!important}.cm-detail-total-row td:first-child{color:var(--cm-cyan);text-transform:uppercase;letter-spacing:.055em;text-align:left!important}
.cm-grand-container-card{background:oklch(0.19 0.045 260 / .98);border:1px solid var(--cm-border2);border-radius:14px;padding:14px 16px;margin-top:14px}
.cm-grand-container-title{font-size:.72rem;font-weight:900;text-transform:uppercase;letter-spacing:.08em;color:var(--cm-cyan);margin-bottom:10px}
.cm-grand-grid{display:grid;grid-template-columns:repeat(2,minmax(160px,1fr));gap:0 18px}
.cm-grand-row{display:flex;justify-content:space-between;padding:5px 0;border-bottom:1px solid var(--cm-border);font-size:.78rem}.cm-grand-row span:first-child{color:var(--cm-muted)}.cm-grand-row span:last-child{font-weight:900}
.cm-empty-team-row{padding:16px;text-align:center;color:var(--cm-muted);font-weight:700;border-top:1px solid var(--cm-border)}
.cm-table-note{color:var(--cm-muted);font-size:.72rem;font-weight:700}
@media(max-width:760px){.cm-grand-grid{grid-template-columns:1fr}.cm-detail-table-head{align-items:flex-start;flex-direction:column}}
@media(max-width:960px){.cm-report-metrics{grid-template-columns:repeat(3,minmax(120px,1fr))}}
@media(max-width:540px){.cm-report-metrics{grid-template-columns:repeat(2,minmax(120px,1fr))}}
</style>
CSS;

ob_start();
?>

<div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-4">
  <div>
    <h2 style="font-family:'Space Grotesk',system-ui,sans-serif;font-weight:900;margin:0;">
      <i class="fas fa-chart-line me-2" style="color:var(--cm-blue);"></i>CSR Daily Report
    </h2>
    <small style="color:var(--cm-muted);">Totals are based on the selected Start Date to End Date filter. Collects data from all CSR Agents and CSR Team Leaders.</small>
  </div>
  <div class="d-flex gap-2 flex-wrap">
    <a href="dashboard.php" class="cm-btn"><i class="fas fa-arrow-left me-1"></i>Back to Dashboard</a>
    <a href="../csr/export_report.php?start_date=<?= mgr_h($startDate) ?>&end_date=<?= mgr_h($endDate) ?>&team_id=<?= (int)$teamFilter ?>&csr_id=<?= (int)$agentFilter ?>" class="cm-btn cm-btn--primary" target="_blank"><i class="fas fa-download me-1"></i>Export</a>
  </div>
</div>

<form method="get" class="cm-card mb-3">
  <div style="display:flex;gap:12px;align-items:end;flex-wrap:wrap;">
    <div style="min-width:150px;">
      <label style="color:var(--cm-muted);font-size:.72rem;font-weight:800;display:block;margin-bottom:4px;">START DATE</label>
      <input type="date" name="start_date" class="cm-input" value="<?= mgr_h($startDate) ?>">
    </div>
    <div style="min-width:150px;">
      <label style="color:var(--cm-muted);font-size:.72rem;font-weight:800;display:block;margin-bottom:4px;">END DATE</label>
      <input type="date" name="end_date" class="cm-input" value="<?= mgr_h($endDate) ?>">
    </div>
    <div style="min-width:180px;">
      <label style="color:var(--cm-muted);font-size:.72rem;font-weight:800;display:block;margin-bottom:4px;">TEAM</label>
      <select name="team_id" class="cm-select">
        <option value="0">All Teams</option>
        <?php foreach ($allTeamsForFilter as $t): ?>
          <option value="<?= (int)$t['id'] ?>" <?= $teamFilter === (int)$t['id'] ? 'selected' : '' ?>><?= mgr_h($t['team_name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div style="min-width:220px;">
      <label style="color:var(--cm-muted);font-size:.72rem;font-weight:800;display:block;margin-bottom:4px;">AGENT / TEAM LEADER</label>
      <select name="csr_id" class="cm-select">
        <option value="0">All Agents + Team Leaders</option>
        <?php foreach ($agentDropdown as $a): ?>
          <option value="<?= (int)$a['id'] ?>" <?= $agentFilter === (int)$a['id'] ? 'selected' : '' ?>><?= mgr_h(trim($a['full_name']) ?: ('CSR #'.$a['id'])) ?><?= in_array(($a['role'] ?? ''), ['team_leader','csr_manager'], true) ? ' (Team Leader)' : '' ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <button class="cm-btn cm-btn--primary" type="submit"><i class="fas fa-search me-1"></i>Apply</button>
    <a class="cm-btn" href="report.php"><i class="fas fa-times me-1"></i>Reset</a>
  </div>
</form>

<div class="cm-range-note"><i class="fas fa-calendar-days me-1"></i>Default view shows totals from <strong>01/01/2026</strong> up to <strong>today</strong>. Filters will update every total below from the selected Start Date to End Date.</div>

<div class="cm-report-metrics">
  <?php foreach ($metricCards as [$k,$label,$color]): ?>
  <div class="cm-card cm-report-metric">
    <div class="cm-report-metric__label"><?= mgr_h($label) ?></div>
    <div class="cm-report-metric__value" style="color:<?= mgr_h($color) ?>;"><?= (int)($totals[$k] ?? 0) ?></div>
  </div>
  <?php endforeach; ?>
</div>

<?php if ($teamGroups): ?>
<div class="cm-team-summary-grid">
  <?php $summaryColors = ['var(--cm-cyan)','var(--cm-green)','var(--cm-purple)','var(--cm-yellow)']; $si = 0; ?>
  <?php foreach ($teamGroups as $teamId => $group): $tt = $group['totals']; $teamName = (string)($group['team_name'] ?? ('Team #' . $teamId)); $teamIdForLink = (int)($group['team_id'] ?? $teamId); ?>
    <div class="cm-team-summary-card" onclick="window.location.href='report.php?start_date=<?= mgr_h($startDate) ?>&end_date=<?= mgr_h($endDate) ?>&team_id=<?= $teamIdForLink ?>'">
      <div class="cm-team-summary-head">
        <div class="cm-team-summary-name" style="color:<?= $summaryColors[$si++ % count($summaryColors)] ?>"><?= mgr_h(strtoupper($teamName)) ?></div>
        <div class="cm-team-summary-hint">Click to filter</div>
      </div>
      <div class="cm-team-summary-grid-inner">
        <div class="cm-team-summary-row"><span>Agents</span><span><?= count($group['rows']) ?></span></div>
        <div class="cm-team-summary-row"><span>Total Handled</span><span style="color:var(--cm-cyan)"><?= (int)$tt['handled_today'] ?></span></div>
        <div class="cm-team-summary-row"><span>Assigned Tickets</span><span style="color:var(--cm-blue)"><?= (int)$tt['assigned_tickets'] ?></span></div>
        <div class="cm-team-summary-row"><span>In Progress</span><span style="color:var(--cm-purple)"><?= (int)$tt['in_progress'] ?></span></div>
        <div class="cm-team-summary-row"><span>Completed Tickets</span><span style="color:var(--cm-green)"><?= (int)$tt['completed_today'] ?></span></div>
        <div class="cm-team-summary-row"><span>Cancelled Tickets</span><span style="color:var(--cm-red)"><?= (int)$tt['cancelled_today'] ?></span></div>
        <div class="cm-team-summary-row"><span>Total Calls</span><span><?= (int)$tt['total_calls'] ?></span></div>
        <div class="cm-team-summary-row"><span>Calls Scheduled</span><span style="color:var(--cm-cyan)"><?= (int)$tt['calls_scheduled'] ?></span></div>
        <div class="cm-team-summary-row"><span>Connected</span><span style="color:var(--cm-green)"><?= (int)$tt['connected'] ?></span></div>
        <div class="cm-team-summary-row"><span>Missed / Absent</span><span style="color:var(--cm-yellow)"><?= (int)$tt['missed_absent'] ?></span></div>
        <div class="cm-team-summary-row"><span>Updates</span><span style="color:var(--cm-purple)"><?= (int)$tt['updates'] ?></span></div>
        <div class="cm-team-summary-row"><span>Warnings</span><span style="color:var(--cm-yellow)"><?= (int)$tt['warnings'] ?></span></div>
        <div class="cm-team-summary-row"><span>Mistakes</span><span style="color:var(--cm-red)"><?= (int)$tt['mistakes'] ?></span></div>
      </div>
    </div>
  <?php endforeach; ?>
</div>
<?php endif; ?>

<div class="cm-detail-table-card">
  <div class="cm-detail-table-head">
    <div>
      <div class="cm-detail-table-title"><i class="fas fa-table me-2"></i>Team Details Table</div>
      <div class="cm-detail-table-sub">Remade to match the team container style. Each team below has its own table and total row.</div>
    </div>
    <div class="cm-table-note">Showing <?= count($rows) ?> user<?= count($rows) === 1 ? '' : 's' ?></div>
  </div>

  <?php if (!$teamGroups): ?>
    <div class="cm-detail-team-card"><div class="cm-empty-team-row">No agents or team leaders found for this filter.</div></div>
  <?php else: ?>
    <div class="cm-detail-team-list">
      <?php $detailColors = ['var(--cm-cyan)','var(--cm-green)','var(--cm-purple)','var(--cm-yellow)']; $di = 0; ?>
      <?php foreach ($teamGroups as $teamId => $group): $teamName = (string)($group['team_name'] ?? ('Team #' . $teamId)); $tt = $group['totals']; ?>
        <div class="cm-detail-team-card" id="team-report-<?= (int)$teamId ?>">
          <div class="cm-detail-team-head">
            <div class="cm-detail-team-name" style="color:<?= $detailColors[$di++ % count($detailColors)] ?>"><?= mgr_h(strtoupper($teamName)) ?></div>
            <div class="cm-detail-team-meta"><?= count($group['rows']) ?> member<?= count($group['rows']) === 1 ? '' : 's' ?></div>
          </div>

          <?php if (empty($group['rows'])): ?>
            <div class="cm-empty-team-row"><i class="fas fa-circle-info me-1"></i>No active CSR agents are assigned to this team yet.</div>
          <?php else: ?>
            <div class="cm-container-table-wrap">
              <table class="cm-container-table">
                <thead>
                  <tr>
                    <th>Name</th>
                    <th>Role</th>
                    <th>Total Handled</th>
                    <th>Assigned</th>
                    <th>In Progress</th>
                    <th>Completed</th>
                    <th>Cancelled</th>
                    <th>Total Calls</th>
                    <th>Scheduled</th>
                    <th>Connected</th>
                    <th>Missed</th>
                    <th>Updates</th>
                    <th>Warnings</th>
                    <th>Mistakes</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($group['rows'] as $r): ?>
                    <tr>
                      <td><strong><?= mgr_h(trim($r['full_name']) ?: ('CSR #'.$r['id'])) ?></strong></td>
                      <td>
                        <?php if (in_array(($r['role'] ?? ''), ['team_leader','csr_manager'], true)): ?>
                          <span class="cm-badge cm-badge--yellow">Team Leader</span>
                        <?php else: ?>
                          <span class="cm-badge cm-badge--blue">CSR Agent</span>
                        <?php endif; ?>
                      </td>
                      <td><span class="cm-num cyan"><?= (int)$r['handled_today'] ?></span></td>
                      <td><span class="cm-num blue"><?= (int)$r['assigned_tickets'] ?></span></td>
                      <td><span class="cm-num purple"><?= (int)$r['in_progress'] ?></span></td>
                      <td><span class="cm-num green"><?= (int)$r['completed_today'] ?></span></td>
                      <td><span class="cm-num red"><?= (int)$r['cancelled_today'] ?></span></td>
                      <td><span class="cm-num"><?= (int)$r['total_calls'] ?></span></td>
                      <td><span class="cm-num cyan"><?= (int)$r['calls_scheduled'] ?></span></td>
                      <td><span class="cm-num green"><?= (int)$r['connected'] ?></span></td>
                      <td><span class="cm-num yellow"><?= (int)$r['missed_absent'] ?></span></td>
                      <td><span class="cm-num purple"><?= (int)$r['updates'] ?></span></td>
                      <td><span class="cm-num yellow"><?= (int)$r['warnings'] ?></span></td>
                      <td><span class="cm-num red"><?= (int)$r['mistakes'] ?></span></td>
                    </tr>
                  <?php endforeach; ?>
                  <tr class="cm-detail-total-row">
                    <td colspan="2">TEAM TOTAL — <?= mgr_h(strtoupper($teamName)) ?></td>
                    <td><span class="cm-num cyan"><?= (int)$tt['handled_today'] ?></span></td>
                    <td><span class="cm-num blue"><?= (int)$tt['assigned_tickets'] ?></span></td>
                    <td><span class="cm-num purple"><?= (int)$tt['in_progress'] ?></span></td>
                    <td><span class="cm-num green"><?= (int)$tt['completed_today'] ?></span></td>
                    <td><span class="cm-num red"><?= (int)$tt['cancelled_today'] ?></span></td>
                    <td><span class="cm-num"><?= (int)$tt['total_calls'] ?></span></td>
                    <td><span class="cm-num cyan"><?= (int)$tt['calls_scheduled'] ?></span></td>
                    <td><span class="cm-num green"><?= (int)$tt['connected'] ?></span></td>
                    <td><span class="cm-num yellow"><?= (int)$tt['missed_absent'] ?></span></td>
                    <td><span class="cm-num purple"><?= (int)$tt['updates'] ?></span></td>
                    <td><span class="cm-num yellow"><?= (int)$tt['warnings'] ?></span></td>
                    <td><span class="cm-num red"><?= (int)$tt['mistakes'] ?></span></td>
                  </tr>
                </tbody>
              </table>
            </div>
          <?php endif; ?>
        </div>
      <?php endforeach; ?>
    </div>

    <div class="cm-grand-container-card">
      <div class="cm-grand-container-title"><i class="fas fa-calculator me-2"></i>Grand Total — All Teams</div>
      <div class="cm-grand-grid">
        <div class="cm-grand-row"><span>Total Handled</span><span style="color:var(--cm-cyan)"><?= (int)$totals['handled_today'] ?></span></div>
        <div class="cm-grand-row"><span>Assigned Tickets</span><span style="color:var(--cm-blue)"><?= (int)$totals['assigned_tickets'] ?></span></div>
        <div class="cm-grand-row"><span>In Progress</span><span style="color:var(--cm-purple)"><?= (int)$totals['in_progress'] ?></span></div>
        <div class="cm-grand-row"><span>Completed Tickets</span><span style="color:var(--cm-green)"><?= (int)$totals['completed_today'] ?></span></div>
        <div class="cm-grand-row"><span>Cancelled Tickets</span><span style="color:var(--cm-red)"><?= (int)$totals['cancelled_today'] ?></span></div>
        <div class="cm-grand-row"><span>Total Calls</span><span><?= (int)$totals['total_calls'] ?></span></div>
        <div class="cm-grand-row"><span>Calls Scheduled</span><span style="color:var(--cm-cyan)"><?= (int)$totals['calls_scheduled'] ?></span></div>
        <div class="cm-grand-row"><span>Connected</span><span style="color:var(--cm-green)"><?= (int)$totals['connected'] ?></span></div>
        <div class="cm-grand-row"><span>Missed / Absent</span><span style="color:var(--cm-yellow)"><?= (int)$totals['missed_absent'] ?></span></div>
        <div class="cm-grand-row"><span>Updates</span><span style="color:var(--cm-purple)"><?= (int)$totals['updates'] ?></span></div>
        <div class="cm-grand-row"><span>Warnings</span><span style="color:var(--cm-yellow)"><?= (int)$totals['warnings'] ?></span></div>
        <div class="cm-grand-row"><span>Mistakes</span><span style="color:var(--cm-red)"><?= (int)$totals['mistakes'] ?></span></div>
      </div>
    </div>
  <?php endif; ?>
</div>

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