@extends('layouts.dashboard')

@section('title', 'Schedule New Visit')

@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-8">
        <div>
            <a href="{{ route('visits.index') }}" 
               class="text-blue-600 hover:text-blue-700 transition-colors duration-200 inline-flex items-center mb-2 group">
                <i class="fas fa-arrow-left mr-2 group-hover:-translate-x-1 transition-transform duration-200"></i> 
                Back to Visits
            </a>
            <h1 class="text-2xl font-bold text-gray-900">Schedule New Visit</h1>
            <p class="text-gray-600 mt-1">Schedule a new field visit for an employee</p>
        </div>
        <div class="flex items-center space-x-2 mt-4 md:mt-0">
            <div class="w-12 h-12 rounded-xl bg-gradient-to-br from-blue-100 to-indigo-200 flex items-center justify-center shadow-sm">
                <i class="fas fa-calendar-plus text-blue-600 text-xl"></i>
            </div>
        </div>
    </div>

    <div class="max-w-6xl mx-auto">
        <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
            <!-- Form Header -->
            <div class="px-6 py-5 border-b border-gray-200 bg-gradient-to-r from-blue-50 to-indigo-50">
                <h2 class="text-lg font-semibold text-gray-900">Visit Information</h2>
                <p class="text-sm text-gray-600 mt-1">Fill in the visit details and schedule</p>
            </div>

            <!-- Form -->
            <form action="{{ route('visits.store') }}" method="POST" id="visitForm" class="p-6">
                @csrf

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <!-- Visit Details -->
                    <div class="space-y-6">
                        <div class="flex items-center mb-4">
                            <div class="w-8 h-8 rounded-lg bg-blue-100 text-blue-600 flex items-center justify-center mr-3">
                                <i class="fas fa-calendar-alt"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-900">Visit Details</h3>
                        </div>
                        
                        <!-- Client -->
                        <div>
                            <label for="client_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-handshake mr-2 text-blue-500"></i>Client *
                            </label>
                            <select id="client_id" 
                                    name="client_id" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('client_id') border-red-500 @enderror"
                                    required>
                                <option value="">Select Client</option>
                                @foreach($clients as $client)
                                    <option value="{{ $client->id }}" 
                                            data-governorate="{{ $client->governorate_id }}"
                                            data-city="{{ $client->city_id }}"
                                            data-area="{{ $client->area }}"
                                            data-latitude="{{ $client->latitude }}"
                                            data-longitude="{{ $client->longitude }}"
                                            data-address="{{ $client->address }}"
                                            {{ old('client_id') == $client->id ? 'selected' : '' }}>
                                        {{ $client->name }} - {{ $client->contact_person ?? 'No contact' }}
                                    </option>
                                @endforeach
                            </select>
                            @error('client_id')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>

                        <!-- Employee -->
                        <div>
                            <label for="employee_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-user-tie mr-2 text-blue-500"></i>Employee *
                            </label>
                            <select id="employee_id" 
                                    name="employee_id" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('employee_id') border-red-500 @enderror"
                                    required>
                                <option value="">Select Employee</option>
                                @foreach($employees as $employee)
                                    <option value="{{ $employee->id }}" {{ old('employee_id') == $employee->id ? 'selected' : '' }}>
                                        {{ $employee->name }} ({{ $employee->employee_id }})
                                    </option>
                                @endforeach
                            </select>
                            @error('employee_id')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>

                        <!-- Date -->
                        <div>
                            <label for="scheduled_date" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-calendar-day mr-2 text-blue-500"></i>Date *
                            </label>
                            <input type="date" 
                                   id="scheduled_date" 
                                   name="scheduled_date" 
                                   value="{{ old('scheduled_date', date('Y-m-d')) }}"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('scheduled_date') border-red-500 @enderror"
                                   required>
                            @error('scheduled_date')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>

                        <!-- Time -->
                        <div>
                            <label for="scheduled_time" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-clock mr-2 text-blue-500"></i>Time *
                            </label>
                            <input type="time" 
                                   id="scheduled_time" 
                                   name="scheduled_time" 
                                   value="{{ old('scheduled_time', '09:00') }}"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('scheduled_time') border-red-500 @enderror"
                                   required>
                            @error('scheduled_time')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>
                    </div>

                    <!-- Location Information -->
                    <div class="space-y-6">
                        <div class="flex items-center mb-4">
                            <div class="w-8 h-8 rounded-lg bg-indigo-100 text-indigo-600 flex items-center justify-center mr-3">
                                <i class="fas fa-map-marked-alt"></i>
                            </div>
                            <h3 class="text-lg font-semibold text-gray-900">Location Information</h3>
                        </div>
                        
                        <!-- Governorate -->
                        <div>
                            <label for="governorate_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-flag mr-2 text-indigo-500"></i>Governorate *
                            </label>
                            <select id="governorate_id" 
                                    name="governorate_id" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('governorate_id') border-red-500 @enderror"
                                    required>
                                <option value="">Select Governorate</option>
                                @foreach($governorates as $governorate)
                                    <option value="{{ $governorate->id }}" {{ old('governorate_id') == $governorate->id ? 'selected' : '' }}>
                                        {{ $governorate->name }}
                                    </option>
                                @endforeach
                            </select>
                            @error('governorate_id')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>

                        <!-- City -->
                        <div>
                            <label for="city_id" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-city mr-2 text-indigo-500"></i>City *
                            </label>
                            <select id="city_id" 
                                    name="city_id" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('city_id') border-red-500 @enderror"
                                    required>
                                <option value="">Select City</option>
                            </select>
                            @error('city_id')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>

                        <!-- Area -->
                        <div>
                            <label for="area" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-map-marker mr-2 text-indigo-500"></i>Area *
                            </label>
                            <input type="text" 
                                   id="area" 
                                   name="area" 
                                   value="{{ old('area') }}"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('area') border-red-500 @enderror"
                                   placeholder="e.g., Downtown, Nasr City"
                                   required>
                            @error('area')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>

                        <!-- Address -->
                        <div>
                            <label for="address" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-map-pin mr-2 text-indigo-500"></i>Full Address
                            </label>
                            <textarea id="address" 
                                      name="address" 
                                      rows="2"
                                      class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('address') border-red-500 @enderror"
                                      placeholder="Street name, building number, floor...">{{ old('address') }}</textarea>
                            @error('address')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>
                    </div>
                </div>

                <!-- GPS Coordinates -->
                <div class="mt-10 pt-8 border-t border-gray-200">
                    <div class="flex items-center mb-6">
                        <div class="w-8 h-8 rounded-lg bg-green-100 text-green-600 flex items-center justify-center mr-3">
                            <i class="fas fa-globe-americas"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray-900">GPS Coordinates</h3>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- Latitude -->
                        <div>
                            <label for="latitude" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-globe-americas mr-2 text-green-500"></i>Latitude
                            </label>
                            <div class="flex items-center space-x-3">
                                <input type="number" 
                                       id="latitude" 
                                       name="latitude" 
                                       value="{{ old('latitude') }}"
                                       class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('latitude') border-red-500 @enderror"
                                       placeholder="e.g., 30.0444"
                                       step="0.000001">
                                <button type="button" 
                                        id="getLocationBtn"
                                        class="whitespace-nowrap px-4 py-3 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition duration-200 flex items-center">
                                    <i class="fas fa-crosshairs mr-2"></i> Get Location
                                </button>
                            </div>
                            @error('latitude')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>

                        <!-- Longitude -->
                        <div>
                            <label for="longitude" class="block text-sm font-medium text-gray-700 mb-2">
                                <i class="fas fa-globe-americas mr-2 text-green-500"></i>Longitude
                            </label>
                            <input type="number" 
                                   id="longitude" 
                                   name="longitude" 
                                   value="{{ old('longitude') }}"
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('longitude') border-red-500 @enderror"
                                   placeholder="e.g., 31.2357"
                                   step="0.000001">
                            @error('longitude')
                                <p class="mt-2 text-sm text-red-600 flex items-center">
                                    <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                                </p>
                            @enderror
                        </div>
                    </div>
                    
                    <!-- Map Preview -->
                    <div id="mapPreview" class="mt-6 h-64 bg-gray-50 rounded-xl border-2 border-gray-200 border-dashed flex items-center justify-center overflow-hidden">
                        <div id="map" class="w-full h-full rounded-lg"></div>
                        <div id="noCoords" class="text-center p-6">
                            <i class="fas fa-map-marked-alt text-gray-300 text-5xl mb-4"></i>
                            <p class="text-gray-500 font-medium mb-1">Map Preview</p>
                            <p class="text-gray-400 text-sm">Enter GPS coordinates or use "Get Location" to view map</p>
                        </div>
                    </div>
                </div>

                <!-- Comments -->
                <div class="mt-10 pt-8 border-t border-gray-200">
                    <div class="flex items-center mb-6">
                        <div class="w-8 h-8 rounded-lg bg-purple-100 text-purple-600 flex items-center justify-center mr-3">
                            <i class="fas fa-comment-alt"></i>
                        </div>
                        <h3 class="text-lg font-semibold text-gray-900">Additional Comments</h3>
                    </div>
                    
                    <div>
                        <label for="comments" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-comment-alt mr-2 text-purple-500"></i>Instructions & Notes
                        </label>
                        <textarea id="comments" 
                                  name="comments" 
                                  rows="4"
                                  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition duration-200 @error('comments') border-red-500 @enderror"
                                  placeholder="Any additional instructions or notes for the employee...">{{ old('comments') }}</textarea>
                        @error('comments')
                            <p class="mt-2 text-sm text-red-600 flex items-center">
                                <i class="fas fa-exclamation-circle mr-2"></i> {{ $message }}
                            </p>
                        @enderror
                    </div>
                </div>

                <!-- Form Footer -->
                <div class="mt-12 pt-8 border-t border-gray-200 flex flex-col md:flex-row md:items-center md:justify-between">
                    <div class="mb-4 md:mb-0">
                        <p class="text-sm text-gray-500 flex items-center">
                            <i class="fas fa-info-circle mr-2 text-blue-500"></i> Fields marked with * are required
                        </p>
                    </div>
                    <div class="flex items-center space-x-3">
                        <a href="{{ route('visits.index') }}" 
                           class="px-5 py-3 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition duration-200 flex items-center">
                            <i class="fas fa-times mr-2"></i> Cancel
                        </a>
                        <button type="submit" 
                                class="px-5 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition duration-200 shadow-sm hover:shadow-md flex items-center group">
                            <i class="fas fa-calendar-check mr-2 group-hover:scale-110 transition-transform duration-200"></i> 
                            <span>Schedule Visit</span>
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <!-- Quick Tips -->
        <div class="mt-8 bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-100 rounded-xl p-5">
            <div class="flex">
                <div class="flex-shrink-0">
                    <div class="w-10 h-10 rounded-lg bg-blue-100 text-blue-600 flex items-center justify-center">
                        <i class="fas fa-lightbulb"></i>
                    </div>
                </div>
                <div class="ml-4">
                    <h3 class="text-sm font-semibold text-blue-800">Quick Tips</h3>
                    <div class="mt-2">
                        <ul class="space-y-2">
                            <li class="text-sm text-blue-700 flex items-start">
                                <i class="fas fa-check-circle text-blue-500 mr-2 mt-0.5 text-xs"></i>
                                <span>Select a client to automatically fill location information</span>
                            </li>
                            <li class="text-sm text-blue-700 flex items-start">
                                <i class="fas fa-check-circle text-blue-500 mr-2 mt-0.5 text-xs"></i>
                                <span>GPS coordinates are required for visit tracking and verification</span>
                            </li>
                            <li class="text-sm text-blue-700 flex items-start">
                                <i class="fas fa-check-circle text-blue-500 mr-2 mt-0.5 text-xs"></i>
                                <span>Use "Get Location" button to automatically fetch your current coordinates</span>
                            </li>
                            <li class="text-sm text-blue-700 flex items-start">
                                <i class="fas fa-check-circle text-blue-500 mr-2 mt-0.5 text-xs"></i>
                                <span>Employees will receive notifications for their scheduled visits</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </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 map = null;
let marker = null;

document.addEventListener('DOMContentLoaded', function() {
    const clientSelect = document.getElementById('client_id');
    const governorateSelect = document.getElementById('governorate_id');
    const citySelect = document.getElementById('city_id');
    const areaInput = document.getElementById('area');
    const addressInput = document.getElementById('address');
    const latitudeInput = document.getElementById('latitude');
    const longitudeInput = document.getElementById('longitude');
    const mapPreview = document.getElementById('mapPreview');
    const noCoords = document.getElementById('noCoords');
    const getLocationBtn = document.getElementById('getLocationBtn');

    // When client is selected, auto-fill location data
    clientSelect.addEventListener('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        
        if (selectedOption.value) {
            const governorateId = selectedOption.getAttribute('data-governorate');
            const cityId = selectedOption.getAttribute('data-city');
            const area = selectedOption.getAttribute('data-area');
            const latitude = selectedOption.getAttribute('data-latitude');
            const longitude = selectedOption.getAttribute('data-longitude');
            const address = selectedOption.getAttribute('data-address');
            
            // Set governorate
            governorateSelect.value = governorateId;
            
            // Load cities for this governorate
            loadCities(governorateId, cityId);
            
            // Set area and address
            areaInput.value = area || '';
            addressInput.value = address || '';
            
            // Set coordinates if available
            if (latitude && longitude) {
                latitudeInput.value = latitude;
                longitudeInput.value = longitude;
                updateMapPreview();
            }
        }
    });

    // Load cities when governorate changes
    governorateSelect.addEventListener('change', function() {
        loadCities(this.value);
    });

    // Initial load if governorate is pre-selected
    @if(old('governorate_id'))
        loadCities('{{ old('governorate_id') }}', '{{ old('city_id') }}');
    @endif

    function loadCities(governorateId, selectedCityId = null) {
        if (governorateId) {
            citySelect.innerHTML = '<option value="">Select City</option>';
            citySelect.disabled = true;
            
            fetch(`/clients/cities?governorate_id=${governorateId}`)
                .then(response => response.json())
                .then(data => {
                    citySelect.disabled = false;
                    data.forEach(city => {
                        const option = document.createElement('option');
                        option.value = city.id;
                        option.textContent = city.name;
                        if (selectedCityId && city.id == selectedCityId) {
                            option.selected = true;
                        }
                        citySelect.appendChild(option);
                    });
                    
                    // Set initial city if from old data
                    @if(old('city_id'))
                        citySelect.value = '{{ old('city_id') }}';
                    @endif
                })
                .catch(error => {
                    console.error('Error fetching cities:', error);
                    citySelect.disabled = false;
                });
        } else {
            citySelect.innerHTML = '<option value="">Select City</option>';
        }
    }

    // Get current location
    getLocationBtn.addEventListener('click', function() {
        if (navigator.geolocation) {
            const originalText = getLocationBtn.innerHTML;
            getLocationBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Getting Location...';
            getLocationBtn.disabled = true;
            
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    latitudeInput.value = position.coords.latitude.toFixed(6);
                    longitudeInput.value = position.coords.longitude.toFixed(6);
                    getLocationBtn.innerHTML = originalText;
                    getLocationBtn.disabled = false;
                    updateMapPreview();
                },
                function(error) {
                    alert('Unable to get your location. Please allow location access or enter coordinates manually.');
                    getLocationBtn.innerHTML = originalText;
                    getLocationBtn.disabled = false;
                },
                {
                    enableHighAccuracy: true,
                    timeout: 10000,
                    maximumAge: 0
                }
            );
        } else {
            alert('Geolocation is not supported by your browser. Please enter coordinates manually.');
        }
    });

    // Update map preview when coordinates change
    latitudeInput.addEventListener('input', updateMapPreview);
    longitudeInput.addEventListener('input', updateMapPreview);

    // Initial map update if coordinates exist
    @if(old('latitude') && old('longitude'))
        setTimeout(() => updateMapPreview(), 500);
    @endif

    function updateMapPreview() {
        const lat = parseFloat(latitudeInput.value);
        const lng = parseFloat(longitudeInput.value);
        
        if (!isNaN(lat) && !isNaN(lng) && lat >= -90 && lat <= 90 && lng >= -180 && lng <= 180) {
            mapPreview.classList.remove('border-dashed');
            mapPreview.classList.add('border-solid', 'border-gray-300');
            noCoords.style.display = 'none';
            
            if (!map) {
                initMap(lat, lng);
            } else {
                map.setView([lat, lng], 15);
                if (marker) {
                    marker.setLatLng([lat, lng]);
                } else {
                    marker = L.marker([lat, lng]).addTo(map);
                }
            }
            
            // Add popup to marker
            if (marker) {
                marker.bindPopup(`<b>Visit Location</b><br>Lat: ${lat.toFixed(6)}<br>Lng: ${lng.toFixed(6)}`).openPopup();
            }
        } else {
            if (map) {
                map.remove();
                map = null;
                marker = null;
            }
            mapPreview.classList.add('border-dashed');
            mapPreview.classList.remove('border-solid', 'border-gray-300');
            noCoords.style.display = 'block';
        }
    }

    function initMap(lat, lng) {
        map = L.map('map').setView([lat, lng], 15);
        
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
            maxZoom: 19
        }).addTo(map);
        
        marker = L.marker([lat, lng]).addTo(map);
        
        // Add scale control
        L.control.scale().addTo(map);
    }
});
</script>

<style>
/* Custom styles for the form */
.form-select:focus, .form-input:focus, textarea:focus {
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

#map { 
    height: 100%; 
    width: 100%;
}

/* Smooth transitions */
* {
    transition-property: background-color, border-color, color, fill, stroke, opacity, box-shadow, transform;
    transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
    transition-duration: 200ms;
}

/* Custom scrollbar for select */
select {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
    background-position: right 0.75rem center;
    background-repeat: no-repeat;
    background-size: 1.5em 1.5em;
    padding-right: 2.5rem;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
}

/* Map container */
#mapPreview {
    min-height: 256px;
}
</style>
@endsection