<?php
require_once __DIR__ . '/../../app/core/bootstrap.php';
$pdo = crm_pdo();

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

if (!$weatherApiKey) {
    echo "ERROR: No API key found in settings table for 'weather_api_key'.\n";
} else {
    echo "API Key found: " . substr($weatherApiKey, 0, 4) . "..." . substr($weatherApiKey, -4) . "\n";
    
    // Test for a common city
    $city = "Athens";
    $url = "https://api.openweathermap.org/data/2.5/weather?q=" . urlencode($city) . "&units=metric&appid=" . $weatherApiKey;
    echo "Testing API with city: $city\n";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $res = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    echo "HTTP Status: $httpCode\n";
    if ($res) {
        $data = json_decode($res, true);
        if ($httpCode == 200) {
            echo "SUCCESS: Temp is " . $data['main']['temp'] . "°C, Description: " . $data['weather'][0]['description'] . "\n";
        } else {
            echo "API ERROR: " . ($data['message'] ?? 'Unknown error') . "\n";
        }
    } else {
        echo "CURL ERROR: Failed to get response.\n";
    }
}
