<?php
/**
 * Traffic API — Merges HERE Traffic (flow + incidents) + OHGO (construction/incidents)
 * Returns GeoJSON flow lines + incident markers for Mapbox GL rendering.
 */
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('max_execution_time', 30);

require_once __DIR__ . '/../config/auth.php';
requireLogin();

$action = $_GET['action'] ?? 'all';
$cacheFile = __DIR__ . '/../uploads/traffic_cache.json';

// 2-minute cache for traffic data
if ($action === 'all' && file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 120) {
    header('Content-Type: application/json');
    readfile($cacheFile);
    exit;
}

function curlFetch($url, $headers = [], $timeout = 12) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING => '',
        CURLOPT_USERAGENT => 'CFDPortal/1.0',
        CURLOPT_HTTPHEADER => $headers,
    ]);
    $res = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return ($code >= 200 && $code < 400) ? $res : null;
}

// ── HERE Traffic Flow ──────────────────────────────────
function fetchHereFlow() {
    $key = defined('HERE_API_KEY') ? HERE_API_KEY : '4FXTgj268naOB3m7fTe8TyqJgwVpo8VfJAZ0IfNBNZY';
    if (!$key) return ['type' => 'FeatureCollection', 'features' => []];

    // Smaller radius + only functionalClass 1-3 (major roads) to stay within memory
    $url = "https://data.traffic.hereapi.com/v7/flow?locationReferencing=shape&in=circle:39.1031,-84.5120;r=15000&functionalClasses=1,2,3&apiKey={$key}";
    $raw = curlFetch($url, [], 15);
    if (!$raw) return ['type' => 'FeatureCollection', 'features' => []];

    $data = json_decode($raw, true);
    if (!$data) return ['type' => 'FeatureCollection', 'features' => []];
    $features = [];

    foreach (($data['results'] ?? []) as $segment) {
        $flow = $segment['currentFlow'] ?? [];
        $jamFactor = $flow['jamFactor'] ?? 0;
        $speed = $flow['speed'] ?? 0;
        $freeFlow = $flow['freeFlow'] ?? 0;

        // Only include segments with some congestion OR major roads
        $location = $segment['location'] ?? [];
        $shape = $location['shape'] ?? [];
        if (empty($shape) || !isset($shape['links'])) continue;

        // Limit to first link per segment to reduce memory
        $link = $shape['links'][0] ?? [];
        $points = $link['points'] ?? [];
        if (count($points) < 2) continue;

        $coords = [];
        foreach ($points as $pt) {
            $coords[] = [round($pt['lng'], 5), round($pt['lat'], 5)];
        }

        $features[] = [
            'type' => 'Feature',
            'geometry' => ['type' => 'LineString', 'coordinates' => $coords],
            'properties' => [
                'jamFactor' => round($jamFactor, 1),
                'speed' => round($speed * 2.237, 0),
                'freeFlow' => round($freeFlow * 2.237, 0),
            ],
        ];

        if (count($features) >= 500) break; // cap at 500 segments
    }

    return ['type' => 'FeatureCollection', 'features' => $features];
}

// ── HERE Traffic Incidents ─────────────────────────────
function fetchHereIncidents() {
    $key = defined('HERE_API_KEY') ? HERE_API_KEY : '4FXTgj268naOB3m7fTe8TyqJgwVpo8VfJAZ0IfNBNZY';
    if (!$key) return [];

    $url = "https://data.traffic.hereapi.com/v7/incidents?locationReferencing=shape&in=circle:39.1031,-84.5120;r=20000&apiKey={$key}";
    $raw = curlFetch($url);
    if (!$raw) return [];

    $data = json_decode($raw, true);
    $incidents = [];

    foreach (($data['results'] ?? []) as $item) {
        $details = $item['incidentDetails'] ?? [];
        $location = $item['location'] ?? [];
        $desc = $details['description']['value'] ?? '';
        $type = $details['type'] ?? 'other';
        $road = $location['description']['value'] ?? '';

        // Get coordinates from shape
        $shape = $location['shape'] ?? [];
        $lat = $lng = null;
        if (!empty($shape['links'][0]['points'][0])) {
            $lat = $shape['links'][0]['points'][0]['lat'];
            $lng = $shape['links'][0]['points'][0]['lng'];
        }
        if (!$lat) continue;

        $incidents[] = [
            'type' => $type,
            'description' => $desc ?: $type,
            'road' => $road,
            'lat' => $lat,
            'lng' => $lng,
            'source' => 'here',
            'severity' => $details['severity'] ?? 'unknown',
        ];
    }

    return $incidents;
}

// ── OHGO Incidents + Construction ──────────────────────
function fetchOhgoData() {
    $key = defined('OHGO_API_KEY') ? OHGO_API_KEY : '9ae3adee-63fb-4a3e-ad87-b96a24e745e1';
    if (!$key) return [];

    $items = [];

    // Incidents
    $raw = curlFetch("https://publicapi.ohgo.com/api/v1/incidents?region=Cincinnati", ["Authorization: APIKEY {$key}"]);
    if ($raw) {
        $data = json_decode($raw, true);
        foreach (($data['results'] ?? $data ?? []) as $inc) {
            if (!is_array($inc) || empty($inc['latitude'])) continue;
            $items[] = [
                'type' => 'accident',
                'description' => $inc['description'] ?? 'Incident',
                'road' => $inc['routeName'] ?? '',
                'lat' => (float)$inc['latitude'],
                'lng' => (float)$inc['longitude'],
                'source' => 'ohgo',
                'severity' => 'major',
            ];
        }
    }

    // Construction
    $raw = curlFetch("https://publicapi.ohgo.com/api/v1/construction?region=Cincinnati", ["Authorization: APIKEY {$key}"]);
    if ($raw) {
        $data = json_decode($raw, true);
        foreach (($data['results'] ?? $data ?? []) as $con) {
            if (!is_array($con) || empty($con['latitude'])) continue;
            $items[] = [
                'type' => 'construction',
                'description' => $con['description'] ?? 'Construction',
                'road' => $con['routeName'] ?? '',
                'lat' => (float)$con['latitude'],
                'lng' => (float)$con['longitude'],
                'source' => 'ohgo',
                'severity' => 'minor',
            ];
        }
    }

    return $items;
}

// ── Build response ─────────────────────────────────────
try {
$flow = fetchHereFlow();
$hereIncidents = fetchHereIncidents();
$ohgoData = fetchOhgoData();

// Merge incidents
$allIncidents = array_merge($hereIncidents, $ohgoData);

// Count by type
$counts = ['accident' => 0, 'roadClosure' => 0, 'construction' => 0, 'other' => 0];
foreach ($allIncidents as $inc) {
    $t = $inc['type'];
    if ($t === 'accident' || $t === 'congestion') $counts['accident']++;
    elseif ($t === 'roadClosure' || $t === 'roadClosed') $counts['roadClosure']++;
    elseif ($t === 'construction') $counts['construction']++;
    else $counts['other']++;
}

$result = [
    'flow' => $flow,
    'incidents' => $allIncidents,
    'counts' => $counts,
    'total' => count($allIncidents),
    'flow_segments' => count($flow['features']),
    'cached_at' => date('c'),
];

@file_put_contents($cacheFile, json_encode($result));
jsonResponse($result);
} catch (Exception $e) {
    jsonResponse(['error' => $e->getMessage(), 'flow' => ['type'=>'FeatureCollection','features'=>[]], 'incidents' => [], 'counts' => ['accident'=>0,'roadClosure'=>0,'construction'=>0,'other'=>0], 'total' => 0, 'flow_segments' => 0], 500);
}
