<?php
/**
 * Active Incidents API — serves from incidents_cache DB table.
 * Data flows in via webhook-active911.php.
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$action = $_GET['action'] ?? 'list';
$db = getDB();

switch ($action) {
    case 'new':
        $stmt = $db->query("SELECT * FROM incidents_cache WHERE displayed = 0 ORDER BY received_at DESC LIMIT 10");
        $incidents = $stmt->fetchAll();
        if (!empty($incidents)) {
            $ids = array_column($incidents, 'id');
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $db->prepare("UPDATE incidents_cache SET displayed = 1 WHERE id IN ($placeholders)")->execute($ids);
        }
        jsonResponse(['incidents' => $incidents]);
        break;

    case 'list':
        $hours = min((int)($_GET['hours'] ?? 24), 168);
        $stmt = $db->prepare("SELECT * FROM incidents_cache WHERE received_at >= DATE_SUB(NOW(), INTERVAL :hours HOUR) ORDER BY received_at DESC");
        $stmt->execute([':hours' => $hours]);
        jsonResponse(['incidents' => $stmt->fetchAll()]);
        break;

    case 'stats':
        $total24h = (int)$db->query("SELECT COUNT(*) FROM incidents_cache WHERE received_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)")->fetchColumn();
        $total7d = (int)$db->query("SELECT COUNT(*) FROM incidents_cache WHERE received_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();
        $latest = $db->query("SELECT received_at FROM incidents_cache ORDER BY received_at DESC LIMIT 1")->fetchColumn();
        jsonResponse(['total_24h' => $total24h, 'total_7d' => $total7d, 'latest' => $latest]);
        break;

    case 'today_stats':
        date_default_timezone_set('America/New_York');
        $currentShift = getCurrentShiftBounds();
        $prevShift = getPreviousShiftBounds();
        $todayStart = $currentShift['start'];
        $todayEnd = $currentShift['end'];
        $yesterdayStart = $prevShift['start'];
        $shift = $currentShift['shift'];

        // Current shift count
        $stmt = $db->prepare("SELECT COUNT(DISTINCT incident_id) FROM incidents_cache WHERE received_at >= ? AND received_at < ?");
        $stmt->execute([$todayStart, $todayEnd]);
        $todayCount = (int)$stmt->fetchColumn();

        // Previous shift count
        $stmt = $db->prepare("SELECT COUNT(DISTINCT incident_id) FROM incidents_cache WHERE received_at >= ? AND received_at < ?");
        $stmt->execute([$yesterdayStart, $todayStart]);
        $yesterdayCount = (int)$stmt->fetchColumn();

        // Call types this shift (cleaned)
        $stmt = $db->prepare("SELECT incident_type, COUNT(*) as cnt FROM incidents_cache WHERE received_at >= ? AND received_at < ? GROUP BY incident_type ORDER BY cnt DESC");
        $stmt->execute([$todayStart, $todayEnd]);
        $rawTypes = $stmt->fetchAll();
        $types = [];
        foreach ($rawTypes as $row) {
            $clean = preg_replace('/\s*[-]\s*[\d\w]*\s*CFD\d+.*$/', '', $row['incident_type']);
            $clean = preg_replace('/\s*CFD\d+.*$/', '', $clean);
            $clean = preg_replace('/^=/', '', $clean);
            $clean = trim($clean) ?: 'UNKNOWN';
            $types[$clean] = ($types[$clean] ?? 0) + (int)$row['cnt'];
        }
        arsort($types);
        $types = array_slice($types, 0, 12, true);

        // Hourly volume this shift
        $stmt = $db->prepare("SELECT HOUR(received_at) as hr, COUNT(*) as cnt FROM incidents_cache WHERE received_at >= ? AND received_at < ? GROUP BY hr ORDER BY hr");
        $stmt->execute([$todayStart, $todayEnd]);
        $hourlyRaw = $stmt->fetchAll();
        $hourly = array_fill(0, 24, 0);
        foreach ($hourlyRaw as $row) $hourly[(int)$row['hr']] = (int)$row['cnt'];

        // Priority breakdown this shift
        $stmt = $db->prepare("SELECT priority, COUNT(*) as cnt FROM incidents_cache WHERE received_at >= ? AND received_at < ? GROUP BY priority ORDER BY priority");
        $stmt->execute([$todayStart, $todayEnd]);
        $priorities = [];
        foreach ($stmt->fetchAll() as $row) $priorities[$row['priority'] ?: '3'] = (int)$row['cnt'];

        // Busiest units this shift
        $stmt = $db->prepare("SELECT units_assigned FROM incidents_cache WHERE received_at >= ? AND received_at < ?");
        $stmt->execute([$todayStart, $todayEnd]);
        $unitCounts = [];
        foreach ($stmt->fetchAll() as $row) {
            foreach (explode(',', $row['units_assigned']) as $u) {
                $u = trim($u);
                if ($u) $unitCounts[$u] = ($unitCounts[$u] ?? 0) + 1;
            }
        }
        arsort($unitCounts);
        $topUnits = array_slice($unitCounts, 0, 10, true);

        // YTD totals (all data in incidents_cache)
        $ytdTotal = (int)$db->query("SELECT COUNT(DISTINCT incident_id) FROM incidents_cache")->fetchColumn();
        $ytdStruct = (int)$db->query("SELECT COUNT(DISTINCT incident_id) FROM incidents_cache WHERE incident_type LIKE '%STRUCT%'")->fetchColumn();
        $ytdAlarms = (int)$db->query("SELECT COUNT(DISTINCT incident_id) FROM incidents_cache WHERE incident_type LIKE '%FALARM%' OR incident_type LIKE '%CALARM%'")->fetchColumn();
        $ytdSince = $db->query("SELECT MIN(received_at) FROM incidents_cache")->fetchColumn();

        jsonResponse([
            'today' => $todayCount,
            'yesterday' => $yesterdayCount,
            'diff' => $todayCount - $yesterdayCount,
            'types' => $types,
            'hourly' => $hourly,
            'priorities' => $priorities,
            'top_units' => $topUnits,
            'ytd_total' => $ytdTotal,
            'ytd_struct' => $ytdStruct,
            'ytd_alarms' => $ytdAlarms,
            'ytd_since' => $ytdSince,
            'shift' => $shift,
            'shift_start' => $todayStart,
            'shift_end' => $todayEnd,
            'prev_shift' => $prevShift['shift'],
            'date' => date('l, F j, Y'),
            'updated_at' => date('c'),
        ]);
        break;

    default:
        jsonResponse(['error' => 'Unknown action'], 400);
}
