@extends('layouts.dashboard')

@section('title', 'Active Visits Map')

@section('content')
<div class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">Active Visits Map</h1>
            <p class="text-gray-600 mt-1">Real-time tracking of all active field visits</p>
        </div>
        <div class="flex items-center space-x-3">
            <div id="lastUpdate" class="text-sm text-gray-600">
                Last update: <span id="updateTime">--:--:--</span>
            </div>
            <button onclick="refreshMap()" class="btn-secondary">
                <i class="fas fa-sync-alt mr-2"></i> Refresh
            </button>
        </div>
    </div>

    <!-- Stats Overview -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
        <div class="card-hover bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-600">
                    <i class="fas fa-user-md text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Active Employees</p>
                    <p id="activeEmployees" class="text-2xl font-bold text-gray-800">0</p>
                </div>
            </div>
        </div>

        <div class="card-hover bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-600">
                    <i class="fas fa-map-marker-alt text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Active Visits</p>
                    <p id="activeVisits" class="text-2xl font-bold text-gray-800">0</p>
                </div>
            </div>
        </div>

        <div class="card-hover bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-yellow-100 text-yellow-600">
                    <i class="fas fa-clock text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Avg. Duration</p>
                    <p id="avgDuration" class="text-2xl font-bold text-gray-800">0 min</p>
                </div>
            </div>
        </div>

        <div class="card-hover bg-white rounded-xl shadow-sm border border-gray-100 p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-purple-100 text-purple-600">
                    <i class="fas fa-ruler text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Coverage Area</p>
                    <p id="coverageArea" class="text-2xl font-bold text-gray-800">0 km²</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Map -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden mb-6">
        <div class="px-6 py-4 border-b border-gray-100 bg-gradient-to-r from-blue-50 to-indigo-100">
            <div class="flex items-center justify-between">
                <h2 class="text-lg font-semibold text-gray-800">Live Field Operations Map</h2>
                <div class="flex items-center space-x-2">
                    <button onclick="centerOnAll()" class="btn-secondary">
                        <i class="fas fa-globe mr-2"></i> View All
                    </button>
                    <button onclick="startAutoRefresh()" id="autoRefreshBtn" class="btn-primary">
                        <i class="fas fa-play-circle mr-2"></i> Auto-Refresh
                    </button>
                </div>
            </div>
        </div>
        <div class="p-4">
            <div id="activeVisitsMap" class="h-[600px] rounded-lg border border-gray-300"></div>
        </div>
    </div>

    <!-- Active Visits List -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-100">
            <h2 class="text-lg font-semibold text-gray-800">Active Visits Details</h2>
        </div>
        <div class="p-6">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Employee
                            </th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Client
                            </th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Location
                            </th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Status
                            </th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Duration
                            </th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Distance to Client
                            </th>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                                Actions
                            </th>
                        </tr>
                    </thead>
                    <tbody id="visitsList" class="bg-white divide-y divide-gray-200">
                        <!-- Will be populated by JavaScript -->
                    </tbody>
                </table>
            </div>
            <div id="noActiveVisits" class="text-center py-8 hidden">
                <i class="fas fa-map-marked-alt text-gray-300 text-4xl mb-3"></i>
                <p class="text-gray-500">No active visits at the moment</p>
            </div>
        </div>
    </div>
</div>

<!-- Leaflet JS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.5.3/dist/MarkerCluster.Default.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet.markercluster@1.5.3/dist/leaflet.markercluster.js"></script>

<script>
let map = null;
let markers = L.markerClusterGroup();
let markersData = {};
let autoRefreshInterval = null;

// Initialize map
function initMap() {
    map = L.map('activeVisitsMap').setView([30.0444, 31.2357], 10);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);
    
    map.addLayer(markers);
    
    // Load initial data
    loadActiveVisits();
}

// Load active visits
async function loadActiveVisits() {
    try {
        const response = await fetch('/gps/active-visits');
        const visits = await response.json();
        
        updateMapMarkers(visits);
        updateVisitsList(visits);
        updateStats(visits);
        updateTime();
        
    } catch (error) {
        console.error('Error loading active visits:', error);
    }
}

// Update map markers
function updateMapMarkers(visits) {
    markers.clearLayers();
    markersData = {};
    
    visits.forEach(visit => {
        if (visit.current_location && visit.current_location.latitude && visit.current_location.longitude) {
            const lat = visit.current_location.latitude;
            const lng = visit.current_location.longitude;
            
            const markerIcon = L.divIcon({
                html: `
                    <div class="relative">
                        <div class="w-10 h-10 bg-blue-600 rounded-full border-2 border-white shadow-lg flex items-center justify-center">
                            <i class="fas fa-user text-white"></i>
                        </div>
                        <div class="absolute -top-1 -right-1 w-6 h-6 bg-green-500 rounded-full border-2 border-white flex items-center justify-center">
                            <i class="fas fa-walking text-white text-xs"></i>
                        </div>
                    </div>
                `,
                className: 'employee-marker',
                iconSize: [40, 40],
                iconAnchor: [20, 20]
            });
            
            const marker = L.marker([lat, lng], { icon: markerIcon });
            
            const popupContent = `
                <div class="p-2">
                    <h3 class="font-bold text-lg mb-2">${visit.employee_name}</h3>
                    <div class="space-y-1">
                        <div class="flex items-center">
                            <i class="fas fa-handshake text-gray-400 w-4 mr-2"></i>
                            <span class="text-sm">Client: ${visit.client_name}</span>
                        </div>
                        <div class="flex items-center">
                            <i class="fas fa-clock text-gray-400 w-4 mr-2"></i>
                            <span class="text-sm">Started: ${visit.started_at}</span>
                        </div>
                        <div class="flex items-center">
                            <i class="fas fa-satellite text-gray-400 w-4 mr-2"></i>
                            <span class="text-sm">Last update: Just now</span>
                        </div>
                    </div>
                    <div class="mt-3">
                        <a href="/visits/${visit.id}/track" 
                           class="inline-block bg-blue-600 text-white px-3 py-1 rounded text-sm hover:bg-blue-700">
                            <i class="fas fa-map-marker-alt mr-1"></i> Track Live
                        </a>
                    </div>
                </div>
            `;
            
            marker.bindPopup(popupContent);
            markers.addLayer(marker);
            
            // Store marker data
            markersData[visit.id] = {
                marker: marker,
                data: visit
            };
        }
        
        // Add client location marker
        if (visit.client_location && visit.client_location.latitude && visit.client_location.longitude) {
            const clientIcon = L.divIcon({
                html: `
                    <div class="w-8 h-8 bg-green-500 rounded-full border-2 border-white shadow-lg flex items-center justify-center">
                        <i class="fas fa-handshake text-white"></i>
                    </div>
                `,
                className: 'client-marker',
                iconSize: [32, 32],
                iconAnchor: [16, 16]
            });
            
            const clientMarker = L.marker([
                visit.client_location.latitude, 
                visit.client_location.longitude
            ], { icon: clientIcon });
            
            clientMarker.bindPopup(`<b>${visit.client_name}</b><br>Client Location`);
            markers.addLayer(clientMarker);
        }
    });
    
    // Fit bounds to show all markers
    if (visits.length > 0 && markers.getLayers().length > 0) {
        map.fitBounds(markers.getBounds());
    }
}

// Update visits list
function updateVisitsList(visits) {
    const listContainer = document.getElementById('visitsList');
    const noVisitsMessage = document.getElementById('noActiveVisits');
    
    if (visits.length === 0) {
        listContainer.innerHTML = '';
        noVisitsMessage.classList.remove('hidden');
        return;
    }
    
    noVisitsMessage.classList.add('hidden');
    
    let html = '';
    
    visits.forEach(visit => {
        const duration = calculateDuration(visit.started_at);
        const distance = visit.current_location ? 
            calculateDistance(
                visit.current_location.latitude,
                visit.current_location.longitude,
                visit.client_location.latitude,
                visit.client_location.longitude
            ) : '--';
        
        html += `
            <tr class="hover:bg-gray-50">
                <td class="px-4 py-3 whitespace-nowrap">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 h-8 w-8">
                            <div class="h-8 w-8 rounded-full bg-gradient-to-r from-blue-400 to-blue-500 flex items-center justify-center">
                                <i class="fas fa-user text-white text-xs"></i>
                            </div>
                        </div>
                        <div class="ml-3">
                            <div class="text-sm font-medium text-gray-900">${visit.employee_name}</div>
                            <div class="text-xs text-gray-500">ID: ${visit.id}</div>
                        </div>
                    </div>
                </td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <div class="text-sm text-gray-900">${visit.client_name}</div>
                </td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <div class="text-sm text-gray-900">
                        ${visit.current_location ? '📍 Live' : 'No location'}
                    </div>
                </td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <span class="inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
                        <i class="fas fa-running mr-1"></i> In Progress
                    </span>
                </td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <div class="text-sm text-gray-900">${duration}</div>
                </td>
                <td class="px-4 py-3 whitespace-nowrap">
                    <div class="text-sm text-gray-900">${distance}m</div>
                </td>
                <td class="px-4 py-3 whitespace-nowrap text-sm font-medium">
                    <a href="/visits/${visit.id}/track" class="text-blue-600 hover:text-blue-900 mr-3">
                        <i class="fas fa-map-marker-alt"></i> Track
                    </a>
                    <a href="/visits/${visit.id}" class="text-green-600 hover:text-green-900">
                        <i class="fas fa-eye"></i> View
                    </a>
                </td>
            </tr>
        `;
    });
    
    listContainer.innerHTML = html;
}

// Update statistics
function updateStats(visits) {
    document.getElementById('activeEmployees').textContent = 
        new Set(visits.map(v => v.employee_name)).size;
    document.getElementById('activeVisits').textContent = visits.length;
    
    if (visits.length > 0) {
        // Calculate average duration
        const totalMinutes = visits.reduce((sum, visit) => {
            const duration = calculateDurationMinutes(visit.started_at);
            return sum + duration;
        }, 0);
        
        const avgMinutes = Math.round(totalMinutes / visits.length);
        document.getElementById('avgDuration').textContent = avgMinutes + ' min';
        
        // Calculate coverage area (simplified)
        if (visits.length >= 2) {
            const bounds = markers.getBounds();
            if (bounds) {
                const area = bounds.getNorthEast().distanceTo(bounds.getSouthWest()) / 1000;
                document.getElementById('coverageArea').textContent = Math.round(area) + ' km';
            }
        }
    } else {
        document.getElementById('avgDuration').textContent = '0 min';
        document.getElementById('coverageArea').textContent = '0 km';
    }
}

// Calculate duration from start time
function calculateDuration(startTime) {
    const start = new Date(`2000-01-01T${startTime}`);
    const now = new Date();
    now.setHours(parseInt(startTime.split(':')[0]));
    now.setMinutes(parseInt(startTime.split(':')[1]));
    
    const diffMs = now - start;
    const diffMins = Math.floor(diffMs / 60000);
    
    if (diffMins < 60) {
        return `${diffMins} min`;
    } else {
        const hours = Math.floor(diffMins / 60);
        const mins = diffMins % 60;
        return `${hours}h ${mins}m`;
    }
}

function calculateDurationMinutes(startTime) {
    const start = new Date(`2000-01-01T${startTime}`);
    const now = new Date();
    now.setHours(parseInt(startTime.split(':')[0]));
    now.setMinutes(parseInt(startTime.split(':')[1]));
    
    return Math.floor((now - start) / 60000);
}

// Calculate distance between two points
function calculateDistance(lat1, lon1, lat2, lon2) {
    const R = 6371; // Earth's radius in kilometers
    const dLat = (lat2 - lat1) * Math.PI / 180;
    const dLon = (lon2 - lon1) * Math.PI / 180;
    const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
        Math.sin(dLon/2) * Math.sin(dLon/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    const distanceKm = R * c;
    
    return Math.round(distanceKm * 1000); // Convert to meters
}

// Update time display
function updateTime() {
    const now = new Date();
    const timeString = now.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit', second:'2-digit'});
    document.getElementById('updateTime').textContent = timeString;
}

// Refresh map
function refreshMap() {
    loadActiveVisits();
}

// Center on all markers
function centerOnAll() {
    if (markers.getLayers().length > 0) {
        map.fitBounds(markers.getBounds());
    }
}

// Start auto-refresh
function startAutoRefresh() {
    const btn = document.getElementById('autoRefreshBtn');
    
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
        btn.innerHTML = '<i class="fas fa-play-circle mr-2"></i> Auto-Refresh';
        btn.className = 'btn-primary';
    } else {
        autoRefreshInterval = setInterval(loadActiveVisits, 10000); // Refresh every 10 seconds
        btn.innerHTML = '<i class="fas fa-stop-circle mr-2"></i> Stop Auto-Refresh';
        btn.className = 'btn-danger';
    }
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', function() {
    initMap();
    
    // Set up auto-refresh every 30 seconds
    autoRefreshInterval = setInterval(loadActiveVisits, 30000);
    
    // Update button state
    document.getElementById('autoRefreshBtn').innerHTML = '<i class="fas fa-stop-circle mr-2"></i> Stop Auto-Refresh';
    document.getElementById('autoRefreshBtn').className = 'btn-danger';
});
</script>

<style>
.employee-marker {
    animation: pulse 2s infinite;
}

.client-marker {
    animation: bounce 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.1); }
    100% { transform: scale(1); }
}

@keyframes bounce {
    0%, 100% { transform: translateY(0); }
    50% { transform: translateY(-5px); }
}
</style>
@endsection