<?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';
$db = (new Database())->getConnection();
$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 = 'Ticket Log';
$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; }
$owned = "(sr.assigned_csr_id = :id1 OR sr.handled_by_csr_id = :id2 OR sr.created_by_csr_id = :id3)";
$tickets = rows($db, "SELECT sr.*, COALESCE(b.name,sr.manual_brand,'—') brand, COALESCE(c.city_name,sr.service_address,'—') city, COALESCE(js.status_name,'New Request') status_name, CONCAT(t.first_name,' ',t.last_name) technician 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 LEFT JOIN service_assignments sa ON sa.request_id=sr.id AND sa.status <> 'cancelled' LEFT JOIN technicians t ON t.id=sa.technician_id WHERE $owned AND DATE(sr.requested_at) BETWEEN :date_from AND :date_to ORDER BY sr.requested_at DESC", [':id1'=>$csrId, ':id2'=>$csrId, ':id3'=>$csrId, ':date_from'=>$dateFrom, ':date_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 Ticket Log</div><div class="table-responsive"><table class="table table-hover align-middle" id="ticketLogTable"><thead><tr><th>Date / Time</th><th>Request #</th><th>Customer</th><th>City</th><th>Brand</th><th>Status</th><th>Source</th><th>Technician</th><th>Last Updated</th></tr></thead><tbody><?php foreach($tickets as $t): ?><tr><td><?= xh(dt($t['requested_at'])) ?></td><td><?= xh($t['request_number']) ?></td><td><?= xh($t['full_name']) ?></td><td><?= xh($t['city']) ?></td><td><?= xh($t['brand']) ?></td><td><span class="badge bg-primary"><?= xh($t['status_name']) ?></span></td><td><?= xh($t['ticket_source'] ?: 'cx_online') ?></td><td><?= xh($t['technician'] ?: '—') ?></td><td><?= xh(dt($t['last_updated_at'])) ?></td></tr><?php endforeach; ?></tbody></table></div></div>
<script>$(function(){ if($.fn.DataTable) $('#ticketLogTable').DataTable({order:[[0,'desc']],pageLength:25}); });</script>
<?php $content = ob_get_clean(); include __DIR__ . '/layout.php';
