@extends('layouts.dashboard')

@section('title', 'Tracking Alerts')

@section('content')
<div class="container mx-auto px-4">
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">Tracking Alerts & Notifications</h1>
        <div class="flex space-x-3">
            <a href="{{ route('live-tracking.index') }}" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded flex items-center">
                <i class="fas fa-arrow-left mr-2"></i> Back to Dashboard
            </a>
            <button onclick="refreshAlerts()" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded flex items-center">
                <i class="fas fa-sync-alt mr-2"></i> Refresh
            </button>
        </div>
    </div>

    <!-- Alert Stats -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white shadow rounded-lg p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-red-100 text-red-600 mr-4">
                    <i class="fas fa-exclamation-triangle text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-600">Critical Alerts</p>
                    <h3 class="text-2xl font-bold">{{ $alerts->where('scheduled_end', '<', now())->count() }}</h3>
                </div>
            </div>
        </div>
        
        <div class="bg-white shadow rounded-lg p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-yellow-100 text-yellow-600 mr-4">
                    <i class="fas fa-clock text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-600">Overdue Visits</p>
                    <h3 class="text-2xl font-bold">{{ $alerts->where('scheduled_end', '<', now())->count() }}</h3>
                </div>
            </div>
        </div>
        
        <div class="bg-white shadow rounded-lg p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-blue-100 text-blue-600 mr-4">
                    <i class="fas fa-map-marker-slash text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-600">No Location Updates</p>
                    <h3 class="text-2xl font-bold">{{ $alerts->where('last_location_update', '<', now()->subMinutes(30))->count() }}</h3>
                </div>
            </div>
        </div>
        
        <div class="bg-white shadow rounded-lg p-6">
            <div class="flex items-center">
                <div class="p-3 rounded-full bg-green-100 text-green-600 mr-4">
                    <i class="fas fa-check-circle text-xl"></i>
                </div>
                <div>
                    <p class="text-sm text-gray-600">Resolved Today</p>
                    <h3 class="text-2xl font-bold">0</h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Alerts Table -->
    <div class="bg-white shadow-md rounded-lg overflow-hidden mb-6">
        <div class="px-6 py-4 border-b border-gray-200">
            <div class="flex justify-between items-center">
                <h2 class="text-lg font-semibold text-gray-800">Active Alerts</h2>
                <div class="flex space-x-2">
                    <select id="alertTypeFilter" class="border border-gray-300 rounded px-3 py-1 text-sm">
                        <option value="">All Alert Types</option>
                        <option value="overdue">Overdue</option>
                        <option value="no_location">No Location</option>
                        <option value="off_route">Off Route</option>
                    </select>
                    <select id="severityFilter" class="border border-gray-300 rounded px-3 py-1 text-sm">
                        <option value="">All Severities</option>
                        <option value="critical">Critical</option>
                        <option value="warning">Warning</option>
                        <option value="info">Info</option>
                    </select>
                </div>
            </div>
        </div>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Alert</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Employee & Client</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Details</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Severity</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Time</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200" id="alerts-table-body">
                    @php
                        $alertTypes = [
                            'overdue' => ['icon' => 'fa-clock', 'color' => 'text-red-600', 'bg' => 'bg-red-100'],
                            'no_location' => ['icon' => 'fa-map-marker-slash', 'color' => 'text-yellow-600', 'bg' => 'bg-yellow-100'],
                            'off_route' => ['icon' => 'fa-route', 'color' => 'text-orange-600', 'bg' => 'bg-orange-100'],
                        ];
                    @endphp
                    
                    @forelse($alerts as $visit)
                    @php
                        $isOverdue = $visit->scheduled_end && $visit->scheduled_end < now();
                        $noLocation = $visit->last_location_update && $visit->last_location_update < now()->subMinutes(30);
                        
                        if ($isOverdue) {
                            $type = 'overdue';
                            $severity = 'critical';
                            $message = 'Visit overdue by ' . $visit->scheduled_end->diffForHumans(null, true);
                        } elseif ($noLocation) {
                            $type = 'no_location';
                            $severity = 'warning';
                            $message = 'No location update for ' . $visit->last_location_update->diffForHumans(null, true);
                        } else {
                            $type = 'off_route';
                            $severity = 'info';
                            $message = 'Potential route deviation';
                        }
                    @endphp
                    <tr class="alert-row" data-type="{{ $type }}" data-severity="{{ $severity }}">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex items-center">
                                <div class="p-2 rounded-full {{ $alertTypes[$type]['bg'] }} {{ $alertTypes[$type]['color'] }} mr-3">
                                    <i class="fas {{ $alertTypes[$type]['icon'] }}"></i>
                                </div>
                                <div>
                                    <div class="text-sm font-medium text-gray-900">
                                        @if($type == 'overdue') Overdue Visit
                                        @elseif($type == 'no_location') No Location Update
                                        @else Route Deviation
                                        @endif
                                    </div>
                                    <div class="text-sm text-gray-500">{{ $message }}</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">{{ $visit->employee->name }}</div>
                            <div class="text-sm text-gray-500">
                                <i class="fas fa-building mr-1"></i> {{ $visit->client->name }}
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900">
                                @if($visit->current_address)
                                    <i class="fas fa-map-marker-alt mr-1"></i> {{ Str::limit($visit->current_address, 25) }}
                                @else
                                    <span class="text-gray-400">Location unknown</span>
                                @endif
                            </div>
                            <div class="text-xs text-gray-500 mt-1">
                                Scheduled: {{ $visit->scheduled_date->format('H:i') }}
                                @if($visit->scheduled_end)
                                    - {{ $visit->scheduled_end->format('H:i') }}
                                @endif
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            @if($severity == 'critical')
                                <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-red-100 text-red-800">
                                    <i class="fas fa-exclamation-circle mr-1"></i> Critical
                                </span>
                            @elseif($severity == 'warning')
                                <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">
                                    <i class="fas fa-exclamation-triangle mr-1"></i> Warning
                                </span>
                            @else
                                <span class="px-2 py-1 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800">
                                    <i class="fas fa-info-circle mr-1"></i> Info
                                </span>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            @if($type == 'overdue')
                                {{ $visit->scheduled_end->diffForHumans() }}
                            @elseif($type == 'no_location')
                                {{ $visit->last_location_update->diffForHumans() }}
                            @else
                                {{ $visit->updated_at->diffForHumans() }}
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex space-x-2">
                                <a href="{{ route('gps.track', $visit) }}" 
                                   class="text-blue-600 hover:text-blue-900"
                                   title="Track Live">
                                    <i class="fas fa-satellite"></i>
                                </a>
                                <button onclick="contactEmployee('{{ $visit->employee->phone }}')" 
                                        class="text-green-600 hover:text-green-900"
                                        title="Contact Employee">
                                    <i class="fas fa-phone"></i>
                                </button>
                                <button onclick="resolveAlert({{ $visit->id }})" 
                                        class="text-gray-600 hover:text-gray-900"
                                        title="Mark as Resolved">
                                    <i class="fas fa-check"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="px-6 py-8 text-center text-gray-500">
                            <i class="fas fa-bell-slash text-3xl mb-3"></i>
                            <p>No active alerts at the moment</p>
                            <p class="text-sm mt-2">Great! Everything is running smoothly.</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <!-- Alert History -->
    <div class="bg-white shadow-md rounded-lg overflow-hidden">
        <div class="px-6 py-4 border-b border-gray-200">
            <h2 class="text-lg font-semibold text-gray-800">Recent Resolved Alerts</h2>
        </div>
        <div class="p-6">
            <div class="text-center text-gray-500 py-8">
                <i class="fas fa-history text-3xl mb-3"></i>
                <p>No resolved alerts in the past 24 hours</p>
                <p class="text-sm mt-2">Resolved alerts will appear here for 24 hours</p>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const typeFilter = document.getElementById('alertTypeFilter');
    const severityFilter = document.getElementById('severityFilter');
    const alertRows = document.querySelectorAll('.alert-row');
    
    function filterAlerts() {
        const selectedType = typeFilter.value;
        const selectedSeverity = severityFilter.value;
        
        alertRows.forEach(row => {
            const type = row.getAttribute('data-type');
            const severity = row.getAttribute('data-severity');
            
            let matchesType = !selectedType || type === selectedType;
            let matchesSeverity = !selectedSeverity || severity === selectedSeverity;
            
            if (matchesType && matchesSeverity) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }
    
    typeFilter.addEventListener('change', filterAlerts);
    severityFilter.addEventListener('change', filterAlerts);
});

function contactEmployee(phoneNumber) {
    if (phoneNumber) {
        if (confirm(`Call employee at ${phoneNumber}?`)) {
            window.location.href = `tel:${phoneNumber}`;
        }
    } else {
        alert('Phone number not available');
    }
}

function resolveAlert(visitId) {
    if (confirm('Mark this alert as resolved?')) {
        // In a real application, you would send an API request here
        const row = document.querySelector(`tr[data-visit-id="${visitId}"]`);
        if (row) {
            row.style.opacity = '0.5';
            setTimeout(() => {
                row.remove();
                showAlert('Alert marked as resolved', 'success');
                updateAlertCounts();
            }, 500);
        }
    }
}

function refreshAlerts() {
    showLoading();
    // Simulate refresh
    setTimeout(() => {
        hideLoading();
        showAlert('Alerts refreshed', 'success');
        // In real app, fetch new data here
    }, 1000);
}

function updateAlertCounts() {
    // Update stats after resolving alerts
    const activeAlerts = document.querySelectorAll('.alert-row:not([style*="display: none"])').length;
    // Update UI elements as needed
}

function showLoading() {
    const spinner = document.getElementById('loading-spinner');
    if (spinner) spinner.classList.remove('hidden');
}

function hideLoading() {
    const spinner = document.getElementById('loading-spinner');
    if (spinner) spinner.classList.add('hidden');
}

function showAlert(message, type = 'success') {
    const alert = document.createElement('div');
    alert.className = `fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 ${
        type === 'success' ? 'bg-green-100 text-green-800 border border-green-200' : 
        'bg-red-100 text-red-800 border border-red-200'
    }`;
    alert.innerHTML = `
        <div class="flex items-center">
            <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'} mr-2"></i>
            ${message}
        </div>
    `;
    
    document.body.appendChild(alert);
    
    setTimeout(() => {
        alert.remove();
    }, 3000);
}
</script>
@endsection