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

function update_weather_data() {
    $api_key = OPENWEATHERMAP_API_KEY;
    $lat = 7.1164;
    $lon = 171.1850;
    $url = "https://api.openweathermap.org/data/3.0/onecall?lat={$lat}&lon={$lon}&exclude=minutely,hourly,daily&appid={$api_key}&units=metric";

    $response = file_get_contents($url);
    $data = json_decode($response, true);

    if ($data) {
        $temperature = $data['current']['temp'];
        $humidity = $data['current']['humidity'];
        $wind_speed = $data['current']['wind_speed'];
        $precipitation = isset($data['current']['rain']['1h']) ? $data['current']['rain']['1h'] : 0;
        
        $alert_status = false;
        $alert_message = 'No alerts';
        
        $db = db();

        if (!empty($data['alerts'])) {
            $alert_status = true;
            $alert_message = $data['alerts'][0]['event'] . ": " . $data['alerts'][0]['description'];
            
            // Send email alert
            $to = 'admin@majuroeats.com';
            $subject = 'Weather Alert for Majuro';
            $htmlBody = "<h1>Weather Alert</h1><p>{$alert_message}</p>";
            MailService::sendMail($to, $subject, $htmlBody);

            // Log the event
            $event_type = 'Weather Alert';
            $description = $alert_message;
            $severity = 'Warning'; // Or determine from alert data if possible
            $triggered_by = 'System (Weather Monitor)';
            $status = 'Ongoing';

            $stmt_log = $db->prepare("INSERT INTO system_events (event_type, description, severity, triggered_by, status) VALUES (?, ?, ?, ?, ?)");
            $stmt_log->execute([$event_type, $description, $severity, $triggered_by, $status]);
        }

        $stmt = $db->prepare(
            'INSERT INTO weather_status (temperature, humidity, wind_speed, precipitation, alert_status, alert_message)'
            . ' VALUES (?, ?, ?, ?, ?, ?)'
        );

        try {
            $stmt->execute([$temperature, $humidity, $wind_speed, $precipitation, $alert_status ? 'true' : 'false', $alert_message]);
            echo "Weather data updated successfully.";
        } catch (PDOException $e) {
            echo "Error updating weather data: " . $e->getMessage();
        }
    }
}