<?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';
$db = (new Database())->getConnection();
$title = 'Team Agents';
$leaderId = (int)$_SESSION['csr_id'];
$leaderStmt = $db->prepare("SELECT first_name, last_name FROM csr_users WHERE id = :id LIMIT 1");
$leaderStmt->execute([':id' => $leaderId]);
$leader = $leaderStmt->fetch(PDO::FETCH_ASSOC) ?: [];
$leaderName = trim(($leader['first_name'] ?? '') . ' ' . ($leader['last_name'] ?? '')) ?: 'Team Leader';
$teamLabel = 'Team ' . $leaderName;
function taDate($v){ return $v ? date('M j, Y g:i A', strtotime($v)) : '—'; }
$teamStmt = $db->prepare("SELECT * FROM csr_teams WHERE manager_id = :id AND is_active = 1 ORDER BY id ASC LIMIT 1");
$teamStmt->execute([':id'=>$leaderId]);
$team = $teamStmt->fetch(PDO::FETCH_ASSOC);
$agents = [];
if ($team) {
    $stmt = $db->prepare("SELECT cu.* 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");
    $stmt->execute([':team_id'=>(int)$team['id']]);
    $agents = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
ob_start();
?>
<div class="cm-card">
  <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
    <div>
      <div class="cm-card__title mb-1"><?= htmlspecialchars($teamLabel, ENT_QUOTES, 'UTF-8') ?></div>
      <h3 class="mb-0" style="font-family:'Space Grotesk',system-ui,sans-serif;font-weight:900;">CSR Agents</h3>
    </div>
    <span class="badge bg-info"><?= count($agents) ?> Agent<?= count($agents) === 1 ? '' : 's' ?></span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover align-middle mb-0">
      <thead><tr><th>Name</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 $a): ?>
        <tr>
          <td><strong><?= htmlspecialchars(trim(($a['first_name'] ?? '').' '.($a['last_name'] ?? '')), ENT_QUOTES, 'UTF-8') ?></strong><br><small class="text-muted">CSR Agent</small></td>
          <td><?= htmlspecialchars($a['email'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($a['phone_number'] ?: '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= ((int)($a['is_active'] ?? 0) === 1) ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>' ?></td>
          <td><?= htmlspecialchars(taDate($a['last_login'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>
<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
