<?php $__env->startSection('title', 'Lokasi Kantor & Geofencing'); ?>
<?php $__env->startSection('page-title', 'Lokasi Kantor & Radius Geofence'); ?>
<?php $__env->startSection('page-subtitle', 'Kelola koordinat titik pusat kantor resmi, radius meter presensi, dan toleransi akurasi GPS.'); ?>

<?php $__env->startPush('styles'); ?>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<style>
    .office-map {
        height: 180px;
        width: 100%;
        border-radius: 0.75rem;
        z-index: 1;
    }
    .modal-map-picker {
        height: 260px;
        width: 100%;
        border-radius: 0.75rem;
        z-index: 1;
    }
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="d-flex justify-content-between align-items-center mb-4">
    <a href="<?php echo e(route('admin.qr.index')); ?>" class="btn btn-outline-primary">
        <i class="bi bi-qr-code me-1"></i> Buka Layar QR Code Kantor
    </a>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalCreateLocation">
        <i class="bi bi-plus-lg me-1"></i> Tambah Lokasi Kantor
    </button>
</div>

<div class="row">
    <?php $__empty_1 = true; $__currentLoopData = $locations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $loc): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
        <div class="col-12 col-md-6 col-lg-4 mb-4">
            <div class="card shadow-sm border-0 h-100">
                <div class="card-header bg-white py-3 border-bottom d-flex justify-content-between align-items-center">
                    <h5 class="fw-bold mb-0 text-dark"><?php echo e($loc->name); ?></h5>
                    <?php if($loc->is_active): ?>
                        <span class="badge bg-success">Aktif</span>
                    <?php else: ?>
                        <span class="badge bg-secondary">Nonaktif</span>
                    <?php endif; ?>
                </div>
                <div class="card-body p-3 d-flex flex-column">
                    <p class="text-muted text-xs mb-2">
                        <i class="bi bi-geo-alt me-1 text-danger"></i> <?php echo e($loc->address ?? 'Alamat belum ditentukan'); ?>

                    </p>

                    <div id="map-<?php echo e($loc->id); ?>" class="office-map mb-3 shadow-sm border"></div>

                    <div class="bg-light p-3 rounded-3 mb-3">
                        <div class="row g-2 text-xs">
                            <div class="col-6"><span class="text-muted d-block">LATITUDE:</span><strong class="font-monospace"><?php echo e($loc->latitude); ?></strong></div>
                            <div class="col-6"><span class="text-muted d-block">LONGITUDE:</span><strong class="font-monospace"><?php echo e($loc->longitude); ?></strong></div>
                            <div class="col-6"><span class="text-muted d-block">RADIUS GEOFENCE:</span><span class="badge bg-primary"><?php echo e($loc->radius_meters); ?> Meter</span></div>
                            <div class="col-6"><span class="text-muted d-block">MAX AKURASI GPS:</span><span class="badge bg-secondary"><?php echo e($loc->max_gps_accuracy ?? 50); ?> Meter</span></div>
                        </div>
                    </div>

                    <div class="d-flex gap-2 mt-auto">
                        <button type="button" class="btn btn-outline-warning btn-sm w-100" data-bs-toggle="modal" data-bs-target="#modalEditLoc<?php echo e($loc->id); ?>" onclick="initEditMap('<?php echo e($loc->id); ?>', <?php echo e($loc->latitude); ?>, <?php echo e($loc->longitude); ?>, <?php echo e($loc->radius_meters); ?>)">
                            <i class="bi bi-pencil-square me-1"></i> Edit Lokasi
                        </button>
                        <button type="button" class="btn btn-outline-danger btn-sm" onclick="confirmDeleteLoc('<?php echo e($loc->id); ?>', '<?php echo e($loc->name); ?>')">
                            <i class="bi bi-trash"></i>
                        </button>
                        <form id="delete-loc-<?php echo e($loc->id); ?>" action="<?php echo e(route('admin.office-locations.destroy', $loc->id)); ?>" method="POST" class="d-none">
                            <?php echo csrf_field(); ?>
                            <?php echo method_field('DELETE'); ?>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        
        <div class="modal fade" id="modalEditLoc<?php echo e($loc->id); ?>" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog modal-lg modal-dialog-centered">
                <div class="modal-content border-0 shadow">
                    <div class="modal-header bg-warning text-dark">
                        <h5 class="modal-title"><i class="bi bi-pencil-square me-2"></i> Edit Lokasi: <?php echo e($loc->name); ?></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <form action="<?php echo e(route('admin.office-locations.update', $loc->id)); ?>" method="POST">
                        <?php echo csrf_field(); ?>
                        <?php echo method_field('PUT'); ?>
                        <div class="modal-body p-4">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label class="form-label fw-bold">Nama Kantor <span class="text-danger">*</span></label>
                                        <input type="text" name="name" class="form-control" value="<?php echo e($loc->name); ?>" required>
                                    </div>
                                    <div class="mb-3">
                                        <label class="form-label fw-bold">Alamat Lengkap</label>
                                        <textarea name="address" class="form-control" rows="2"><?php echo e($loc->address); ?></textarea>
                                    </div>
                                    <div class="row g-2 mb-3">
                                        <div class="col-6">
                                            <label class="form-label fw-bold">Latitude <span class="text-danger">*</span></label>
                                            <input type="text" name="latitude" id="lat-edit-<?php echo e($loc->id); ?>" class="form-control font-monospace" value="<?php echo e($loc->latitude); ?>" oninput="updatePinFromInputs('edit', '<?php echo e($loc->id); ?>')" required>
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label fw-bold">Longitude <span class="text-danger">*</span></label>
                                            <input type="text" name="longitude" id="lng-edit-<?php echo e($loc->id); ?>" class="form-control font-monospace" value="<?php echo e($loc->longitude); ?>" oninput="updatePinFromInputs('edit', '<?php echo e($loc->id); ?>')" required>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <button type="button" class="btn btn-sm btn-outline-primary w-100" onclick="getCurrentGPS('lat-edit-<?php echo e($loc->id); ?>', 'lng-edit-<?php echo e($loc->id); ?>', 'edit', '<?php echo e($loc->id); ?>')">
                                            <i class="bi bi-crosshair me-1"></i> Ambil Titik GPS Posisi Saya Saat Ini
                                        </button>
                                    </div>
                                    <div class="row g-2 mb-3">
                                        <div class="col-6">
                                            <label class="form-label fw-bold">Radius Absensi (m) <span class="text-danger">*</span></label>
                                            <input type="number" name="radius_meters" id="radius-edit-<?php echo e($loc->id); ?>" class="form-control" value="<?php echo e($loc->radius_meters); ?>" min="1" max="10000" oninput="updateCircleRadius('edit', '<?php echo e($loc->id); ?>')" required>
                                        </div>
                                        <div class="col-6">
                                            <label class="form-label fw-bold">Max Akurasi GPS (m) <span class="text-danger">*</span></label>
                                            <input type="number" name="max_gps_accuracy" class="form-control" value="<?php echo e($loc->max_gps_accuracy ?? 50); ?>" min="5" max="500" required>
                                        </div>
                                    </div>
                                    <div class="form-check form-switch">
                                        <input class="form-check-input" type="checkbox" name="is_active" value="1" id="locActive<?php echo e($loc->id); ?>" <?php echo e($loc->is_active ? 'checked' : ''); ?>>
                                        <label class="form-check-label fw-bold" for="locActive<?php echo e($loc->id); ?>">Lokasi Aktif untuk Absensi</label>
                                    </div>
                                </div>

                                
                                <div class="col-md-6">
                                    <label class="form-label fw-bold d-block"><i class="bi bi-pin-map-fill text-danger me-1"></i> Titik Peta (Geser Pin ke Lokasi Kantor):</label>
                                    <div id="map-picker-edit-<?php echo e($loc->id); ?>" class="modal-map-picker border shadow-sm mb-2"></div>
                                    <small class="text-muted text-xs d-block"><i class="bi bi-info-circle me-1"></i> Anda bisa <strong>menggeser pin merah</strong> atau <strong>mengklik langsung di peta</strong> untuk menentukan titik kantor dengan presisi.</small>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer bg-light">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                            <button type="submit" class="btn btn-warning"><i class="bi bi-save me-1"></i> Simpan Perubahan</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
        <div class="col-12">
            <div class="alert alert-info">Belum ada lokasi kantor yang terdaftar. Silakan klik tombol "Tambah Lokasi Kantor".</div>
        </div>
    <?php endif; ?>
</div>


<div class="modal fade" id="modalCreateLocation" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title text-white"><i class="bi bi-geo-alt-fill me-2"></i> Tambah Lokasi Kantor Baru</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form action="<?php echo e(route('admin.office-locations.store')); ?>" method="POST">
                <?php echo csrf_field(); ?>
                <div class="modal-body p-4">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label fw-bold">Nama Kantor <span class="text-danger">*</span></label>
                                <input type="text" name="name" class="form-control" placeholder="Contoh: Kantor Pusat Jakarta" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-bold">Alamat Lengkap</label>
                                <textarea name="address" class="form-control" rows="2" placeholder="Jl. ..."></textarea>
                            </div>
                            <div class="row g-2 mb-3">
                                <div class="col-6">
                                    <label class="form-label fw-bold">Latitude <span class="text-danger">*</span></label>
                                    <input type="text" name="latitude" id="lat-create" class="form-control font-monospace" value="-6.225588" oninput="updatePinFromInputs('create')" required>
                                </div>
                                <div class="col-6">
                                    <label class="form-label fw-bold">Longitude <span class="text-danger">*</span></label>
                                    <input type="text" name="longitude" id="lng-create" class="form-control font-monospace" value="106.808560" oninput="updatePinFromInputs('create')" required>
                                </div>
                            </div>
                            <div class="mb-3">
                                <button type="button" class="btn btn-sm btn-outline-primary w-100" onclick="getCurrentGPS('lat-create', 'lng-create', 'create')">
                                    <i class="bi bi-crosshair me-1"></i> Gunakan Koordinat GPS Saya Saat Ini
                                </button>
                            </div>
                            <div class="row g-2 mb-3">
                                <div class="col-6">
                                    <label class="form-label fw-bold">Radius Absensi (m) <span class="text-danger">*</span></label>
                                    <input type="number" name="radius_meters" id="radius-create" class="form-control" value="150" min="1" max="10000" oninput="updateCircleRadius('create')" required>
                                </div>
                                <div class="col-6">
                                    <label class="form-label fw-bold">Max Akurasi GPS (m) <span class="text-danger">*</span></label>
                                    <input type="number" name="max_gps_accuracy" class="form-control" value="50" min="5" max="500" required>
                                </div>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="is_active" value="1" id="createLocActive" checked>
                                <label class="form-check-label fw-bold" for="createLocActive">Aktif Digunakan untuk Absensi</label>
                            </div>
                        </div>

                        
                        <div class="col-md-6">
                            <label class="form-label fw-bold d-block"><i class="bi bi-pin-map-fill text-danger me-1"></i> Titik Peta (Geser Pin ke Lokasi Kantor):</label>
                            <div id="map-picker-create" class="modal-map-picker border shadow-sm mb-2"></div>
                            <small class="text-muted text-xs d-block"><i class="bi bi-info-circle me-1"></i> Anda bisa <strong>menggeser pin merah</strong> atau <strong>mengklik langsung di peta</strong> untuk menentukan titik kantor dengan presisi.</small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check2-circle me-1"></i> Simpan Lokasi</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
    const mapPickers = {};

    document.addEventListener('DOMContentLoaded', function() {
        // Init card overview maps
        <?php $__currentLoopData = $locations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $loc): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            try {
                const map<?php echo e($loc->id); ?> = L.map('map-<?php echo e($loc->id); ?>', {
                    center: [<?php echo e($loc->latitude); ?>, <?php echo e($loc->longitude); ?>],
                    zoom: 15,
                    zoomControl: false,
                    attributionControl: false
                });

                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map<?php echo e($loc->id); ?>);

                L.marker([<?php echo e($loc->latitude); ?>, <?php echo e($loc->longitude); ?>]).addTo(map<?php echo e($loc->id); ?>);

                L.circle([<?php echo e($loc->latitude); ?>, <?php echo e($loc->longitude); ?>], {
                    color: '#435ebe',
                    fillColor: '#435ebe',
                    fillOpacity: 0.2,
                    radius: <?php echo e($loc->radius_meters); ?>

                }).addTo(map<?php echo e($loc->id); ?>);
            } catch(e) {
                console.error(e);
            }
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

        // Initialize Create Modal Map when modal opens
        const createModal = document.getElementById('modalCreateLocation');
        if (createModal) {
            createModal.addEventListener('shown.bs.modal', function () {
                initCreateMap();
            });
        }
    });

    function initCreateMap() {
        if (mapPickers['create']) {
            mapPickers['create'].map.invalidateSize();
            return;
        }

        const lat = parseFloat(document.getElementById('lat-create').value) || -6.225588;
        const lng = parseFloat(document.getElementById('lng-create').value) || 106.808560;
        const rad = parseInt(document.getElementById('radius-create').value) || 150;

        const map = L.map('map-picker-create').setView([lat, lng], 16);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

        const marker = L.marker([lat, lng], { draggable: true }).addTo(map);
        const circle = L.circle([lat, lng], { color: '#435ebe', fillColor: '#435ebe', fillOpacity: 0.2, radius: rad }).addTo(map);

        marker.on('dragend', function(e) {
            const pos = e.target.getLatLng();
            document.getElementById('lat-create').value = pos.lat.toFixed(8);
            document.getElementById('lng-create').value = pos.lng.toFixed(8);
            circle.setLatLng(pos);
        });

        map.on('click', function(e) {
            marker.setLatLng(e.latlng);
            circle.setLatLng(e.latlng);
            document.getElementById('lat-create').value = e.latlng.lat.toFixed(8);
            document.getElementById('lng-create').value = e.latlng.lng.toFixed(8);
        });

        mapPickers['create'] = { map, marker, circle };
    }

    function initEditMap(id, defaultLat, defaultLng, defaultRad) {
        setTimeout(() => {
            const containerId = `map-picker-edit-${id}`;
            const container = document.getElementById(containerId);
            if (!container) return;

            if (mapPickers[id]) {
                mapPickers[id].map.invalidateSize();
                return;
            }

            const lat = parseFloat(document.getElementById(`lat-edit-${id}`).value) || defaultLat;
            const lng = parseFloat(document.getElementById(`lng-edit-${id}`).value) || defaultLng;
            const rad = parseInt(document.getElementById(`radius-edit-${id}`).value) || defaultRad;

            const map = L.map(containerId).setView([lat, lng], 16);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

            const marker = L.marker([lat, lng], { draggable: true }).addTo(map);
            const circle = L.circle([lat, lng], { color: '#e67e22', fillColor: '#e67e22', fillOpacity: 0.2, radius: rad }).addTo(map);

            marker.on('dragend', function(e) {
                const pos = e.target.getLatLng();
                document.getElementById(`lat-edit-${id}`).value = pos.lat.toFixed(8);
                document.getElementById(`lng-edit-${id}`).value = pos.lng.toFixed(8);
                circle.setLatLng(pos);
            });

            map.on('click', function(e) {
                marker.setLatLng(e.latlng);
                circle.setLatLng(e.latlng);
                document.getElementById(`lat-edit-${id}`).value = e.latlng.lat.toFixed(8);
                document.getElementById(`lng-edit-${id}`).value = e.latlng.lng.toFixed(8);
            });

            mapPickers[id] = { map, marker, circle };
        }, 300);
    }

    function updatePinFromInputs(type, id = null) {
        const key = type === 'create' ? 'create' : id;
        const latInput = type === 'create' ? document.getElementById('lat-create') : document.getElementById(`lat-edit-${id}`);
        const lngInput = type === 'create' ? document.getElementById('lng-create') : document.getElementById(`lng-edit-${id}`);

        const latVal = parseFloat(latInput.value.replace(',', '.').trim());
        const lngVal = parseFloat(lngInput.value.replace(',', '.').trim());

        if (!isNaN(latVal) && !isNaN(lngVal) && mapPickers[key]) {
            const pos = [latVal, lngVal];
            mapPickers[key].marker.setLatLng(pos);
            mapPickers[key].circle.setLatLng(pos);
            mapPickers[key].map.panTo(pos);
        }
    }

    function updateCircleRadius(type, id = null) {
        const key = type === 'create' ? 'create' : id;
        const radInput = type === 'create' ? document.getElementById('radius-create') : document.getElementById(`radius-edit-${id}`);
        const radVal = parseInt(radInput.value);

        if (!isNaN(radVal) && mapPickers[key]) {
            mapPickers[key].circle.setRadius(radVal);
        }
    }

    function getCurrentGPS(latInputId, lngInputId, type, id = null) {
        if (!navigator.geolocation) {
            Swal.fire('Error', 'Browser Anda tidak mendukung Geolocation GPS.', 'error');
            return;
        }

        Swal.fire({
            title: 'Mendeteksi GPS Akurat...',
            text: 'Mengambil titik koordinat hardware posisi Anda saat ini...',
            allowOutsideClick: false,
            didOpen: () => Swal.showLoading()
        });

        navigator.geolocation.getCurrentPosition(
            (pos) => {
                const lat = pos.coords.latitude.toFixed(8);
                const lng = pos.coords.longitude.toFixed(8);

                document.getElementById(latInputId).value = lat;
                document.getElementById(lngInputId).value = lng;

                updatePinFromInputs(type, id);

                Swal.fire({
                    icon: 'success',
                    title: 'GPS Berhasil Terdeteksi!',
                    html: `<b>Latitude:</b> ${lat}<br><b>Longitude:</b> ${lng}<br><b>Akurasi GPS:</b> ±${Math.round(pos.coords.accuracy)} meter`,
                    timer: 2500,
                    showConfirmButton: false
                });
            },
            (err) => {
                Swal.fire('Gagal Mendeteksi GPS', 'Pastikan izin lokasi browser aktif atau geser pin langsung pada peta di sebelah kanan.', 'error');
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 0 }
        );
    }

    function confirmDeleteLoc(id, name) {
        Swal.fire({
            title: 'Hapus Lokasi Kantor?',
            text: `Apakah Anda yakin ingin menghapus lokasi kantor "${name}"?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Ya, Hapus',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById(`delete-loc-${id}`).submit();
            }
        });
    }
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\absensi\resources\views/admin/office_locations/index.blade.php ENDPATH**/ ?>