<?php
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../mail/MailService.php';
require_once __DIR__ . '/../weather.php';

// This script should be run by a cron job every hour.

// IMPORTANT: This script assumes the delivery_time in the database is in UTC.
$now = new DateTime('now', new DateTimeZone('UTC'));
$current_hour = $now->format('H');

echo "Running weather alert script for hour: {$current_hour}:00 UTC\n";

try {
    $pdo = db();
    // Fetch subscriptions for the current hour
    $stmt = $pdo->prepare("SELECT ws.*, u.email, fl.city_name FROM weather_subscriptions ws JOIN users u ON ws.user_id = u.id JOIN favorite_locations fl ON ws.location_id = fl.id WHERE ws.is_active = 1 AND HOUR(ws.delivery_time) = ?");
    $stmt->execute([$current_hour]);
    $subscriptions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo "Found " . count($subscriptions) . " subscriptions to process.\n";

    foreach ($subscriptions as $subscription) {
        $city = $subscription['city_name'];
        $email = $subscription['email'];

        echo "Processing subscription for {$email} in {$city}...\n";

        $weatherData = getWeatherByCity($city);

        if (isset($weatherData['error'])) {
            echo "Could not get weather for {$city}: " . $weatherData['error'] . "\n";
            continue;
        }

        $subject = "Your Daily Weather Forecast for {$city}";
        $iconUrl = "https://openweathermap.org/img/wn/{$weatherData['weather'][0]['icon']}@2x.png";
        $htmlBody = ""
            . "<h1>Weather in {$weatherData['name']}</h1>"
            . "<img src=\"{$iconUrl}\" alt='Weather icon'>"
            . "<h2>{$weatherData['main']['temp']}°C</h2>"
            . "<p>{$weatherData['weather'][0]['description']}</p>"
            . "<p>Humidity: {$weatherData['main']['humidity']}%</p>";

        $result = MailService::sendMail($email, $subject, $htmlBody);

        if ($result['success']) {
            echo "Email sent to {$email} for {$city}.\n";
        } else {
            echo "Failed to send email to {$email} for {$city}. Error: {$result['error']}\n";
        }
    }

    echo "Finished processing subscriptions.\n";

} catch (PDOException $e) {
    die("DB ERROR: " . $e->getMessage());
}
?>
