<?php
/**
 * Ohio River Level API — USGS Water Services
 * Site: 03255000 (Ohio River at Cincinnati, OH)
 * Flood stage: 52 ft, Action stage: 46 ft
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$cacheFile = __DIR__ . '/../uploads/river_cache.json';
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < 1800) {
    header('Content-Type: application/json');
    readfile($cacheFile);
    exit;
}

$url = 'https://waterservices.usgs.gov/nwis/iv/?format=json&sites=03255000&parameterCd=00065&period=PT2H';
$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_ENCODING       => '',
]);
$response = curl_exec($ch);
curl_close($ch);

if (!$response) {
    if (file_exists($cacheFile)) { header('Content-Type: application/json'); readfile($cacheFile); exit; }
    jsonResponse(['error' => 'Unable to fetch river data'], 502);
}

$data = json_decode($response, true);
if (!$data || !isset($data['value']['timeSeries'][0])) {
    jsonResponse(['error' => 'Invalid river data'], 502);
}

$ts = $data['value']['timeSeries'][0];
$vals = $ts['values'][0]['value'] ?? [];
$latest = end($vals);
$level = (float)($latest['value'] ?? 0);
$time = $latest['dateTime'] ?? '';

// Determine status
$floodStage = 52.0;
$actionStage = 46.0;
$moderateStage = 40.0;

if ($level >= $floodStage) {
    $status = 'major_flood';
    $color = '#DC2626';
    $label = 'Major Flood';
} elseif ($level >= $actionStage) {
    $status = 'moderate_flood';
    $color = '#FF9500';
    $label = 'Moderate Flood';
} elseif ($level >= $moderateStage) {
    $status = 'action';
    $color = '#FFCC00';
    $label = 'Action Stage';
} else {
    $status = 'normal';
    $color = '#8CC63F';
    $label = 'Normal';
}

$result = [
    'level'        => $level,
    'unit'         => 'ft',
    'status'       => $status,
    'status_label' => $label,
    'color'        => $color,
    'flood_stage'  => $floodStage,
    'action_stage' => $actionStage,
    'site_name'    => 'Ohio River at Cincinnati',
    'measured_at'  => $time,
    'cached_at'    => date('c'),
];

@file_put_contents($cacheFile, json_encode($result));
jsonResponse($result);
