<?php
// csr/dashboard.php — CSR Agent dashboard styled like CSR Manager dashboard
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['csr_id'])) { header('Location: ../login.php'); exit(); }
// CSR main page is Tickets. Use dashboard.php?profile=1 to view old profile dashboard.
if (!isset($_GET['profile'])) { header('Location: requests.php'); exit(); }
if (isset($_SESSION['csr_role']) && $_SESSION['csr_role'] === 'csr_manager') { header('Location: ../csr_manager/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);
$csrId = (int)$_SESSION['csr_id'];
$title = 'Dashboard';

function caCount(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 caRows(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 caDate($v): string { return $v ? date('M j, Y g:i A', strtotime($v)) : '—'; }
function caStatusBadge($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 caCallStatusBadge($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>';
}

$csr = caRows($db, "SELECT * FROM csr_users WHERE id = :csr_id LIMIT 1", [':csr_id' => $csrId]);
$csr = $csr[0] ?? [];
$sessionName = trim((string)($_SESSION['csr_name'] ?? ''));
$dbName = trim(($csr['first_name'] ?? '').' '.($csr['last_name'] ?? ''));
$name = $dbName ?: ($sessionName ?: 'CSR Agent');
$email = $csr['email'] ?? ($_SESSION['csr_email'] ?? '—');
$role = $csr['role'] ?? ($_SESSION['csr_role'] ?? 'csr');
$roleDisplay = $role === 'team_leader' ? 'CSR Team Leader' : ($role === 'csr_manager' ? 'CSR Manager' : 'CSR Agent');
$lastLogin = $csr['last_login'] ?? null;
$phone = $csr['phone_number'] ?? '—';

// Important: use unique placeholders. Some hosting PDO configs do not allow reusing the same named placeholder more than once.
$handledToday = caCount($db, "
    SELECT COUNT(DISTINCT request_id) FROM (
        SELECT request_id FROM csr_activity WHERE csr_id = :a_id AND request_id IS NOT NULL AND DATE(created_at) = CURDATE()
        UNION
        SELECT id AS request_id FROM service_requests
        WHERE (assigned_csr_id = :sr_a OR handled_by_csr_id = :sr_h OR created_by_csr_id = :sr_c)
          AND DATE(COALESCE(last_updated_at, completed_date, requested_at)) = CURDATE()
    ) x
", [':a_id'=>$csrId, ':sr_a'=>$csrId, ':sr_h'=>$csrId, ':sr_c'=>$csrId]);

$assigned = caCount($db, "
    SELECT COUNT(*) FROM service_requests
    WHERE (assigned_csr_id = :a_id OR handled_by_csr_id = :h_id)
      AND COALESCE(job_status_id, 1) NOT IN (4, 5)
", [':a_id'=>$csrId, ':h_id'=>$csrId]);

$inProgress = caCount($db, "
    SELECT COUNT(*) FROM service_requests
    WHERE (assigned_csr_id = :a_id OR handled_by_csr_id = :h_id OR created_by_csr_id = :c_id)
      AND job_status_id = 3
", [':a_id'=>$csrId, ':h_id'=>$csrId, ':c_id'=>$csrId]);

$completed = caCount($db, "
    SELECT COUNT(DISTINCT request_id) FROM (
        SELECT id AS request_id FROM service_requests
        WHERE (assigned_csr_id = :a_id OR handled_by_csr_id = :h_id OR created_by_csr_id = :c_id)
          AND job_status_id = 4
          AND DATE(COALESCE(completed_date, last_updated_at, requested_at)) = CURDATE()
        UNION
        SELECT request_id FROM csr_activity
        WHERE csr_id = :act_id AND action = 'status_change' AND details LIKE '%4%' AND DATE(created_at) = CURDATE()
    ) x
", [':a_id'=>$csrId, ':h_id'=>$csrId, ':c_id'=>$csrId, ':act_id'=>$csrId]);

$cancelled = caCount($db, "
    SELECT COUNT(*) FROM service_requests
    WHERE (assigned_csr_id = :a_id OR handled_by_csr_id = :h_id OR created_by_csr_id = :c_id)
      AND job_status_id = 5
      AND DATE(COALESCE(last_updated_at, requested_at)) = CURDATE()
", [':a_id'=>$csrId, ':h_id'=>$csrId, ':c_id'=>$csrId]);

$totalCalls = caCount($db, "
    SELECT COUNT(*) FROM call_requests
    WHERE (assigned_csr_id = :a_id OR accepted_by = :accepted_id)
      AND DATE(queued_at) = CURDATE()
", [':a_id'=>$csrId, ':accepted_id'=>$csrId]);

$connectedCalls = caCount($db, "
    SELECT COUNT(*) FROM call_requests
    WHERE (assigned_csr_id = :a_id OR accepted_by = :accepted_id)
      AND status IN ('accepted','completed')
      AND DATE(COALESCE(accepted_at, completed_at, queued_at)) = CURDATE()
", [':a_id'=>$csrId, ':accepted_id'=>$csrId]);

$scheduledCalls = caCount($db, "
    SELECT COUNT(*) FROM call_requests
    WHERE (assigned_csr_id = :a_id OR accepted_by = :accepted_id)
      AND status IN ('assigned','manager_queue')
      AND DATE(queued_at) = CURDATE()
", [':a_id'=>$csrId, ':accepted_id'=>$csrId]);

$missedCalls = caCount($db, "
    SELECT COUNT(*) FROM call_requests
    WHERE (assigned_csr_id = :a_id OR accepted_by = :accepted_id)
      AND status IN ('missed','cancelled')
      AND DATE(queued_at) = CURDATE()
", [':a_id'=>$csrId, ':accepted_id'=>$csrId]);

$ticketUpdates = caCount($db, "
    SELECT COUNT(*) FROM csr_activity
    WHERE csr_id = :csr_id
      AND (action IN ('status_change','note_added','request_claimed','manual_ticket_created') OR action LIKE '%update%')
      AND DATE(created_at) = CURDATE()
", [':csr_id'=>$csrId]);

$warnings = caCount($db, "
    SELECT COUNT(*) FROM csr_activity
    WHERE csr_id = :csr_id
      AND (action LIKE '%warning%' OR details LIKE '%warning%')
      AND DATE(created_at) = CURDATE()
", [':csr_id'=>$csrId]);
$warnings += caCount($db, "
    SELECT COUNT(*) FROM csr_discipline_records
    WHERE recipient_id = :csr_id
      AND record_type = 'warning'
      AND DATE(created_at) = CURDATE()
", [':csr_id'=>$csrId]);

$mistakes = caCount($db, "
    SELECT COUNT(*) FROM csr_activity
    WHERE csr_id = :csr_id
      AND (action LIKE '%mistake%' OR action LIKE '%error%' OR details LIKE '%mistake%' OR details LIKE '%error%')
      AND DATE(created_at) = CURDATE()
", [':csr_id'=>$csrId]);
$mistakes += caCount($db, "
    SELECT COUNT(*) FROM csr_discipline_records
    WHERE recipient_id = :csr_id
      AND record_type = 'mistake'
      AND DATE(created_at) = CURDATE()
", [':csr_id'=>$csrId]);

$recentTickets = caRows($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
    FROM csr_activity ca
    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 ca.csr_id = :csr_id
    ORDER BY ca.created_at DESC
    LIMIT 8
", [':csr_id'=>$csrId]);

if (!$recentTickets) {
    $recentTickets = caRows($db, "
        SELECT
            COALESCE(sr.last_updated_at, sr.requested_at) AS activity_at,
            'ticket_activity' AS action,
            '' AS 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
        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 (sr.assigned_csr_id = :a_id OR sr.handled_by_csr_id = :h_id OR sr.created_by_csr_id = :c_id)
        ORDER BY COALESCE(sr.last_updated_at, sr.requested_at) DESC
        LIMIT 8
    ", [':a_id'=>$csrId, ':h_id'=>$csrId, ':c_id'=>$csrId]);
}

$recentCalls = caRows($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
    FROM call_requests cr
    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 (cr.assigned_csr_id = :assigned_id OR cr.accepted_by = :accepted_id)
    ORDER BY cr.queued_at DESC
    LIMIT 8
", [':assigned_id'=>$csrId, ':accepted_id'=>$csrId]);

ob_start();
?>
<div class="ca-quick-bar">
  <a class="cm-btn" href="requests.php"><i class="fas fa-clipboard-list"></i> Requests</a>
  <a class="cm-btn" href="manual_ticket.php"><i class="fas fa-ticket-alt"></i> Manual Ticket</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>
  <a class="cm-btn" href="technicians.php"><i class="fas fa-user-gear"></i> Technicians</a>
  <a class="cm-btn" href="messages.php"><i class="fas fa-comments"></i> Messages</a>
  <a class="cm-btn" href="performance.php"><i class="fas fa-chart-line"></i> 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">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(caDate($lastLogin), ENT_QUOTES, 'UTF-8') ?></strong></div></div>
      </div>
    </div>
    <span class="badge bg-primary">My CSR Workspace</span>
  </div>
</div>

<div class="ca-stat-grid mb-3">
  <div class="ca-stat"><div class="ca-stat__icon"><i class="fas fa-headset"></i></div><div class="ca-stat__value"><?= $handledToday ?></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)"><?= $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)"><?= $inProgress ?></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)"><?= $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)"><?= $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"><?= $totalCalls ?></div><div class="ca-stat__label">Total Calls Today</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)"><?= $scheduledCalls ?></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)"><?= $connectedCalls ?></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)"><?= $missedCalls ?></div><div class="ca-stat__label">Absent / Missed</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)"><?= $ticketUpdates ?></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)"><?= $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)"><?= $mistakes ?></div><div class="ca-stat__label">Mistakes</div></div>
</div>

<div class="ca-grid-2">
  <div class="cm-card">
    <div class="cm-card__title">Recent Ticket Activity</div>
    <div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Date / Time</th><th>Request #</th><th>Customer</th><th>City</th><th>Brand</th><th>Status</th></tr></thead><tbody>
      <?php if (!$recentTickets): ?><tr><td colspan="6" class="text-center text-muted py-4">No ticket activity yet.</td></tr><?php endif; ?>
      <?php foreach ($recentTickets as $r): ?>
        <tr>
          <td><?= htmlspecialchars(caDate($r['activity_at'] ?? null), 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><?= htmlspecialchars($r['brand'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= caStatusBadge($r['status_name'] ?? 'New') ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody></table></div>
  </div>
  <div class="cm-card">
    <div class="cm-card__title">Recent Call Activity</div>
    <div class="table-responsive"><table class="table table-sm align-middle mb-0"><thead><tr><th>Date</th><th>Customer / City</th><th>Brand</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 call activity yet.</td></tr><?php endif; ?>
      <?php foreach ($recentCalls as $c): $dur = (int)($c['call_duration_seconds'] ?? 0); ?>
        <tr>
          <td><?= htmlspecialchars(caDate($c['queued_at'] ?? null), ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars(($c['customer_name'] ?? '—').' / '.($c['city'] ?? '—'), ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= htmlspecialchars($c['brand'] ?? '—', ENT_QUOTES, 'UTF-8') ?></td>
          <td><?= caCallStatusBadge($c['status'] ?? 'pending') ?></td>
          <td><?= $dur ? gmdate('i:s', $dur) : '—' ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody></table></div>
  </div>
</div>
<?php
$content = ob_get_clean();
include __DIR__ . '/layout.php';
