<?php
// Koneksi ke database
define('DB_HOST', 'localhost');
define('DB_USER', 'nanj9171_nanda');
define('DB_PASS', 'Clemira123');
define('DB_NAME', 'nanj9171_kanaka');

$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Inisialisasi pesan
$msg = '';

// --- PROSES TAMBAH LOKASI ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_location'])) {
    $name = $conn->real_escape_string($_POST['location-name']);
    $latitude = $conn->real_escape_string($_POST['latitude']);
    $longitude = $conn->real_escape_string($_POST['longitude']);
    $radius_km = $conn->real_escape_string($_POST['radius_km']);

    // Validasi sederhana
    if (!empty($name) && !empty($latitude) && !empty($longitude) && !empty($radius_km)) {
        $sql = "INSERT INTO locations (name, latitude, longitude, radius_km, status) VALUES ('$name', '$latitude', '$longitude', '$radius_km', 'active')";
        if ($conn->query($sql) === TRUE) {
            $msg = '<div class="alert alert-success">Lokasi berhasil ditambahkan.</div>';
        } else {
            $msg = '<div class="alert alert-danger">Gagal menambahkan lokasi: ' . $conn->error . '</div>';
        }
    } else {
        $msg = '<div class="alert alert-danger">Semua field harus diisi.</div>';
    }
}

// --- PROSES UPDATE STATUS LOKASI ---
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['status_toggle'])) {
    $id = (int)$_GET['status_toggle'];
    $current_status = $conn->real_escape_string($_GET['current_status']);
    $new_status = ($current_status == 'active') ? 'inactive' : 'active';

    $sql = "UPDATE locations SET status = '$new_status' WHERE id = $id";
    if ($conn->query($sql) === TRUE) {
        $msg = '<div class="alert alert-success">Status lokasi berhasil diperbarui.</div>';
    } else {
        $msg = '<div class="alert alert-danger">Gagal memperbarui status lokasi: ' . $conn->error . '</div>';
    }
}

// Ambil semua data lokasi dari tabel
$locations = [];
$result = $conn->query("SELECT * FROM locations");
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $locations[] = $row;
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Kelola Lokasi</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>
        body {
            padding-top: 20px;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-12">
            <?php echo $msg; ?>
        </div>
    </div>

    <div class="row">
        <div class="col-md-5">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong><span class="glyphicon glyphicon-plus"></span><span> Tambah Lokasi Baru</span></strong>
                </div>
                <div class="panel-body">
                    <form method="post" action="">
                        <div class="form-group">
                            <label for="location-name">Nama Lokasi</label>
                            <input type="text" class="form-control" name="location-name" required>
                        </div>
                        <div class="form-group">
                            <label>Koordinat Saat Ini</label>
                            <p><strong>Status:</strong> <span id="location-status">Mencari lokasi...</span></p>
                            <p><strong>Latitude:</strong> <span id="displayed-latitude"></span></p>
                            <p><strong>Longitude:</strong> <span id="displayed-longitude"></span></p>
                            <p><strong>Akurasi:</strong> <span id="accuracy-info"></span></p>
                            <input type="hidden" name="latitude" id="latitude-input" required>
                            <input type="hidden" name="longitude" id="longitude-input" required>
                        </div>
                        <div class="form-group">
                            <label for="radius_km">Radius (km)</label>
                            <input type="text" class="form-control" name="radius_km" required>
                        </div>
                        <button type="submit" name="add_location" class="btn btn-primary" id="add-btn" disabled>Tambah Lokasi</button>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-md-7">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong><span class="glyphicon glyphicon-map-marker"></span><span> Daftar Lokasi</span></strong>
                </div>
                <div class="panel-body">
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Nama Lokasi</th>
                                <th>Latitude</th>
                                <th>Longitude</th>
                                <th>Radius (km)</th>
                                <th>Status</th>
                                <th>Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($locations as $i => $location): ?>
                            <tr>
                                <td><?php echo $i + 1; ?></td>
                                <td><?php echo htmlspecialchars($location['name']); ?></td>
                                <td><?php echo htmlspecialchars($location['latitude']); ?></td>
                                <td><?php echo htmlspecialchars($location['longitude']); ?></td>
                                <td><?php echo htmlspecialchars($location['radius_km']); ?></td>
                                <td>
                                    <?php if ($location['status'] == 'active'): ?>
                                        <span class="label label-success">Aktif</span>
                                    <?php else: ?>
                                        <span class="label label-danger">Tidak Aktif</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <a href="?status_toggle=<?php echo (int)$location['id']; ?>&current_status=<?php echo htmlspecialchars($location['status']); ?>" class="btn btn-warning btn-xs" title="Ganti Status"><span class="glyphicon glyphicon-refresh"></span></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const latInput = document.getElementById('latitude-input');
    const lonInput = document.getElementById('longitude-input');
    const locationStatus = document.getElementById('location-status');
    const displayedLat = document.getElementById('displayed-latitude');
    const displayedLon = document.getElementById('displayed-longitude');
    const accuracyInfoEl = document.getElementById('accuracy-info');
    const addButton = document.getElementById('add-btn');

    function getGeoLocation() {
        if (navigator.geolocation) {
            locationStatus.textContent = 'Mencari lokasi...';
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    const lat = position.coords.latitude;
                    const lon = position.coords.longitude;
                    const accuracy = position.coords.accuracy;

                    accuracyInfoEl.textContent = `${accuracy.toFixed(2)} meter`;
                    displayedLat.textContent = lat;
                    displayedLon.textContent = lon;

                    locationStatus.textContent = 'Lokasi berhasil didapatkan.';
                    locationStatus.style.color = 'green';
                        
                    latInput.value = lat;
                    lonInput.value = lon;
                        
                    addButton.disabled = false;
                },
                (error) => {
                    let errorMessage = "Gagal mendapatkan lokasi.";
                    if (error.code === 1) {
                        errorMessage += " Pastikan Anda memberikan izin akses lokasi.";
                    } else if (error.code === 2) {
                        errorMessage += " Lokasi tidak dapat ditemukan.";
                    } else if (error.code === 3) {
                        errorMessage += " Permintaan lokasi timeout.";
                    }
                    locationStatus.textContent = errorMessage;
                    locationStatus.style.color = 'red';
                    addButton.disabled = true;
                },
                {
                    enableHighAccuracy: true,
                    timeout: 10000,
                    maximumAge: 0
                }
            );
        } else {
            locationStatus.textContent = "Geolocation tidak didukung oleh browser ini.";
            locationStatus.style.color = 'red';
            addButton.disabled = true;
        }
    }

    getGeoLocation();
});
</script>
</body>
</html>