<?php $__env->startSection('title', 'Geolocalización de Guardias - Ojo de Águila'); ?>
<?php $__env->startSection('header_title', 'Monitoreo de Guardias (GPS)'); ?>

<?php $__env->startSection('content'); ?>
<div class="dashboard-grid full-width-grid">
    <!-- Map Card -->
    <div class="card">
        <div class="card-header">
            <h3 class="card-title">🗺️ Mapa de Patrullaje en Tiempo Real</h3>
            <span class="badge badge-info" style="font-size: 11px;">Actualización: cada 10 segs</span>
        </div>
        <div class="card-body" style="padding: 0; position: relative;">
            <div id="tracking-map" class="map-container" style="height: 480px;"></div>
        </div>
    </div>
</div>

<!-- Bottom Section: Historial de Ubicaciones -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">📝 Historial de ubicaciones de hoy</h3>
    </div>
    <div class="table-responsive">
        <table class="table">
            <thead>
                <tr>
                    <th>Hora</th>
                    <th>Guardia</th>
                    <th>Latitud</th>
                    <th>Longitud</th>
                    <th>Precisión</th>
                </tr>
            </thead>
            <tbody>
                <?php $__empty_1 = true; $__currentLoopData = $locations; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $loc): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                    <tr>
                        <td style="font-weight: 600;">
                            <?php echo e($loc->recorded_at instanceof \Carbon\Carbon ? $loc->recorded_at->format('H:i:s A') : \Carbon\Carbon::parse($loc->recorded_at)->format('H:i:s A')); ?>

                        </td>
                        <td style="font-weight: 700; color: var(--text-primary);">
                            <?php echo e($loc->guardUser->name); ?>

                        </td>
                        <td style="font-family: monospace;"><?php echo e(number_format($loc->latitude, 6)); ?></td>
                        <td style="font-family: monospace;"><?php echo e(number_format($loc->longitude, 6)); ?></td>
                        <td>
                            <span class="badge <?php echo e($loc->accuracy <= 15 ? 'badge-success' : 'badge-warning'); ?>" style="font-size: 11px;">
                                ± <?php echo e(number_format($loc->accuracy, 1)); ?> metros
                            </span>
                        </td>
                    </tr>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                    <tr>
                        <td colspan="5" style="text-align: center; color: var(--text-light); padding: 40px;">
                            No se registran ubicaciones hoy todavía.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        // Inicializar mapa de Leaflet
        // Coordenadas fijas en Santiago de Chile
        var map = L.map('tracking-map').setView([-33.4489, -70.6693], 17);

        // Capa de OpenStreetMap
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            maxZoom: 19,
            attribution: '© OpenStreetMap'
        }).addTo(map);

        var guardMarkers = {};

        function updateGuardPositions() {
            fetch('/api/tracking/active-guards')
                .then(res => res.json())
                .then(response => {
                    if (response.success) {
                        const activeGuards = response.data;

                        activeGuards.forEach(function(guard) {
                            const name = guard.name;
                            const lat = guard.lat;
                            const lng = guard.lng;
                            const time = guard.time;

                            const popupContent = `
                                <b>👮 Guardia: ${name}</b><br>
                                📞 Teléfono: ${guard.phone ?? 'N/A'}<br>
                                ⏱️ Último reporte: ${time}<br>
                                🎯 Precisión GPS: ±${guard.accuracy}m
                            `;

                            if (guardMarkers[name]) {
                                // Mover marcador existente con transición suave
                                guardMarkers[name].setLatLng([lat, lng]);
                                guardMarkers[name].setPopupContent(popupContent);
                            } else {
                                // Crear nuevo marcador
                                // Crear icono de escudo azul personalizado para el guardia
                                var guardIcon = L.divIcon({
                                    html: '<div style="background-color: var(--accent-color); border: 2px solid white; border-radius: 50%; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; color: white; font-size: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.3);">👮</div>',
                                    className: 'custom-guard-icon',
                                    iconSize: [28, 28],
                                    iconAnchor: [14, 14]
                                });

                                guardMarkers[name] = L.marker([lat, lng], { icon: guardIcon })
                                    .addTo(map)
                                    .bindPopup(popupContent);
                            }
                        });
                    }
                })
                .catch(err => console.error('Error fetching GPS positions:', err));
        }

        // Consultar inmediatamente y luego cada 10 segundos
        updateGuardPositions();
        setInterval(updateGuardPositions, 10000);
    });
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH C:\xampp\htdocs\ojodeaguila\resources\views/tracking.blade.php ENDPATH**/ ?>