<?php
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/discipline_system.php';
$db = (new Database())->getConnection();
discEnsureTables($db);
$csrId = (int)$_SESSION['csr_id'];
function xh($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }
function dt($v){ return $v ? date('M j, Y g:i A', strtotime($v)) : '—'; }
function rows(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 scalar(PDO $db, string $sql, array $params=[]): int { try{$s=$db->prepare($sql);$s->execute($params);return (int)$s->fetchColumn();}catch(Exception $e){return 0;} }

$title = 'Performance';
$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; }
$perf = rows($db, "
SELECT d.day_date,
       DAYNAME(d.day_date) AS day_name,
       COALESCE(sr.handled_today,0) AS handled_today,
       COALESCE(sr.assigned_tickets,0) AS assigned_tickets,
       COALESCE(sr.in_progress,0) AS in_progress,
       COALESCE(sr.completed_today,0) AS completed_today,
       COALESCE(sr.cancelled_today,0) AS cancelled_today,
       COALESCE(cr.total_calls,0) AS total_calls,
       COALESCE(cr.calls_scheduled,0) AS calls_scheduled,
       COALESCE(cr.connected,0) AS connected,
       COALESCE(cr.missed_absent,0) AS missed_absent,
       COALESCE(a.updates,0) AS updates,
       COALESCE(a.warnings,0) + COALESCE(dr.warnings,0) AS warnings,
       COALESCE(a.mistakes,0) + COALESCE(dr.mistakes,0) AS mistakes
FROM (
  SELECT DATE(COALESCE(last_updated_at, completed_date, requested_at)) day_date
  FROM service_requests
  WHERE (assigned_csr_id=:d_sr_a OR handled_by_csr_id=:d_sr_h OR created_by_csr_id=:d_sr_c)
    AND DATE(COALESCE(last_updated_at, completed_date, requested_at)) BETWEEN :d_from1 AND :d_to1
  UNION
  SELECT DATE(queued_at) day_date
  FROM call_requests
  WHERE (assigned_csr_id=:d_cr_a OR accepted_by=:d_cr_b)
    AND DATE(queued_at) BETWEEN :d_from2 AND :d_to2
  UNION
  SELECT DATE(created_at) day_date
  FROM csr_activity
  WHERE csr_id=:d_act
    AND DATE(created_at) BETWEEN :d_from3 AND :d_to3
  UNION
  SELECT DATE(created_at) day_date
  FROM csr_discipline_records
  WHERE recipient_id=:d_disc
    AND DATE(created_at) BETWEEN :d_from4 AND :d_to4
) d
LEFT JOIN (
  SELECT day_date,
         COUNT(*) AS handled_today,
         SUM(COALESCE(job_status_id,1) NOT IN (4,5)) AS assigned_tickets,
         SUM(job_status_id = 3) AS in_progress,
         SUM(job_status_id = 4) AS completed_today,
         SUM(job_status_id = 5) AS cancelled_today
  FROM (
    SELECT id,
           COALESCE(job_status_id,1) AS job_status_id,
           DATE(COALESCE(last_updated_at, completed_date, requested_at)) AS day_date
    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)) BETWEEN :sr_from AND :sr_to
  ) x
  GROUP BY day_date
) sr ON sr.day_date=d.day_date
LEFT JOIN (
  SELECT DATE(queued_at) day_date,
         COUNT(*) AS total_calls,
         SUM(status IN ('assigned','manager_queue','scheduled','pending')) AS calls_scheduled,
         SUM(status IN ('accepted','completed','connected')) AS connected,
         SUM(status IN ('missed','cancelled','no_answer','no answer')) AS missed_absent
  FROM call_requests
  WHERE (assigned_csr_id=:cr_a OR accepted_by=:cr_b)
    AND DATE(queued_at) BETWEEN :cr_from AND :cr_to
  GROUP BY DATE(queued_at)
) cr ON cr.day_date=d.day_date
LEFT JOIN (
  SELECT DATE(created_at) day_date,
         SUM(action IN ('status_change','note_added','request_claimed','manual_ticket_created') OR action LIKE '%update%') AS updates,
         SUM(action LIKE '%warning%' OR details LIKE '%warning%') AS warnings,
         SUM(action LIKE '%mistake%' OR action LIKE '%error%' OR details LIKE '%mistake%' OR details LIKE '%error%') AS mistakes
  FROM csr_activity
  WHERE csr_id=:act_id
    AND DATE(created_at) BETWEEN :act_from AND :act_to
  GROUP BY DATE(created_at)
) a ON a.day_date=d.day_date
LEFT JOIN (
  SELECT DATE(created_at) day_date,
         SUM(record_type = 'warning') AS warnings,
         SUM(record_type = 'mistake') AS mistakes
  FROM csr_discipline_records
  WHERE recipient_id=:disc_id
    AND DATE(created_at) BETWEEN :disc_from AND :disc_to
  GROUP BY DATE(created_at)
) dr ON dr.day_date=d.day_date
ORDER BY d.day_date DESC", [
  ':d_sr_a'=>$csrId, ':d_sr_h'=>$csrId, ':d_sr_c'=>$csrId, ':d_from1'=>$dateFrom, ':d_to1'=>$dateTo,
  ':d_cr_a'=>$csrId, ':d_cr_b'=>$csrId, ':d_from2'=>$dateFrom, ':d_to2'=>$dateTo,
  ':d_act'=>$csrId, ':d_from3'=>$dateFrom, ':d_to3'=>$dateTo,
  ':d_disc'=>$csrId, ':d_from4'=>$dateFrom, ':d_to4'=>$dateTo,
  ':sr_a'=>$csrId, ':sr_h'=>$csrId, ':sr_c'=>$csrId, ':sr_from'=>$dateFrom, ':sr_to'=>$dateTo,
  ':cr_a'=>$csrId, ':cr_b'=>$csrId, ':cr_from'=>$dateFrom, ':cr_to'=>$dateTo,
  ':act_id'=>$csrId, ':act_from'=>$dateFrom, ':act_to'=>$dateTo,
  ':disc_id'=>$csrId, ':disc_from'=>$dateFrom, ':disc_to'=>$dateTo
]);
ob_start(); ?>
<form method="get" class="ca-filter-form">
  <div>
    <label class="form-label" for="date_from">Date From</label>
    <input type="date" class="form-control" id="date_from" name="date_from" value="<?= xh($dateFrom) ?>">
  </div>
  <div>
    <label class="form-label" for="date_to">Date To</label>
    <input type="date" class="form-control" id="date_to" name="date_to" value="<?= xh($dateTo) ?>">
  </div>
  <button type="submit" class="cm-btn cm-btn--primary"><i class="fas fa-filter"></i> Apply Filter</button>
  <a href="<?= xh(basename(__FILE__)) ?>" class="cm-btn"><i class="fas fa-rotate-left"></i> Reset</a>
</form>
<div class="cm-card"><div class="cm-card__title">My Performance</div><div class="table-responsive"><table class="table table-hover align-middle" id="performanceTable"><thead><tr><th>Date</th><th>Day</th><th>Handled</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($perf as $p): ?><tr><td><?= xh(date('M j, Y', strtotime($p['day_date']))) ?></td><td><?= xh($p['day_name']) ?></td><td><?= (int)$p['handled_today'] ?></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['updates'] ?></td><td><?= (int)$p['warnings'] ?></td><td><?= (int)$p['mistakes'] ?></td></tr><?php endforeach; ?></tbody></table></div></div>
<script>$(function(){ if($.fn.DataTable) $('#performanceTable').DataTable({order:[[0,'desc']],pageLength:31}); });</script>
<?php $content = ob_get_clean(); include __DIR__ . '/layout.php';
