<?php
/**
 * ESO EMS Dashboard API — serves data from local MySQL
 * Called via AJAX from the dashboard page
 */
require_once __DIR__ . '/../../../config/auth.php';
requireAuth();

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

header('Content-Type: application/json');

switch ($action) {
    case 'summary':
        // Latest day's summary
        $row = $db->query("SELECT * FROM eso_ems_daily ORDER BY report_date DESC LIMIT 1")->fetch(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'data' => $row ?: null]);
        break;

    case 'trend':
        // Last N days of daily summaries
        $days = min((int)($_GET['days'] ?? 7), 90);
        $rows = $db->query("SELECT * FROM eso_ems_daily ORDER BY report_date DESC LIMIT {$days}")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'data' => array_reverse($rows)]);
        break;

    case 'incidents':
        // Individual incidents for a date
        $date = $_GET['date'] ?? date('Y-m-d', strtotime('-1 day'));
        $stmt = $db->prepare("SELECT * FROM eso_ems_incidents WHERE report_date = ? ORDER BY dispatched_at DESC");
        $stmt->execute([$date]);
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        break;

    case 'cardiac_arrests':
        // Recent cardiac arrests
        $days = min((int)($_GET['days'] ?? 7), 90);
        $rows = $db->query("SELECT * FROM eso_cardiac_arrests ORDER BY dispatched_at DESC LIMIT 50")->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['success' => true, 'data' => $rows]);
        break;

    case 'high_acuity':
        // High acuity incidents for a date
        $date = $_GET['date'] ?? date('Y-m-d', strtotime('-1 day'));
        $stmt = $db->prepare("
            SELECT * FROM eso_ems_incidents
            WHERE report_date = ?
              AND (is_cardiac_arrest = 1 OR is_stemi = 1 OR is_stroke = 1 OR is_overdose = 1 OR is_pediatric = 1)
            ORDER BY dispatched_at DESC
        ");
        $stmt->execute([$date]);
        echo json_encode(['success' => true, 'data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
        break;

    default:
        echo json_encode(['success' => false, 'error' => 'Unknown action']);
}
