@extends('layouts.dashboard')

@section('title', 'My Visits')

@section('content')
<div class="container mx-auto px-4 py-6">
    <!-- Header -->
    <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">My Visits</h1>
            <p class="text-gray-600 mt-1">View and manage your scheduled visits</p>
        </div>
        <div class="flex items-center space-x-3 mt-4 md:mt-0">
            <div class="relative">
                <input type="search" 
                       placeholder="Search my visits..." 
                       class="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent">
                <i class="fas fa-search absolute left-3 top-3 text-gray-400"></i>
            </div>
        </div>
    </div>

    <!-- Stats Cards -->
    <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-calendar-alt text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Total Visits</p>
                    <p class="text-2xl font-bold text-gray-800">{{ $visits->total() }}</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">Scheduled</p>
                    <p class="text-2xl font-bold text-gray-800">
                        {{ $visits->where('status', 'scheduled')->count() }}
                    </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-check-circle text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Completed</p>
                    <p class="text-2xl font-bold text-gray-800">
                        {{ $visits->where('status', 'completed')->count() }}
                    </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-running text-xl"></i>
                </div>
                <div class="ml-4">
                    <p class="text-sm font-medium text-gray-600">Today's Visits</p>
                    <p class="text-2xl font-bold text-gray-800">
                        {{ $visits->where('scheduled_date', today())->count() }}
                    </p>
                </div>
            </div>
        </div>
    </div>

    <!-- Visits Table -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <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-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-calendar mr-2"></i> Date & Time
                            </div>
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-handshake mr-2"></i> Client
                            </div>
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-map-marker-alt mr-2"></i> Location
                            </div>
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-info-circle mr-2"></i> Status
                            </div>
                        </th>
                        <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase tracking-wider">
                            <div class="flex items-center">
                                <i class="fas fa-cog mr-2"></i> Actions
                            </div>
                        </th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-100">
                    @forelse($visits as $visit)
                    <tr class="hover:bg-gray-50 transition-colors duration-150 {{ $visit->scheduled_date->isToday() ? 'bg-blue-50' : '' }}">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">
                                {{ $visit->scheduled_date->format('M d, Y') }}
                                @if($visit->scheduled_date->isToday())
                                <span class="ml-2 inline-flex items-center px-2 py-1 rounded text-xs font-medium bg-blue-100 text-blue-800">
                                    <i class="fas fa-star mr-1"></i> Today
                                </span>
                                @endif
                            </div>
                            <div class="text-sm text-gray-500">
                                {{ $visit->scheduled_time }}
                            </div>
                            @if($visit->started_at)
                            <div class="text-xs text-blue-600 mt-1">
                                <i class="fas fa-play-circle mr-1"></i> Started: {{ $visit->started_at->format('h:i A') }}
                            </div>
                            @endif
                            @if($visit->completed_at)
                            <div class="text-xs text-green-600 mt-1">
                                <i class="fas fa-check-circle mr-1"></i> Completed: {{ $visit->completed_at->format('h:i A') }}
                            </div>
                            @endif
                        </td>
                        <td class="px-6 py-4">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 h-10 w-10">
                                    <div class="h-10 w-10 rounded-lg bg-gradient-to-r from-green-500 to-teal-600 flex items-center justify-center">
                                        <i class="fas fa-handshake text-white"></i>
                                    </div>
                                </div>
                                <div class="ml-4">
                                    <div class="text-sm font-semibold text-gray-900">{{ $visit->client->name }}</div>
                                    <div class="text-sm text-gray-500">{{ $visit->client->contact_person ?? 'No contact' }}</div>
                                    <div class="text-xs text-gray-500">{{ $visit->client->phone }}</div>
                                </div>
                            </div>
                        </td>
                        <td class="px-6 py-4">
                            <div class="text-sm text-gray-900">
                                <div class="flex items-center">
                                    <i class="fas fa-map-pin text-gray-400 mr-2"></i>
                                    <span>{{ $visit->area }}, {{ $visit->city->name }}</span>
                                </div>
                                <div class="text-xs text-gray-500 mt-1">{{ $visit->governorate->name }}</div>
                                @if($visit->latitude && $visit->longitude)
                                <a href="javascript:void(0)" 
                                   onclick="showVisitOnMap({{ $visit->latitude }}, {{ $visit->longitude }}, '{{ $visit->client->name }}')"
                                   class="inline-flex items-center px-2 py-1 mt-1 rounded text-xs bg-blue-50 text-blue-700 hover:bg-blue-100">
                                    <i class="fas fa-map-marked-alt mr-1"></i> View on Map
                                </a>
                                @endif
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            @php
                                $statusColors = [
                                    'scheduled' => 'bg-yellow-100 text-yellow-800',
                                    'in_progress' => 'bg-blue-100 text-blue-800',
                                    'completed' => 'bg-green-100 text-green-800',
                                    'cancelled' => 'bg-red-100 text-red-800'
                                ];
                            @endphp
                            <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium {{ $statusColors[$visit->status] }}">
                                <i class="fas fa-circle mr-1 text-{{ 
                                    $visit->status == 'scheduled' ? 'yellow' : 
                                    ($visit->status == 'in_progress' ? 'blue' : 
                                    ($visit->status == 'completed' ? 'green' : 'red')) 
                                }}-500" style="font-size: 8px;"></i>
                                {{ str_replace('_', ' ', ucfirst($visit->status)) }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                            <div class="flex items-center space-x-2">
                                <a href="{{ route('visits.show', $visit) }}" 
                                   class="text-blue-600 hover:text-blue-900 transition-colors duration-200"
                                   title="View Details">
                                    <i class="fas fa-eye"></i>
                                </a>
                                
                                @if($visit->status == 'scheduled')
                                <form action="{{ route('visits.start', $visit) }}" 
                                      method="POST" 
                                      class="inline">
                                    @csrf
                                    <button type="submit" 
                                            class="text-green-600 hover:text-green-900 transition-colors duration-200"
                                            title="Start Visit"
                                            onclick="return confirm('Start this visit now?')">
                                        <i class="fas fa-play-circle"></i>
                                    </button>
                                </form>
                                @endif
                                
                                @if($visit->status == 'in_progress')
                                <button type="button" 
                                        onclick="showCompleteModal({{ $visit->id }})"
                                        class="text-purple-600 hover:text-purple-900 transition-colors duration-200"
                                        title="Complete Visit">
                                    <i class="fas fa-check-circle"></i>
                                </button>
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="5" class="px-6 py-12 text-center">
                            <div class="flex flex-col items-center justify-center">
                                <div class="w-24 h-24 mb-4 text-gray-300">
                                    <i class="fas fa-calendar-times text-6xl"></i>
                                </div>
                                <h3 class="text-lg font-medium text-gray-700 mb-2">No Visits Scheduled</h3>
                                <p class="text-gray-500">You don't have any visits scheduled yet.</p>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        @if($visits->hasPages())
        <div class="bg-gray-50 px-6 py-4 border-t border-gray-100">
            {{ $visits->links() }}
        </div>
        @endif
    </div>
</div>

<!-- Complete Visit Modal -->
<div id="completeModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-1/3 shadow-lg rounded-xl bg-white">
        <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold text-gray-800">Complete Visit</h3>
            <button onclick="closeCompleteModal()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        
        <form id="completeForm" method="POST">
            @csrf
            <div class="mb-4">
                <label class="form-label">Visit Notes</label>
                <textarea name="employee_notes" 
                          rows="4"
                          class="form-input"
                          placeholder="Add notes about the visit, client feedback, or any issues encountered..."></textarea>
            </div>
            
            <div class="flex justify-end space-x-3">
                <button type="button" 
                        onclick="closeCompleteModal()" 
                        class="btn-secondary">
                    Cancel
                </button>
                <button type="submit" 
                        class="btn-primary">
                    <i class="fas fa-check-circle mr-2"></i> Complete Visit
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Map Modal -->
<div id="mapModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full hidden z-50">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-xl bg-white">
        <div class="flex justify-between items-center mb-4">
            <h3 id="mapTitle" class="text-lg font-semibold text-gray-800">Visit Location</h3>
            <button onclick="closeMap()" class="text-gray-400 hover:text-gray-600">
                <i class="fas fa-times text-xl"></i>
            </button>
        </div>
        <div id="modalMap" class="h-96 rounded-lg border border-gray-300"></div>
        <div class="mt-4 flex justify-end">
            <button onclick="closeMap()" class="btn-secondary">
                Close
            </button>
        </div>
    </div>
</div>

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

<script>
let modalMap = null;

function showCompleteModal(visitId) {
    const modal = document.getElementById('completeModal');
    const form = document.getElementById('completeForm');
    
    form.action = `/visits/${visitId}/complete`;
    modal.classList.remove('hidden');
}

function closeCompleteModal() {
    document.getElementById('completeModal').classList.add('hidden');
}

function showVisitOnMap(latitude, longitude, clientName) {
    const modal = document.getElementById('mapModal');
    const mapTitle = document.getElementById('mapTitle');
    const mapContainer = document.getElementById('modalMap');
    
    mapTitle.textContent = clientName + ' - Location';
    modal.classList.remove('hidden');
    
    // Clear previous map
    if (modalMap) {
        modalMap.remove();
    }
    
    // Initialize new map
    modalMap = L.map(mapContainer).setView([latitude, longitude], 15);
    
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(modalMap);
    
    // Add marker for visit location
    L.marker([latitude, longitude])
        .addTo(modalMap)
        .bindPopup(`<b>${clientName}</b><br>Visit Location`)
        .openPopup();
    
    // Add user's current location if available
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                const userLat = position.coords.latitude;
                const userLng = position.coords.longitude;
                
                // Add user location marker
                L.marker([userLat, userLng], {
                    icon: L.divIcon({
                        html: '<div class="w-6 h-6 bg-blue-500 rounded-full border-2 border-white shadow-lg"></div>',
                        className: 'user-location-marker',
                        iconSize: [24, 24],
                        iconAnchor: [12, 12]
                    })
                })
                .addTo(modalMap)
                .bindPopup('<b>Your Current Location</b>');
                
                // Draw line between user and visit location
                L.polyline([
                    [userLat, userLng],
                    [latitude, longitude]
                ], {
                    color: 'blue',
                    weight: 2,
                    opacity: 0.7,
                    dashArray: '10, 10'
                }).addTo(modalMap);
                
                // Fit bounds to show both points
                const bounds = L.latLngBounds(
                    [userLat, userLng],
                    [latitude, longitude]
                );
                modalMap.fitBounds(bounds, { padding: [50, 50] });
            },
            function(error) {
                console.log('Unable to get current location:', error);
            }
        );
    }
}

function closeMap() {
    document.getElementById('mapModal').classList.add('hidden');
    if (modalMap) {
        modalMap.remove();
        modalMap = null;
    }
}

// Search functionality
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.querySelector('input[type="search"]');
    
    searchInput.addEventListener('keyup', function(e) {
        if (e.key === 'Enter') {
            const searchTerm = this.value.trim();
            if (searchTerm) {
                // Implement search functionality here
                console.log('Searching for:', searchTerm);
            }
        }
    });
});
</script>

<style>
#modalMap { 
    height: 100%; 
    width: 100%;
    border-radius: 0.5rem;
}
</style>
@endsection