<?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 = 'Call 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; }
$calls = rows($db, "SELECT cr.*, COALESCE(sr.request_number,'—') request_number, COALESCE(b.name,sr.manual_brand,'—') brand, COALESCE(c.city_name,sr.service_address,'—') 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=:id1 OR cr.accepted_by=:id2) AND DATE(cr.queued_at) BETWEEN :date_from AND :date_to ORDER BY cr.queued_at DESC", [':id1'=>$csrId, ':id2'=>$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 Call Log</div><div class="table-responsive"><table class="table table-hover align-middle" id="callLogTable"><thead><tr><th>Date</th><th>Customer / City</th><th>Brand</th><th>Type</th><th>Status</th><th>Duration</th><th>Notes</th></tr></thead><tbody><?php foreach($calls as $c): $dur=(int)($c['call_duration_seconds'] ?? 0); $type = ($c['provider'] ?? '') === 'manual' ? 'Scheduled' : 'Inbound'; ?><tr><td><?= xh(dt($c['queued_at'])) ?></td><td><?= xh(($c['customer_name'] ?? '—') . ' / ' . ($c['city'] ?? '—')) ?></td><td><?= xh($c['brand'] ?? '—') ?></td><td><?= xh($type) ?></td><td><span class="badge bg-info"><?= xh(ucwords(str_replace('_',' ', $c['status'] ?? 'pending'))) ?></span></td><td><?= $dur ? xh(gmdate('i:s',$dur)) : '—' ?></td><td><?= xh($c['notes'] ?? '') ?></td></tr><?php endforeach; ?></tbody></table></div></div>
<script>$(function(){ if($.fn.DataTable) $('#callLogTable').DataTable({order:[[0,'desc']],pageLength:25}); });</script>
<?php $content = ob_get_clean(); include __DIR__ . '/layout.php';
