<?php
/**
 * Weather API Proxy — OpenWeatherMap
 * ?action=current (default) — current conditions
 * ?action=forecast — 5-day forecast grouped by day
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$action = $_GET['action'] ?? 'current';
$apiKey = OPENWEATHER_API_KEY;
$city = env('OPENWEATHER_CITY', 'Cincinnati');
$units = env('OPENWEATHER_UNITS', 'imperial');
$ctx = stream_context_create(['http' => ['timeout' => 10, 'ignore_errors' => true]]);

if (empty($apiKey)) {
    jsonResponse(['error' => 'Weather API key not configured'], 500);
}

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

    // Fetch 5-day/3-hour forecast
    $url = "https://api.openweathermap.org/data/2.5/forecast?q={$city},US&units={$units}&appid={$apiKey}";
    $response = @file_get_contents($url, false, $ctx);
    if ($response === false) {
        if (file_exists($cacheFile)) { header('Content-Type: application/json'); readfile($cacheFile); exit; }
        jsonResponse(['error' => 'Unable to fetch forecast'], 502);
    }

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

    // Group by day
    $days = [];
    foreach ($data['list'] as $item) {
        $date = date('Y-m-d', $item['dt']);
        if (!isset($days[$date])) {
            $days[$date] = [
                'date'      => $date,
                'day_name'  => date('D', $item['dt']),
                'day_full'  => date('l', $item['dt']),
                'month_day' => date('M j', $item['dt']),
                'temps'     => [],
                'icons'     => [],
                'conditions' => [],
                'humidity'  => [],
                'wind'      => [],
                'pop'       => [],
            ];
        }
        $days[$date]['temps'][] = $item['main']['temp'] ?? 0;
        $days[$date]['icons'][] = $item['weather'][0]['icon'] ?? '01d';
        $days[$date]['conditions'][] = $item['weather'][0]['description'] ?? '';
        $days[$date]['humidity'][] = $item['main']['humidity'] ?? 0;
        $days[$date]['wind'][] = $item['wind']['speed'] ?? 0;
        $days[$date]['pop'][] = ($item['pop'] ?? 0) * 100;
    }

    $forecast = [];
    foreach ($days as $day) {
        // Pick the most common midday icon (prefer 12:00-15:00 readings)
        $iconCounts = array_count_values($day['icons']);
        arsort($iconCounts);
        $topIcon = array_key_first($iconCounts);
        // Use daytime icon
        $topIcon = str_replace('n', 'd', $topIcon);

        $condCounts = array_count_values($day['conditions']);
        arsort($condCounts);

        $forecast[] = [
            'date'       => $day['date'],
            'day_name'   => $day['day_name'],
            'day_full'   => $day['day_full'],
            'month_day'  => $day['month_day'],
            'high'       => round(max($day['temps'])),
            'low'        => round(min($day['temps'])),
            'icon'       => $topIcon,
            'conditions' => array_key_first($condCounts),
            'humidity'   => round(array_sum($day['humidity']) / count($day['humidity'])),
            'wind'       => round(array_sum($day['wind']) / count($day['wind'])),
            'rain_pct'   => round(max($day['pop'])),
        ];
    }

    $result = ['forecast' => array_values($forecast), 'city' => $city, 'cached_at' => date('c')];
    @file_put_contents($cacheFile, json_encode($result));
    jsonResponse($result);
}

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

$url = "https://api.openweathermap.org/data/2.5/weather?q={$city},US&units={$units}&appid={$apiKey}";
$response = @file_get_contents($url, false, $ctx);

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

$data = json_decode($response, true);
if (!$data || !isset($data['main'])) {
    jsonResponse(['error' => 'Invalid weather data received'], 502);
}

$result = [
    'temp'       => $data['main']['temp'] ?? 0,
    'feels_like' => $data['main']['feels_like'] ?? 0,
    'temp_min'   => $data['main']['temp_min'] ?? 0,
    'temp_max'   => $data['main']['temp_max'] ?? 0,
    'humidity'   => $data['main']['humidity'] ?? 0,
    'pressure'   => $data['main']['pressure'] ?? 0,
    'conditions' => $data['weather'][0]['description'] ?? 'Unknown',
    'icon'       => $data['weather'][0]['icon'] ?? '01d',
    'wind_speed' => $data['wind']['speed'] ?? 0,
    'wind_deg'   => $data['wind']['deg'] ?? 0,
    'visibility' => round(($data['visibility'] ?? 0) / 1609, 1),
    'sunrise'    => $data['sys']['sunrise'] ?? 0,
    'sunset'     => $data['sys']['sunset'] ?? 0,
    'city'       => $data['name'] ?? $city,
    'cached_at'  => date('c'),
];

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