<?php
$db_file = 'pollution_data.db';
$db = new SQLite3($db_file);

$selected_year = $_GET['year'] ?? '';
$selected_month = $_GET['month'] ?? '';
$selected_date = $_GET['date'] ?? '';

// Get unique years
$years_res = $db->query("SELECT DISTINCT strftime('%Y', \"DateTime\") as year FROM pollution ORDER BY year DESC");
$years = [];
while ($row = $years_res->fetchArray(SQLITE3_ASSOC)) {
    $years[] = $row['year'];
}

// Get unique months if year is selected
$months = [];
if ($selected_year) {
    $stmt_m = $db->prepare("SELECT DISTINCT strftime('%m', \"DateTime\") as month FROM pollution WHERE strftime('%Y', \"DateTime\") = :year ORDER BY month ASC");
    $stmt_m->bindValue(':year', $selected_year, SQLITE3_TEXT);
    $months_res = $stmt_m->execute();
    while ($row = $months_res->fetchArray(SQLITE3_ASSOC)) {
        $months[] = $row['month'];
    }
}

// Get dates based on filters
$date_query = "SELECT DISTINCT \"DateTime\" FROM pollution";
$params = [];
$where = [];

if ($selected_year) {
    $where[] = "strftime('%Y', \"DateTime\") = :year";
    $params[':year'] = $selected_year;
}
if ($selected_month) {
    $where[] = "strftime('%m', \"DateTime\") = :month";
    $params[':month'] = $selected_month;
}

if (!empty($where)) {
    $date_query .= " WHERE " . implode(" AND ", $where);
}
$date_query .= " ORDER BY \"DateTime\" DESC";

$stmt_d = $db->prepare($date_query);
foreach ($params as $key => $val) {
    $stmt_d->bindValue($key, $val, SQLITE3_TEXT);
}
$dates_result = $stmt_d->execute();
$dates = [];
while ($row = $dates_result->fetchArray(SQLITE3_ASSOC)) {
    $dates[] = $row['DateTime'];
}

$pollution_data = [];
if ($selected_date) {
    $stmt = $db->prepare("SELECT * FROM pollution WHERE \"DateTime\" = :date");
    $stmt->bindValue(':date', $selected_date, SQLITE3_TEXT);
    $res = $stmt->execute();
    $row = $res->fetchArray(SQLITE3_ASSOC);

    if ($row) {
        $geo_res = $db->query("SELECT location, lat, lon, daerah FROM geolocation");
        while ($geo = $geo_res->fetchArray(SQLITE3_ASSOC)) {
            $loc = $geo['location'];
            $val = $row[$loc] ?? null;
            $pollution_data[] = [
                'location' => $loc,
                'lat' => $geo['lat'],
                'lon' => $geo['lon'],
                'daerah' => $geo['daerah'],
                'value' => $val
            ];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Air Pollution Map</title>
    <link rel="manifest" href="manifest.json">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
    <style>
        #map { height: calc(100vh - 70px); }
        .filter-group { display: flex; gap: 10px; align-items: center; }
    </style>
</head>
<body>
    <div id="controls">
        <form method="GET" class="filter-group">
            <select name="year" onchange="this.form.submit()">
                <option value="">Year</option>
                <?php foreach ($years as $y): ?>
                    <option value="<?= $y ?>" <?= $selected_year === $y ? 'selected' : '' ?>><?= $y ?></option>
                <?php endforeach; ?>
            </select>
            <select name="month" onchange="this.form.submit()" <?= !$selected_year ? 'disabled' : '' ?>>
                <option value="">Month</option>
                <?php foreach ($months as $m): ?>
                    <option value="<?= $m ?>" <?= $selected_month === $m ? 'selected' : '' ?>><?= $m ?></option>
                <?php endforeach; ?>
            </select>
            <select name="date" onchange="this.form.submit()">
                <option value="">Date</option>
                <?php foreach ($dates as $d): ?>
                    <option value="<?= htmlspecialchars($d) ?>" <?= $selected_date === $d ? 'selected' : '' ?>>
                        <?= htmlspecialchars($d) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </form>
    </div>
    <div id="map"></div>

    <script>
        const map = L.map('map').setView([4.2105, 101.9758], 6);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors'
        }).addTo(map);

        function getColor(val) {
            if (val === null || val === '' || isNaN(parseFloat(val))) return '#808080';
            val = parseFloat(val);
            if (val <= 50) return '#00E400';
            if (val <= 90) return '#FFFF00';
            if (val <= 190) return '#FF7E00';
            if (val <= 300) return '#FF0000';
            return '#8F3F97';
        }

        function getLabel(val) {
            if (val === null || val === '' || isNaN(parseFloat(val))) return 'Not Available';
            val = parseFloat(val);
            if (val <= 50) return 'Good';
            if (val <= 90) return 'Moderate';
            if (val <= 190) return 'Unhealthy';
            if (val <= 300) return 'Very Unhealthy';
            return 'Hazardous';
        }

        const data = <?= json_encode($pollution_data) ?>;
        data.forEach(item => {
            if (item.lat && item.lon) {
                const color = getColor(item.value);
                const label = getLabel(item.value);
                const valText = (item.value !== null && item.value !== '') ? item.value : 'N/A';

                L.circle([item.lat, item.lon], {
                    color: color,
                    fillColor: color,
                    fillOpacity: 0.5,
                    radius: 15000
                }).addTo(map).bindPopup(`<b>${item.location}</b><br>Value: ${valText}<br>Status: ${label}<br>Daerah: ${item.daerah}`);
            }
        });
    </script>
    <script>
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('sw.js');
        }
    </script>
</body>
</html>
