<?php
$page_title = 'Kelola Lokasi';
require_once('includes/load.php');

// Hak akses level 4 atau lebih tinggi diperlukan
page_require_level(4);

// Ambil semua data lokasi dari tabel
$locations = find_all('locations');

// --- PROSES TAMBAH LOKASI ---
if (isset($_POST['add_location'])) {
    $req_fields = array('location-name', 'latitude', 'longitude', 'radius_km');
    validate_fields($req_fields);

    if (empty($errors)) {
        $name = remove_junk($db->escape($_POST['location-name']));
        $latitude = remove_junk($db->escape($_POST['latitude']));
        $longitude = remove_junk($db->escape($_POST['longitude']));
        $radius_km = remove_junk($db->escape($_POST['radius_km']));

        $sql = "INSERT INTO locations (name, latitude, longitude, radius_km, status) VALUES ('{$name}', '{$latitude}', '{$longitude}', '{$radius_km}', 'active')";
        if ($db->query($sql)) {
            $session->msg("s", "Lokasi berhasil ditambahkan.");
            redirect('locations.php', false);
        } else {
            $session->msg("d", "Gagal menambahkan lokasi.");
            redirect('locations.php', false);
        }
    } else {
        $session->msg("d", $errors);
        redirect('locations.php', false);
    }
}

// --- PROSES HAPUS LOKASI ---
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    if (delete_by_id('locations', $id)) {
        $session->msg("s", "Lokasi berhasil dihapus.");
    } else {
        $session->msg("d", "Gagal menghapus lokasi.");
    }
    redirect('locations.php', false);
}

// --- PROSES UPDATE STATUS LOKASI ---
if (isset($_GET['status_toggle'])) {
    $id = (int)$_GET['status_toggle'];
    $current_status = remove_junk($_GET['current_status']);
    $new_status = ($current_status == 'active') ? 'inactive' : 'active';

    $sql = "UPDATE locations SET status = '{$new_status}' WHERE id = '{$id}'";
    if ($db->query($sql)) {
        $session->msg("s", "Status lokasi berhasil diperbarui.");
    } else {
        $session->msg("d", "Gagal memperbarui status lokasi.");
    }
    redirect('locations.php', false);
}
?>

<?php include_once('layouts/header.php'); ?>
<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($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="locations.php">
                    <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 remove_junk($location['name']); ?></td>
                            <td><?php echo remove_junk($location['latitude']); ?></td>
                            <td><?php echo remove_junk($location['longitude']); ?></td>
                            <td><?php echo remove_junk($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="locations.php?status_toggle=<?php echo (int)$location['id']; ?>&current_status=<?php echo $location['status']; ?>" class="btn btn-warning btn-xs" title="Ganti Status"><span class="glyphicon glyphicon-refresh"></span></a>
                                <a href="locations.php?delete=<?php echo (int)$location['id']; ?>" class="btn btn-danger btn-xs" title="Hapus" onclick="return confirm('Apakah Anda yakin ingin menghapus lokasi ini?');"><span class="glyphicon glyphicon-trash"></span></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </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;

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

                    // Update status message
                    locationStatus.textContent = 'Lokasi berhasil didapatkan.';
                    locationStatus.style.color = 'green';
                        
                    // Fill hidden inputs
                    latInput.value = lat;
                    lonInput.value = lon;
                        
                    // Enable the button regardless of accuracy
                    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>

<?php include_once('layouts/footer.php'); ?>