@extends('admin.layouts.app')

@section('title', 'نقشه آنلاین رانندگان')

@section('content')
@include('admin.partials.iran-plate', ['loadStylesOnly' => true])
<div class="card">
    <div class="card-header">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h5 class="mb-0">ردیابی آنلاین رانندگان</h5>
            </div>
            <div class="col-md-6">
                <div class="d-flex justify-content-end gap-2">
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" id="showOnline" checked onchange="filterDrivers()">
                        <label class="form-check-label" for="showOnline">
                            <span class="badge bg-success">آنلاین ({{ $onlineCount ?? 0 }})</span>
                        </label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" id="showBusy" checked onchange="filterDrivers()">
                        <label class="form-check-label" for="showBusy">
                            <span class="badge bg-warning">مشغول ({{ $busyCount ?? 0 }})</span>
                        </label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" id="showOffline" onchange="filterDrivers()">
                        <label class="form-check-label" for="showOffline">
                            <span class="badge bg-secondary">آفلاین ({{ $offlineCount ?? 0 }})</span>
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card-body p-0">
        <div id="driversMap" style="height: 600px; width: 100%;"></div>
    </div>

    <div class="card-footer">
        <div class="row">
            <div class="col-md-6">
                <small class="text-muted" id="connectionStatus">
                    <i class="fas fa-sync-alt me-1"></i>
                    <span id="statusText">در حال اتصال...</span>
                </small>
            </div>
            <div class="col-md-6 text-end">
                <button class="btn btn-sm btn-primary" onclick="refreshMap()">
                    <i class="fas fa-redo me-1"></i>
                    به‌روزرسانی دستی
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Driver Details Modal -->
<div class="modal fade" id="driverModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">جزئیات راننده</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="driverDetails">
                <div class="text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">در حال بارگذاری...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .driver-marker {
        background: transparent;
        border: none;
    }

    .driver-icon {
        position: relative;
        width: 40px;
        height: 40px;
    }

    .driver-icon-pulse {
        position: absolute;
        width: 100%;
        height: 100%;
        border-radius: 50%;
        animation: pulse 2s ease-out infinite;
    }

    .driver-icon-pulse.online {
        background: rgba(34, 197, 94, 0.4);
    }

    .driver-icon-pulse.busy {
        background: rgba(251, 191, 36, 0.4);
    }

    .driver-icon-pulse.offline {
        background: rgba(107, 114, 128, 0.4);
    }

    @keyframes pulse {
        0% {
            transform: scale(1);
            opacity: 1;
        }
        100% {
            transform: scale(2);
            opacity: 0;
        }
    }

    .leaflet-popup-content {
        min-width: 200px;
    }
</style>
@endpush

@push('scripts')
<script src="{{ asset('assets/vendor/pusher/pusher.min.js') }}"></script>
<script>
    let map;
    let markers = {};
    let refreshInterval;
    let pusher;
    let channel;

    const driversData = {!! json_encode($drivers ?? []) !!};

    // Initialize map
    function initMap() {
        // Default center (Tehran)
        const centerLat = {{ $centerLat ?? 35.6892 }};
        const centerLng = {{ $centerLng ?? 51.3890 }};

        const neshanApiKey = @json($neshanMapApiKey);

        map = new L.Map('driversMap', {
            key: neshanApiKey,
            maptype: 'neshan',
            poi: false,
            traffic: false,
            center: [centerLat, centerLng],
            zoom: 12,
        });

        // Add drivers to map
        driversData.forEach(driver => {
            addDriverMarker(driver);
        });

        // Fit bounds if we have drivers
        if (driversData.length > 0) {
            const bounds = driversData
                .filter(d => d.latitude && d.longitude)
                .map(d => [d.latitude, d.longitude]);

            if (bounds.length > 0) {
                map.fitBounds(bounds, { padding: [50, 50] });
            }
        }
    }

    // Add driver marker to map
    function addDriverMarker(driver) {
        if (!driver.latitude || !driver.longitude) return;

        const statusClass = driver.driver_status || 'offline';
        const statusColor = {
            'online': '#22c55e',
            'busy': '#fbbf24',
            'offline': '#6b7280'
        }[statusClass];

        const icon = L.divIcon({
            html: `
                <div class="driver-icon">
                    <div class="driver-icon-pulse ${statusClass}"></div>
                    <div style="
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                        background: ${statusColor};
                        color: white;
                        width: 30px;
                        height: 30px;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border: 2px solid white;
                        box-shadow: 0 2px 6px rgba(0,0,0,0.3);
                    ">
                        <i class="fas fa-truck"></i>
                    </div>
                </div>
            `,
            iconSize: [40, 40],
            className: 'driver-marker'
        });

        const marker = L.marker([driver.latitude, driver.longitude], { icon: icon })
            .bindPopup(createPopupContent(driver))
            .addTo(map);

        marker.on('click', () => {
            showDriverDetails(driver.id);
        });

        markers[driver.id] = {
            marker: marker,
            driver: driver
        };
    }

    // Create popup content
    function createPopupContent(driver) {
        const statusBadge = {
            'online': '<span class="badge bg-success">آنلاین</span>',
            'busy': '<span class="badge bg-warning">مشغول</span>',
            'offline': '<span class="badge bg-secondary">آفلاین</span>'
        }[driver.driver_status] || '<span class="badge bg-secondary">نامشخص</span>';

        const plateHtml = createIranPlateHtml(driver.vehicle_plate);

        return `
            <div class="p-2">
                <div class="d-flex align-items-center mb-2">
                    <div class="rounded-circle bg-success text-white d-flex align-items-center justify-content-center me-2" style="width: 40px; height: 40px;">
                        ${driver.name.charAt(0)}
                    </div>
                    <div>
                        <strong>${driver.name}</strong><br>
                        ${statusBadge}
                    </div>
                </div>
                <div class="mb-2">
                    <i class="fas fa-phone text-muted me-1"></i>
                    <span class="font-monospace">${driver.phone}</span>
                </div>
                ${driver.vehicle_plate ? `
                    <div class="mb-2">
                        <i class="fas fa-car text-muted me-1"></i>
                        <div class="mt-2">${plateHtml}</div>
                    </div>
                ` : ''}
                <button class="btn btn-sm btn-primary w-100 mt-2" onclick="showDriverDetails(${driver.id})">
                    <i class="fas fa-info-circle me-1"></i>
                    جزئیات بیشتر
                </button>
            </div>
        `;
    }

    // Show driver details in modal
    function showDriverDetails(driverId) {
        const modal = new bootstrap.Modal(document.getElementById('driverModal'));
        modal.show();

        // Load driver details via AJAX
        $.ajax({
            url: '{{ url('/admin/drivers') }}/' + driverId + '/details',
            method: 'GET',
            success: function(response) {
                $('#driverDetails').html(response);
            },
            error: function() {
                $('#driverDetails').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        خطا در بارگذاری راننده
                    </div>
                `);
            }
        });
    }

    function createIranPlateHtml(plate) {
        if (!plate) return '<span class="text-muted">-</span>';
        const digitsMap = {'0':'۰','1':'۱','2':'۲','3':'۳','4':'۴','5':'۵','6':'۶','7':'۷','8':'۸','9':'۹'};
        const toFaDigits = (value) => String(value).replace(/[0-9]/g, (match) => digitsMap[match]);
        let clean = String(plate).replace(/[\s\u200c\u200f-]+/g, '').replace(/ایران/g, '');
        const match = clean.match(/^(\d{2})([\u0600-\u06FFA-Za-z])(\d{3})(\d{2})$/u);
        if (!match) {
            return `<span class="iran-plate-fallback">${plate}</span>`;
        }
        return `
            <div class="iran-plate iran-plate-sm">
                <div class="plate-right">${toFaDigits(match[1])}</div>
                <div class="plate-letter">${match[2]}</div>
                <div class="plate-middle">${toFaDigits(match[3])}</div>
                <div class="plate-iran-section">
                    <div class="plate-iran-flag">
                        <span class="flag-stripe flag-green"></span>
                        <span class="flag-stripe flag-white"></span>
                        <span class="flag-stripe flag-red"></span>
                    </div>
                    <div class="plate-iran-text">ایران</div>
                    <div class="plate-iran-code">${toFaDigits(match[4])}</div>
                </div>
            </div>
        `;
    }

    // Filter drivers based on status
    function filterDrivers() {
        const showOnline = document.getElementById('showOnline').checked;
        const showBusy = document.getElementById('showBusy').checked;
        const showOffline = document.getElementById('showOffline').checked;

        Object.values(markers).forEach(({ marker, driver }) => {
            const status = driver.driver_status;
            let show = false;

            if (status === 'online' && showOnline) show = true;
            if (status === 'busy' && showBusy) show = true;
            if (status === 'offline' && showOffline) show = true;

            if (show) {
                map.addLayer(marker);
            } else {
                map.removeLayer(marker);
            }
        });
    }

    // Refresh map with latest driver positions
    function refreshMap() {
        showLoading();

        $.ajax({
            url: '{{ route("admin.map.refresh") }}',
            method: 'GET',
            success: function(response) {
                // Remove old markers
                Object.values(markers).forEach(({ marker }) => {
                    map.removeLayer(marker);
                });
                markers = {};

                // Add updated markers
                const drivers = response.data || response.drivers || [];
                drivers.forEach(driver => {
                    addDriverMarker(driver);
                });

                filterDrivers();
                hideLoading();
                showToast('موقعیت رانندگان به‌روز شد', 'success');
            },
            error: function() {
                hideLoading();
                showToast('خطا در به‌روزرسانی موقعیت‌ها', 'error');
            }
        });
    }

    // Auto-refresh every 10 seconds
    function startAutoRefresh() {
        refreshInterval = setInterval(refreshMap, 10000);
    }

    function stopAutoRefresh() {
        if (refreshInterval) {
            clearInterval(refreshInterval);
        }
    }

    // Initialize WebSocket connection
    function initWebSocket() {
        // Enable pusher logging for debugging
        Pusher.logToConsole = {{ config('app.debug') ? 'true' : 'false' }};

        pusher = new Pusher('{{ config('broadcasting.connections.pusher.key') }}', {
            wsHost: '{{ config('broadcasting.connections.pusher.options.host') }}',
            wsPort: {{ config('broadcasting.connections.pusher.options.port') }},
            wssPort: {{ config('broadcasting.connections.pusher.options.port') }},
            forceTLS: {{ config('broadcasting.connections.pusher.options.scheme') === 'https' ? 'true' : 'false' }},
            encrypted: {{ config('broadcasting.connections.pusher.options.encrypted') ? 'true' : 'false' }},
            disableStats: true,
            enabledTransports: ['ws', 'wss'],
            cluster: '{{ config('broadcasting.connections.pusher.options.cluster') }}'
        });

        // Subscribe to driver locations channel
        channel = pusher.subscribe('driver-locations');

        // Listen for location updates
        channel.bind('location.updated', function(data) {
            console.log('Location update received:', data);
            updateDriverMarker(data);
        });

        // Connection state change handler
        pusher.connection.bind('state_change', function(states) {
            console.log('WebSocket state changed:', states.current);
            const statusText = document.getElementById('statusText');
            const connectionStatus = document.getElementById('connectionStatus');

            if (states.current === 'connected') {
                console.log('WebSocket connected successfully');
                statusText.innerHTML = '<i class="fas fa-circle text-success me-1"></i>به‌روزرسانی لحظه‌ای فعال';
                connectionStatus.className = 'text-success';
            } else if (states.current === 'connecting') {
                statusText.innerHTML = '<i class="fas fa-circle text-warning me-1"></i>در حال اتصال...';
                connectionStatus.className = 'text-warning';
            } else if (states.current === 'disconnected' || states.current === 'unavailable') {
                statusText.innerHTML = '<i class="fas fa-circle text-danger me-1"></i>اتصال قطع شد';
                connectionStatus.className = 'text-danger';
            }
        });

        // Error handler
        pusher.connection.bind('error', function(err) {
            console.error('WebSocket error:', err);
        });
    }

    // Update driver marker with real-time data
    function updateDriverMarker(data) {
        const driverId = data.driver_id;

        // If marker exists, update it
        if (markers[driverId]) {
            const { marker } = markers[driverId];

            // Update position
            const newLatLng = L.latLng(data.latitude, data.longitude);
            marker.setLatLng(newLatLng);

            // Update driver data
            const updatedDriver = {
                id: data.driver_id,
                name: data.driver_name,
                phone: data.driver_phone,
                latitude: data.latitude,
                longitude: data.longitude,
                speed: data.speed,
                heading: data.heading,
                driver_status: data.is_online ? 'online' : 'offline',
                last_update: data.last_update
            };

            markers[driverId].driver = updatedDriver;

            // Update popup content
            marker.setPopupContent(createPopupContent(updatedDriver));

            // Update marker icon if status changed
            updateMarkerIcon(marker, updatedDriver);

        } else if (data.is_online) {
            // Add new driver marker if online
            const newDriver = {
                id: data.driver_id,
                name: data.driver_name,
                phone: data.driver_phone,
                latitude: data.latitude,
                longitude: data.longitude,
                speed: data.speed,
                heading: data.heading,
                driver_status: 'online',
                last_update: data.last_update
            };
            addDriverMarker(newDriver);
        }

        // Apply current filters
        filterDrivers();
    }

    // Update marker icon based on driver status
    function updateMarkerIcon(marker, driver) {
        const statusClass = driver.driver_status || 'offline';
        const statusColor = {
            'online': '#22c55e',
            'busy': '#fbbf24',
            'offline': '#6b7280'
        }[statusClass];

        const icon = L.divIcon({
            html: `
                <div class="driver-icon">
                    <div class="driver-icon-pulse ${statusClass}"></div>
                    <div style="
                        position: absolute;
                        top: 50%;
                        left: 50%;
                        transform: translate(-50%, -50%);
                        background: ${statusColor};
                        color: white;
                        width: 30px;
                        height: 30px;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        border: 2px solid white;
                        box-shadow: 0 2px 6px rgba(0,0,0,0.3);
                    ">
                        <i class="fas fa-truck"></i>
                    </div>
                </div>
            `,
            iconSize: [40, 40],
            className: 'driver-marker'
        });

        marker.setIcon(icon);
    }

    // Initialize on page load
    $(document).ready(function() {
        initMap();
        initWebSocket();
        // Keep auto-refresh as fallback, but with longer interval
        refreshInterval = setInterval(refreshMap, 30000); // 30 seconds instead of 10
    });

    // Cleanup on page unload
    window.addEventListener('beforeunload', function() {
        if (refreshInterval) {
            clearInterval(refreshInterval);
        }
        if (pusher) {
            pusher.disconnect();
        }
    });
</script>
@endpush
