<?php
$pageTitle = 'Extended Forecast - Weather Portal';
$pageDescription = 'View 7-day and 14-day extended weather forecasts for your city. Track temperature, precipitation, wind, and more.';

$city = isset($_GET['city']) ? urldecode($_GET['city']) : 'Karachi';
$lat = isset($_GET['lat']) ? floatval($_GET['lat']) : null;
$lon = isset($_GET['lon']) ? floatval($_GET['lon']) : null;

$citiesFile = __DIR__ . '/data/cities.json';
$citiesData = file_exists($citiesFile) ? json_decode(file_get_contents($citiesFile), true) : [];
$cities = $citiesData['cities'] ?? [];

$selectedCity = null;
foreach ($cities as $c) {
    if (strtolower($c['name']) === strtolower($city)) {
        $selectedCity = $c;
        break;
    }
}

if ($selectedCity) {
    $lat = $selectedCity['lat'];
    $lon = $selectedCity['lon'];
}

if (!$lat || !$lon) {
    $lat = 24.8607;
    $lon = 67.0011;
    $city = 'Karachi';
}

$apiUrl = "https://api.open-meteo.com/v1/forecast?latitude={$lat}&longitude={$lon}&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,wind_speed_10m_max,wind_direction_10m_dominant&timezone=auto&forecast_days=14";
$apiData = @file_get_contents($apiUrl);
$apiResponse = $apiData ? json_decode($apiData, true) : null;

$weather = null;
if ($apiResponse && isset($apiResponse['daily'])) {
    $daily = $apiResponse['daily'];
    $weather = ['weekly' => []];
    
    $weatherCodes = [
        0 => ['condition' => 'Clear', 'icon' => 'sunny'],
        1 => ['condition' => 'Mostly Clear', 'icon' => 'sunny'],
        2 => ['condition' => 'Partly Cloudy', 'icon' => 'partly_cloudy'],
        3 => ['condition' => 'Overcast', 'icon' => 'cloudy'],
        45 => ['condition' => 'Foggy', 'icon' => 'fog'],
        48 => ['condition' => 'Foggy', 'icon' => 'fog'],
        51 => ['condition' => 'Light Drizzle', 'icon' => 'drizzle'],
        53 => ['condition' => 'Drizzle', 'icon' => 'drizzle'],
        55 => ['condition' => 'Heavy Drizzle', 'icon' => 'drizzle'],
        61 => ['condition' => 'Light Rain', 'icon' => 'rainy'],
        63 => ['condition' => 'Rain', 'icon' => 'rainy'],
        65 => ['condition' => 'Heavy Rain', 'icon' => 'rainy'],
        71 => ['condition' => 'Light Snow', 'icon' => 'snow'],
        73 => ['condition' => 'Snow', 'icon' => 'snow'],
        75 => ['condition' => 'Heavy Snow', 'icon' => 'snow'],
        80 => ['condition' => 'Rain Showers', 'icon' => 'rainy'],
        81 => ['condition' => 'Rain Showers', 'icon' => 'rainy'],
        82 => ['condition' => 'Heavy Showers', 'icon' => 'rainy'],
        95 => ['condition' => 'Thunderstorm', 'icon' => 'thunderstorm'],
        96 => ['condition' => 'Thunderstorm', 'icon' => 'thunderstorm'],
        99 => ['condition' => 'Severe Storm', 'icon' => 'thunderstorm']
    ];
    
    for ($i = 0; $i < count($daily['time']); $i++) {
        $code = $daily['weather_code'][$i] ?? 0;
        $weatherInfo = $weatherCodes[$code] ?? ['condition' => 'Unknown', 'icon' => 'cloudy'];
        
        $date = new DateTime($daily['time'][$i]);
        $weather['weekly'][] = [
            'day' => $date->format('D'),
            'date' => $date->format('M j'),
            'high' => round($daily['temperature_2m_max'][$i]),
            'low' => round($daily['temperature_2m_min'][$i]),
            'condition' => $weatherInfo['condition'],
            'icon' => $weatherInfo['icon'],
            'precipitation' => $daily['precipitation_probability_max'][$i] ?? 0,
            'wind_speed' => round($daily['wind_speed_10m_max'][$i] ?? 0),
            'wind_direction' => $daily['wind_direction_10m_dominant'][$i] ?? 0
        ];
    }
}

function getWeatherEmoji($condition) {
    $condition = strtolower($condition);
    $emojis = [
        'sunny' => '☀️',
        'clear' => '☀️',
        'clear_night' => '🌙',
        'partly_cloudy' => '⛅',
        'partly_cloudy_night' => '☁️',
        'cloudy' => '☁️',
        'overcast' => '☁️',
        'rainy' => '🌧️',
        'rain' => '🌧️',
        'drizzle' => '🌦️',
        'thunderstorm' => '⛈️',
        'snow' => '❄️',
        'snowy' => '❄️',
        'fog' => '🌫️',
        'foggy' => '🌫️',
        'mist' => '🌫️',
        'windy' => '💨',
        'sunrise' => '🌅',
        'sunset' => '🌇'
    ];
    return $emojis[$condition] ?? '🌡️';
}

function getTempClass($temp) {
    if ($temp <= 0) return 'temp-freezing';
    if ($temp <= 10) return 'temp-cold';
    if ($temp <= 18) return 'temp-cool';
    if ($temp <= 25) return 'temp-mild';
    if ($temp <= 32) return 'temp-warm';
    if ($temp <= 40) return 'temp-hot';
    return 'temp-very-hot';
}

include 'header.php';
?>

<main class="container">
    <section class="page-hero" style="background: linear-gradient(135deg, #4a90d9 0%, #667eea 50%, #764ba2 100%); padding: 3rem 2rem; border-radius: 1rem; margin-bottom: 2rem; text-align: center; color: white;">
        <h1 style="font-size: 2rem; margin-bottom: 0.5rem;">Extended Forecast</h1>
        <p style="opacity: 0.9; font-size: 1.1rem;">7-Day and 14-Day Weather Outlook for <?php echo htmlspecialchars($city); ?></p>
    </section>

    <div class="city-selector" style="background: var(--card-bg); padding: 1.5rem; border-radius: 1rem; margin-bottom: 2rem; display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;">
        <label style="font-weight: 600; color: var(--text-color);">Select City:</label>
        <select id="citySelect" onchange="changeCity(this.value)" style="padding: 0.75rem 1rem; border: 1px solid var(--border-color); border-radius: 0.5rem; background: var(--bg-color); color: var(--text-color); font-size: 1rem; min-width: 200px;">
            <?php foreach ($cities as $c): ?>
            <option value="<?php echo htmlspecialchars($c['name']); ?>" <?php echo strtolower($c['name']) === strtolower($city) ? 'selected' : ''; ?>>
                <?php echo htmlspecialchars($c['name']); ?>, <?php echo htmlspecialchars($c['country']); ?>
            </option>
            <?php endforeach; ?>
        </select>
    </div>

    <?php if ($weather && isset($weather['weekly'])): ?>
    <section class="forecast-section" id="extended-forecast" style="margin-bottom: 2rem;">
        <div class="forecast-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; flex-wrap: wrap; gap: 1rem;">
            <h2 class="section-title" style="display: flex; align-items: center; gap: 0.5rem; margin: 0;">
                <span class="icon">📅</span>
                <span data-translate="extendedForecast">Extended Forecast</span>
            </h2>
            <div class="forecast-toggle" style="display: flex; gap: 0.5rem;">
                <button class="forecast-btn active" data-days="7" onclick="toggleForecastDays(7)" style="padding: 0.5rem 1rem; background: var(--primary-color); color: white; border: none; border-radius: 0.5rem; cursor: pointer; font-weight: 500;">7 Days</button>
                <button class="forecast-btn" data-days="14" onclick="toggleForecastDays(14)" style="padding: 0.5rem 1rem; background: var(--card-bg); color: var(--text-color); border: 1px solid var(--border-color); border-radius: 0.5rem; cursor: pointer; font-weight: 500;">14 Days</button>
            </div>
        </div>
        <div class="weekly-forecast" id="weeklyForecast">
            <?php 
            $allTemps = array_merge(
                array_column($weather['weekly'], 'high'),
                array_column($weather['weekly'], 'low')
            );
            $minTemp = min($allTemps);
            $maxTemp = max($allTemps);
            $tempRange = $maxTemp - $minTemp ?: 1;
            ?>
            <?php foreach ($weather['weekly'] as $index => $day): 
                $barStart = (($day['low'] - $minTemp) / $tempRange) * 100;
                $barWidth = (($day['high'] - $day['low']) / $tempRange) * 100;
                $windDir = isset($day['wind_direction']) ? $day['wind_direction'] : 0;
                $windSpeed = isset($day['wind_speed']) ? $day['wind_speed'] : 0;
                $precip = isset($day['precipitation']) ? $day['precipitation'] : 0;
                $tempClass = getTempClass($day['high']);
            ?>
            <div class="weekly-item <?php echo $tempClass; ?>" data-index="<?php echo $index; ?>" <?php echo $index >= 7 ? 'style="display:none;"' : ''; ?>>
                <div class="weekly-day"><?php echo $day['day']; ?></div>
                <div class="weekly-date" style="font-size: 0.75rem; color: var(--text-muted);"><?php echo isset($day['date']) ? $day['date'] : ''; ?></div>
                <div class="weekly-icon animated-<?php echo $day['icon']; ?>"><?php echo getWeatherEmoji($day['icon']); ?></div>
                <div class="weekly-condition"><?php echo $day['condition']; ?></div>
                <div class="weekly-temp-bar">
                    <span class="temp-low"><?php echo $day['low']; ?>&deg;</span>
                    <div class="temp-bar-track">
                        <div class="temp-bar-fill" style="left: <?php echo $barStart; ?>%; width: <?php echo $barWidth; ?>%;"></div>
                    </div>
                    <span class="temp-high"><?php echo $day['high']; ?>&deg;</span>
                </div>
                <div class="weekly-details">
                    <div class="weekly-precip">
                        <span class="precip-icon">💧</span>
                        <span class="precip-value"><?php echo $precip; ?>%</span>
                    </div>
                    <div class="weekly-wind">
                        <span class="wind-arrow" style="transform: rotate(<?php echo $windDir; ?>deg);">➤</span>
                        <span class="wind-speed"><?php echo $windSpeed; ?> km/h</span>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>
    <?php else: ?>
    <div class="error-message" style="text-align: center; padding: 3rem; background: var(--card-bg); border-radius: 1rem;">
        <p style="font-size: 1.2rem; color: var(--text-muted);">Unable to load forecast data. Please try again later.</p>
    </div>
    <?php endif; ?>

    <div class="forecast-info" style="background: var(--card-bg); padding: 2rem; border-radius: 1rem; margin-top: 2rem;">
        <h3 style="margin-bottom: 1rem; color: var(--text-color);">About Extended Forecasts</h3>
        <p style="color: var(--text-muted); line-height: 1.6;">
            Our extended weather forecasts provide detailed predictions for up to 14 days. The 7-day forecast offers higher accuracy, 
            while the 14-day outlook gives you a general idea of upcoming weather patterns. Data includes temperature highs and lows, 
            precipitation probability, and wind conditions to help you plan ahead.
        </p>
    </div>
</main>

<script>
function toggleForecastDays(days) {
    const items = document.querySelectorAll('.weekly-item');
    const buttons = document.querySelectorAll('.forecast-btn');
    
    buttons.forEach(btn => {
        btn.classList.remove('active');
        btn.style.background = 'var(--card-bg)';
        btn.style.color = 'var(--text-color)';
        if (parseInt(btn.dataset.days) === days) {
            btn.classList.add('active');
            btn.style.background = 'var(--primary-color)';
            btn.style.color = 'white';
        }
    });
    
    items.forEach((item, index) => {
        if (index < days) {
            item.style.display = '';
        } else {
            item.style.display = 'none';
        }
    });
}

function changeCity(cityName) {
    window.location.href = '/forecast?city=' + encodeURIComponent(cityName);
}
</script>

<?php include 'footer.php'; ?>
