<?php
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') { header('Location: 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 = 'Team Performance';

function tph($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function tpRows(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 tpInClause(string $col, array $ids, string $prefix, array &$params): string {
    $keys=[];
    foreach(array_values(array_unique(array_map('intval',$ids))) as $i=>$id){
        $k=':'.$prefix.$i;
        $keys[]=$k;
        $params[$k]=$id;
    }
    return $keys ? $col.' IN ('.implode(',', $keys).')' : '1=0';
}

function tpScalar(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 tpIdWhere(string $col, array $ids, string $prefix, array &$params): string {
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids), fn($v) => $v > 0)));
    if (!$ids) return '1=0';
    $keys = [];
    foreach ($ids as $i => $id) {
        $k = ':' . $prefix . $i;
        $keys[] = $k;
        $params[$k] = $id;
    }
    return $col . ' IN (' . implode(',', $keys) . ')';
}

function tpAnyCsrWhere(array $ids, array &$params, string $prefix='csr'): string {
    $a = tpIdWhere('assigned_csr_id', $ids, $prefix.'a', $params);
    $h = tpIdWhere('handled_by_csr_id', $ids, $prefix.'h', $params);
    $c = tpIdWhere('created_by_csr_id', $ids, $prefix.'c', $params);
    return "($a OR $h OR $c)";
}

function tpAnyCallWhere(array $ids, array &$params, string $prefix='call'): string {
    $a = tpIdWhere('assigned_csr_id', $ids, $prefix.'a', $params);
    $b = tpIdWhere('accepted_by', $ids, $prefix.'b', $params);
    return "($a OR $b)";
}

function buildPerformanceRows(PDO $db, array $ids, string $dateFrom, string $dateTo): array {
    $ids = array_values(array_unique(array_filter(array_map('intval', $ids), fn($v) => $v > 0)));
    if (!$ids) return [];

    $rows = [];
    $start = new DateTime($dateFrom);
    $end = new DateTime($dateTo);
    $end->setTime(0, 0, 0);

    for ($d = clone $end; $d >= $start; $d->modify('-1 day')) {
        $day = $d->format('Y-m-d');
        $displayDate = $d->format('M j, Y');

        $p=[];
        $srWhere = tpAnyCsrWhere($ids, $p, 'sr');
        $p[':day'] = $day;
        $ticketDateExpr = "DATE(COALESCE(last_updated_at, completed_date, requested_at))";
        $assigned = tpScalar($db, "SELECT COUNT(*) FROM service_requests WHERE $srWhere AND $ticketDateExpr = :day", $p);

        $p=[];
        $srWhere = tpAnyCsrWhere($ids, $p, 'ip');
        $p[':day'] = $day;
        $inProgress = tpScalar($db, "SELECT COUNT(*) FROM service_requests WHERE $srWhere AND job_status_id = 3 AND DATE(COALESCE(in_progress_started_at, last_updated_at, requested_at)) = :day", $p);

        $p=[];
        $srWhere = tpAnyCsrWhere($ids, $p, 'co');
        $p[':day'] = $day;
        $completed = tpScalar($db, "SELECT COUNT(*) FROM service_requests WHERE $srWhere AND job_status_id = 4 AND DATE(COALESCE(completed_date, last_updated_at, requested_at)) = :day", $p);

        $p=[];
        $srWhere = tpAnyCsrWhere($ids, $p, 'ca');
        $p[':day'] = $day;
        $cancelled = tpScalar($db, "SELECT COUNT(*) FROM service_requests WHERE $srWhere AND job_status_id = 5 AND DATE(COALESCE(last_updated_at, requested_at)) = :day", $p);

        $p=[];
        $callWhere = tpAnyCallWhere($ids, $p, 'tc');
        $p[':day'] = $day;
        $callDateExpr = "DATE(COALESCE(updated_at, completed_at, accepted_at, assigned_at, queued_at))";
        $totalCalls = tpScalar($db, "SELECT COUNT(*) FROM call_requests WHERE $callWhere AND $callDateExpr = :day", $p);

        $p=[];
        $callWhere = tpAnyCallWhere($ids, $p, 'cs');
        $p[':day'] = $day;
        $callsScheduled = tpScalar($db, "SELECT COUNT(*) FROM call_requests WHERE $callWhere AND status IN ('manager_queue','assigned') AND DATE(COALESCE(assigned_at, queued_at, updated_at)) = :day", $p);

        $p=[];
        $callWhere = tpAnyCallWhere($ids, $p, 'cn');
        $p[':day'] = $day;
        $connected = tpScalar($db, "SELECT COUNT(*) FROM call_requests WHERE $callWhere AND status IN ('accepted','completed') AND DATE(COALESCE(completed_at, accepted_at, updated_at, queued_at)) = :day", $p);

        $p=[];
        $callWhere = tpAnyCallWhere($ids, $p, 'mi');
        $p[':day'] = $day;
        $missedAbsent = tpScalar($db, "SELECT COUNT(*) FROM call_requests WHERE $callWhere AND status IN ('missed','cancelled') AND DATE(COALESCE(updated_at, queued_at)) = :day", $p);

        $p=[];
        $actWhere = tpIdWhere('csr_id', $ids, 'ac', $p);
        $p[':day'] = $day;
        $updates = tpScalar($db, "SELECT COUNT(*) FROM csr_activity WHERE $actWhere AND DATE(created_at) = :day AND (action IN ('status_change','note_added','request_claimed','manual_ticket_created') OR action LIKE '%update%' OR details LIKE '%update%')", $p);

        $p=[];
        $actWhere = tpIdWhere('csr_id', $ids, 'wa', $p);
        $p[':day'] = $day;
        $warnings = tpScalar($db, "SELECT COUNT(*) FROM csr_activity WHERE $actWhere AND DATE(created_at) = :day AND (action LIKE '%warning%' OR details LIKE '%warning%')", $p);
        $p=[];
        $discWhere = tpIdWhere('recipient_id', $ids, 'dw', $p);
        $p[':day'] = $day;
        $warnings += tpScalar($db, "SELECT COUNT(*) FROM csr_discipline_records WHERE $discWhere AND record_type='warning' AND DATE(created_at) = :day", $p);

        $p=[];
        $actWhere = tpIdWhere('csr_id', $ids, 'mi', $p);
        $p[':day'] = $day;
        $mistakes = tpScalar($db, "SELECT COUNT(*) FROM csr_activity WHERE $actWhere AND DATE(created_at) = :day AND (action LIKE '%mistake%' OR action LIKE '%error%' OR details LIKE '%mistake%' OR details LIKE '%error%')", $p);
        $p=[];
        $discWhere = tpIdWhere('recipient_id', $ids, 'dm', $p);
        $p[':day'] = $day;
        $mistakes += tpScalar($db, "SELECT COUNT(*) FROM csr_discipline_records WHERE $discWhere AND record_type='mistake' AND DATE(created_at) = :day", $p);

        $rows[] = [
            'day_date' => $day,
            'display_date' => $displayDate,
            'assigned_tickets' => $assigned,
            'in_progress' => $inProgress,
            'completed_today' => $completed,
            'cancelled_today' => $cancelled,
            'total_calls' => $totalCalls,
            'calls_scheduled' => $callsScheduled,
            'connected' => $connected,
            'missed_absent' => $missedAbsent,
            'ticket_updates' => $updates,
            'warnings' => $warnings,
            'mistakes' => $mistakes,
        ];
    }
    return $rows;
}

$teams = tpRows($db, "SELECT id, team_name FROM csr_teams WHERE manager_id = :id AND is_active = 1 ORDER BY id ASC", [':id'=>$leaderId]);
$teamIds = array_map(fn($r)=>(int)$r['id'], $teams);
$leaderName = trim(($_SESSION['csr_name'] ?? '') ?: ($_SESSION['first_name'] ?? '') . ' ' . ($_SESSION['last_name'] ?? ''));
$teamName = $leaderName !== '' ? 'Team ' . $leaderName : ($teams[0]['team_name'] ?? 'Team');

$agentParams=[];
$agents=[];
$agentIds=[];
if($teamIds){
    $teamClause=tpInClause('tm.team_id',$teamIds,'tm',$agentParams);
    $agents=tpRows($db,"SELECT u.id, CONCAT(u.first_name,' ',u.last_name) name, u.email, u.last_login FROM csr_team_members tm JOIN csr_users u ON u.id=tm.csr_id WHERE $teamClause AND u.role='csr' ORDER BY u.first_name,u.last_name",$agentParams);
    $agentIds=array_map(fn($r)=>(int)$r['id'],$agents);
}

$dateFrom = $_GET['date_from'] ?? date('Y-m-01');
$dateTo = $_GET['date_to'] ?? date('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateFrom)) $dateFrom = date('Y-m-01');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $dateTo)) $dateTo = date('Y-m-d');
if (strtotime($dateFrom) > strtotime($dateTo)) { $tmp=$dateFrom; $dateFrom=$dateTo; $dateTo=$tmp; }

$personalDaily = buildPerformanceRows($db, [$leaderId], $dateFrom, $dateTo);
$teamDaily = buildPerformanceRows($db, $agentIds, $dateFrom, $dateTo);

ob_start(); ?>
<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_requests.php"><i class="fas fa-ticket-alt"></i> Team Requests</a>
  <a class="cm-btn" href="team_agents.php"><i class="fas fa-user-group"></i> Team Agents</a>
  <a class="cm-btn cm-btn--primary" href="team_performance.php"><i class="fas fa-chart-line"></i> Team Performance</a>
</div>

<div class="cm-card mb-3">
  <div class="d-flex flex-wrap justify-content-between align-items-start gap-3">
    <div>
      <div class="cm-card__title mb-1">Performance</div>
      <h2 style="font-family:'Space Grotesk',system-ui,sans-serif;font-weight:900;">Team Leader Performance</h2>
      <p class="text-muted mb-0">Shows your personal performance and the total performance of CSR agents assigned to you.</p>
    </div>
    <span class="badge bg-info"><?= count($agentIds) ?> Agent<?= count($agentIds)===1?'':'s' ?></span>
  </div>
</div>

<form method="get" class="cm-card mb-3">
  <div class="row g-3 align-items-end">
    <div class="col-md-3">
      <label class="form-label">Date From</label>
      <input type="date" name="date_from" class="form-control" value="<?= tph($dateFrom) ?>">
    </div>
    <div class="col-md-3">
      <label class="form-label">Date To</label>
      <input type="date" name="date_to" class="form-control" value="<?= tph($dateTo) ?>">
    </div>
    <div class="col-md-4">
      <button type="submit" class="cm-btn cm-btn--primary"><i class="fas fa-filter"></i> Apply Filter</button>
      <a href="team_performance.php" class="cm-btn ms-2"><i class="fas fa-rotate-left"></i> Reset</a>
    </div>
  </div>
</form>

<?php
function renderPerformanceTable(string $tableId, string $emptyMessage, array $rows): void { ?>
  <div class="table-responsive">
    <table class="table table-hover align-middle" id="<?= tph($tableId) ?>" data-empty-message="<?= tph($emptyMessage) ?>">
      <thead>
        <tr>
          <th>Date</th>
          <th>Assigned Tickets</th>
          <th>In Progress</th>
          <th>Completed Today</th>
          <th>Cancelled Today</th>
          <th>Total Calls</th>
          <th>Calls Scheduled</th>
          <th>Connected</th>
          <th>Missed / Absent</th>
          <th>Updates</th>
          <th>Warnings</th>
          <th>Mistakes</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach($rows as $p): ?>
          <tr>
            <td><?= tph($p['display_date'] ?? date('M j, Y', strtotime($p['day_date']))) ?></td>
            <td><?= (int)$p['assigned_tickets'] ?></td>
            <td><?= (int)$p['in_progress'] ?></td>
            <td><?= (int)$p['completed_today'] ?></td>
            <td><?= (int)$p['cancelled_today'] ?></td>
            <td><?= (int)$p['total_calls'] ?></td>
            <td><?= (int)$p['calls_scheduled'] ?></td>
            <td><?= (int)$p['connected'] ?></td>
            <td><?= (int)$p['missed_absent'] ?></td>
            <td><?= (int)$p['ticket_updates'] ?></td>
            <td><?= (int)$p['warnings'] ?></td>
            <td><?= (int)$p['mistakes'] ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php } ?>

<div class="cm-card mb-3">
  <div class="cm-card__title">Personal Performance</div>
  <p class="text-muted mb-3">Your own ticket and call activity as a Team Leader.</p>
  <?php renderPerformanceTable('personalPerf', 'No personal activity found for this date range.', $personalDaily); ?>
</div>

<div class="cm-card">
  <div class="cm-card__title">Team Performance: <?= tph($teamName) ?></div>
  <p class="text-muted mb-3">Total performance for all CSR agents under this team.</p>
  <?php renderPerformanceTable('teamPerf', $agentIds ? 'No team activity found for this date range.' : 'No CSR agents are assigned to this Team Leader yet.', $teamDaily); ?>
</div>

<script>
$(function(){
  if($.fn.DataTable){
    ['#personalPerf', '#teamPerf'].forEach(function(selector){
      var $table = $(selector);
      $table.DataTable({
        order:[[0,'desc']],
        pageLength:31,
        language: { emptyTable: $table.data('empty-message') || 'No records found.' }
      });
    });
  }
});
</script>
<?php $content = ob_get_clean(); include __DIR__ . '/layout.php';
