<?php
/**
 * Active911 Webhook Receiver
 * Public POST endpoint — no session auth, uses shared secret.
 *
 * URL: https://cincinnatifire.ai/api/webhook-active911.php?secret=CFD_A911_2026
 * Configure this URL in Active911 webhook settings or n8n forwarding.
 */

require_once __DIR__ . '/../config/db.php';
date_default_timezone_set('America/New_York');

// Only accept POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo 'Method Not Allowed';
    exit;
}

// Validate shared secret
$secret = $_GET['secret'] ?? '';
$expectedSecret = env('ACTIVE911_WEBHOOK_SECRET', 'CFD_A911_2026');
if ($secret !== $expectedSecret) {
    http_response_code(403);
    echo 'Forbidden';
    exit;
}

// Read raw JSON body
$rawBody = file_get_contents('php://input');
if (empty($rawBody)) {
    http_response_code(400);
    echo 'Empty body';
    exit;
}

// Log raw payload for debugging (first 100 payloads)
$logDir = __DIR__ . '/../uploads';
$logFile = $logDir . '/a911_webhook_log.jsonl';
$logCount = file_exists($logFile) ? count(file($logFile)) : 0;
if ($logCount < 100) {
    @file_put_contents($logFile, date('c') . "\t" . $rawBody . "\n", FILE_APPEND);
}

$data = json_decode($rawBody, true);
if (!$data) {
    http_response_code(400);
    echo 'Invalid JSON';
    exit;
}

$db = getDB();

// Active911 nests data inside alert.normalized_message
$alert = $data['alert'] ?? $data;
$norm = $alert['normalized_message'] ?? $alert;
$agencyData = $data['agency'] ?? [];

// Extract fields — normalized_message takes priority, then flat keys
$incidentId = (string)($alert['id'] ?? $data['alert_id'] ?? $data['id'] ?? uniqid('a911_'));
$type       = trim($norm['description'] ?? $alert['description'] ?? $data['description'] ?? 'Unknown');
$address    = trim($norm['address'] ?? $norm['map_address'] ?? $alert['address'] ?? $data['address'] ?? '');
$city       = trim($norm['city'] ?? $alert['city'] ?? $data['city'] ?? $agencyData['name'] ?? 'Cincinnati');
$lat        = $norm['lat'] ?? $norm['latitude'] ?? $data['latitude'] ?? $data['lat'] ?? null;
$lng        = $norm['lon'] ?? $norm['longitude'] ?? $data['longitude'] ?? $data['lon'] ?? null;
$priority   = $norm['priority'] ?? $alert['priority'] ?? $data['priority'] ?? '3';
$status     = $data['status'] ?? 'active';

// Units — string or array
$rawUnits = $norm['units'] ?? $alert['units'] ?? $data['units'] ?? $data['unit'] ?? '';
$units = is_array($rawUnits) ? implode(',', $rawUnits) : (string)$rawUnits;

// Clean up address (remove extra whitespace from CAD padding)
$address = preg_replace('/\s{2,}/', ' ', $address);
$address = preg_replace('/\s*Apartment:\s*$/', '', $address);

// Append place name if available
$place = trim($norm['place'] ?? $data['place'] ?? '');
if ($place && stripos($address, $place) === false) {
    $address = $place . ' - ' . $address;
}

$stmt = $db->prepare("
    INSERT INTO incidents_cache (incident_id, incident_type, address, city, units_assigned, priority, status, latitude, longitude, raw_json, received_at, displayed)
    VALUES (:iid, :type, :addr, :city, :units, :priority, :status, :lat, :lng, :raw, :received_at, 0)
    ON DUPLICATE KEY UPDATE
        incident_type = VALUES(incident_type),
        address = VALUES(address),
        units_assigned = VALUES(units_assigned),
        status = VALUES(status),
        raw_json = VALUES(raw_json),
        displayed = 0
");

try {
    $stmt->execute([
        ':iid'      => $incidentId,
        ':type'     => $type,
        ':addr'     => $address,
        ':city'     => $city,
        ':units'    => $units,
        ':priority' => $priority,
        ':status'   => $status,
        ':lat'      => $lat,
        ':lng'      => $lng,
        ':raw'      => $rawBody,
        ':received_at' => date('Y-m-d H:i:s'),
    ]);
} catch (Exception $e) {
    error_log('Active911 webhook insert error: ' . $e->getMessage());
    http_response_code(500);
    echo 'DB error';
    exit;
}

http_response_code(200);
echo 'ok';
