<?php
/**
 * Helper to fetch date-specific weather forecast.
 */
function gp_get_weather_forecast(PDO $pdo, string $city, string $startDate): ?array {
    static $weatherApiKey = null;
    static $cityWeatherCache = [];

    if ($weatherApiKey === null) {
        $weatherApiKey = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'weather_api_key'")->fetchColumn();
    }

    if (!$weatherApiKey || empty($city)) return null;

    $dtProject = strtotime($startDate);
    $dtNow = time();
    $daysDiff = ($dtProject - $dtNow) / 86400;

    // Only show forecast if within 5 days.
    if ($daysDiff < -1 || $daysDiff > 5) return null;

    $cacheKey = $city . '_' . $startDate;
    if (isset($cityWeatherCache[$cacheKey])) return $cityWeatherCache[$cacheKey];

    $url = "https://api.openweathermap.org/data/2.5/forecast?q=" . urlencode($city) . "&units=metric&appid=" . $weatherApiKey;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    curl_close($ch);

    if ($res) {
        $data = json_decode($res, true);
        if (!empty($data['list'])) {
            $targetTime = $startDate . ' 12:00:00';
            $bestMatch = null;
            $minDiff = 999999;

            foreach ($data['list'] as $f) {
                $diff = abs(strtotime($f['dt_txt']) - strtotime($targetTime));
                if ($diff < $minDiff) {
                    $minDiff = $diff;
                    $bestMatch = $f;
                }
            }

            if ($bestMatch && substr($bestMatch['dt_txt'], 0, 10) === $startDate) {
                $w = [
                    'temp' => round($bestMatch['main']['temp']),
                    'icon' => $bestMatch['weather'][0]['icon'] ?? '01d',
                    'description' => $bestMatch['weather'][0]['description'] ?? ''
                ];
                $cityWeatherCache[$cacheKey] = $w;
                return $w;
            }
        }
    }

    return null;
}
