<?php
// Detect city from user input or IP
if (isset($_GET['city']) && trim($_GET['city']) !== "") {
    $city = trim($_GET['city']);
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
    $geoip = @json_decode(file_get_contents("http://ip-api.com/json/{$ip}"), true);
    $city = ($geoip && isset($geoip['city']) && $geoip['city'] != "") ? $geoip['city'] : "Greensboro";
}

// Convert city to coordinates
$geo_url = "https://geocoding-api.open-meteo.com/v1/search?name=" . urlencode($city) . "&count=1";
$geo_data = json_decode(@file_get_contents($geo_url), true);
if (!isset($geo_data["results"][0])) {
    $lat = 36.07; $lon = -79.79; $city = "Greensboro (fallback)";
} else {
    $lat = $geo_data["results"][0]["latitude"];
    $lon = $geo_data["results"][0]["longitude"];
    $city = $geo_data["results"][0]["name"];
}

// Weather API call
$url = "https://api.open-meteo.com/v1/forecast?"
    . "latitude=$lat&longitude=$lon"
    . "&daily=weathercode,temperature_2m_max,temperature_2m_min,precipitation_probability_max,windspeed_10m_max"
    . "&temperature_unit=fahrenheit"
    . "&windspeed_unit=mph"
    . "&timezone=auto"
    . "&forecast_days=10";

$data = json_decode(@file_get_contents($url), true);
if (!$data || !isset($data["daily"])) die("Weather data not available.");

$days = $data["daily"]["time"];
$highs = $data["daily"]["temperature_2m_max"];
$lows = $data["daily"]["temperature_2m_min"];
$codes = $data["daily"]["weathercode"];
$rainProb = $data["daily"]["precipitation_probability_max"];
$windMax = $data["daily"]["windspeed_10m_max"];

// Weather decoder with emoji/icon and type
function decodeWeather($code) {
    $map = [
        0 => ["Clear sky","☀️","sunny"],
        1 => ["Mostly clear","🌤","sunny"],
        2 => ["Partly cloudy","⛅","cloudy"],
        3 => ["Overcast","☁️","cloudy"],
        45 => ["Fog","🌫","cloudy"],
        48 => ["Rime fog","🌫","cloudy"],
        51 => ["Light drizzle","🌦","rain"],
        53 => ["Moderate drizzle","🌦","rain"],
        55 => ["Heavy drizzle","🌦","rain"],
        56 => ["Freezing drizzle","🌧","snow"],
        57 => ["Freezing heavy drizzle","🌧","snow"],
        61 => ["Light rain","🌧","rain"],
        63 => ["Moderate rain","🌧","rain"],
        65 => ["Heavy rain","🌧","rain"],
        71 => ["Light snow","❄️","snow"],
        73 => ["Moderate snow","❄️","snow"],
        75 => ["Heavy snow","❄️","snow"],
        80 => ["Rain showers","🌦","rain"],
        81 => ["Moderate showers","🌧","rain"],
        82 => ["Heavy showers","⛈","rain"],
        95 => ["Thunderstorm","⛈","thunder"],
        96 => ["Thunderstorm + light hail","⛈","thunder"],
        99 => ["Thunderstorm + heavy hail","⛈","thunder"]
    ];
    return $map[$code] ?? ["Unknown","❓","unknown"];
}

// Get day name from date
function dayName($date) { return date('l', strtotime($date)); }
// Card background color by type
function cardColor($type) {
    $colors = [
        "sunny" => "#FFF9C4",
        "cloudy" => "#ECEFF1",
        "rain" => "#B3E5FC",
        "thunder" => "#90CAF9",
        "snow" => "#E0E0E0",
        "unknown" => "#F8BBD0"
    ];
    return $colors[$type] ?? "#FFFFFF";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>10-Day Weather Forecast</title>
<style>
* { box-sizing: border-box; }
body {
    font-family: 'Segoe UI', Arial, sans-serif;
    font-size: 28px;
    line-height: 1.8;
    margin: 0 auto;
    padding: 20px;
    max-width: 700px;
    width: 100%;
    background: linear-gradient(to bottom, #e0f7fa, #ffffff);
    color: #333;
    overflow-x: hidden;
}
h2 { text-align: center; color: #00796b; font-size: 44px; margin-bottom: 25px; text-shadow: 1px 1px 2px rgba(0,0,0,0.2); }
form { text-align: center; margin-bottom: 30px; }
input[type=text] {
    padding: 16px; width: 100%; max-width: 400px; font-size: 24px;
    border: 2px solid #00796b; border-radius: 10px; outline: none;
}
input[type=text]:focus { border-color: #004d40; box-shadow: 0 0 5px rgba(0,121,107,0.5); }
input[type=submit] {
    padding: 16px 28px; font-size: 24px; margin-left: 10px;
    background-color: #00796b; color: white; border: none; border-radius: 10px; cursor: pointer;
}
input[type=submit]:hover { background-color: #004d40; }

.day {
    border-radius: 16px; padding: 25px; margin-bottom: 20px;
    font-size: 24px; display: flex; align-items: center;
}
.day-icon { font-size: 60px; margin-right: 25px; flex-shrink: 0; }
.day-info { font-size: 20px; }
.day-info strong { font-size: 28px; color: #004d40; display: block; margin-bottom: 10px; }
.forecast-detail { margin-top: 6px; }
.rain { color: #0288d1; font-weight: bold; }
.wind { color: #f57c00; font-weight: bold; }

@media (max-width: 480px) {
    body { font-size: 22px; padding: 12px; width: 95%; }
    input[type=text] { font-size: 20px; }
    input[type=submit] { font-size: 20px; margin-left: 0; margin-top: 10px; display: block; width: 70%; }
    .day { flex-direction: column; align-items: flex-start; }
    .day-icon { margin-bottom: 10px; }
}
</style>
</head>
<body><center><br>
<a href="./">Back To Main Page!</a></center>

<h2>10-Day Weather Forecast</h2>

<form method="GET" action="">
<input type="text" name="city" placeholder="Enter city" value="<?php echo htmlspecialchars($city); ?>">
<input type="submit" value="Go">
</form>

<h3 style="text-align:center;">Forecast for <?php echo htmlspecialchars($city); ?></h3>

<?php
$forecastDays = min(10, count($days));
for ($i=0; $i<$forecastDays; $i++) {
    list($conditionName, $icon, $type) = decodeWeather($codes[$i]);
    $bg = cardColor($type);
    $dayText = dayName($days[$i]) . ", " . $days[$i];
    echo "<div class='day' style='background-color: {$bg};'>
            <div class='day-icon'>{$icon}</div>
            <div class='day-info'>
                <strong>{$dayText} - {$conditionName}</strong>
                <div class='forecast-detail'>High: {$highs[$i]}°F | Low: {$lows[$i]}°F</div>
                <div class='forecast-detail rain'>🌧 Rain Chance: {$rainProb[$i]}%</div>
                <div class='forecast-detail wind'>💨 Max Wind: {$windMax[$i]} mph</div>
            </div>
          </div>";
}
?>

</body>
</html>
