{{-- resources/views/employee/visits/show.blade.php --}}
@extends('layouts.employee')

@section('content')
<div class="container-fluid px-4 py-6">
    <div class="mb-6">
        <div class="flex justify-between items-start">
            <div>
                <h1 class="text-2xl font-bold text-gray-800">Visit Details</h1>
                <p class="text-gray-600">Visit ID: {{ $visit->id }} - {{ $visit->client->name }}</p>
            </div>
            <div class="flex space-x-2">
                <a href="{{ route('employee.visits.index') }}" class="btn btn-secondary">
                    <i class="fas fa-arrow-left mr-2"></i> Back
                </a>
                @if($visit->status == 'scheduled')
                <form action="{{ route('employee.visits.start', $visit) }}" method="POST">
                    @csrf
                    <input type="hidden" name="latitude" id="start-lat">
                    <input type="hidden" name="longitude" id="start-lng">
                    <button type="button" onclick="startThisVisit()" class="btn btn-primary">
                        <i class="fas fa-play mr-2"></i> Start Visit
                    </button>
                </form>
                @elseif($visit->status == 'started')
                <form action="{{ route('employee.visits.complete', $visit) }}" method="POST">
                    @csrf
                    <input type="hidden" name="latitude" id="complete-lat">
                    <input type="hidden" name="longitude" id="complete-lng">
                    <button type="button" onclick="completeThisVisit()" class="btn btn-success">
                        <i class="fas fa-check mr-2"></i> Complete Visit
                    </button>
                </form>
                @endif
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Left Column - Details -->
        <div class="space-y-6">
            <!-- Visit Info Card -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold mb-4">Visit Information</h3>
                <div class="space-y-3">
                    <div>
                        <label class="text-sm text-gray-600">Client</label>
                        <p class="font-medium">{{ $visit->client->name }}</p>
                    </div>
                    <div>
                        <label class="text-sm text-gray-600">Purpose</label>
                        <p class="font-medium">{{ $visit->purpose }}</p>
                    </div>
                    <div>
                        <label class="text-sm text-gray-600">Scheduled</label>
                        <p class="font-medium">
                            {{ $visit->scheduled_date->format('M d, Y') }} at 
                            {{ \Carbon\Carbon::parse($visit->scheduled_time)->format('h:i A') }}
                        </p>
                    </div>
                    <div>
                        <label class="text-sm text-gray-600">Status</label>
                        <span class="status-badge status-{{ $visit->status }}">
                            {{ ucfirst($visit->status) }}
                        </span>
                    </div>
                    @if($visit->started_at)
                    <div>
                        <label class="text-sm text-gray-600">Started At</label>
                        <p class="font-medium">{{ $visit->started_at->format('M d, Y h:i A') }}</p>
                    </div>
                    @endif
                    @if($visit->completed_at)
                    <div>
                        <label class="text-sm text-gray-600">Completed At</label>
                        <p class="font-medium">{{ $visit->completed_at->format('M d, Y h:i A') }}</p>
                    </div>
                    @endif
                </div>
            </div>

            <!-- Client Info Card -->
            <div class="bg-white rounded-lg shadow p-6">
                <h3 class="text-lg font-semibold mb-4">Client Information</h3>
                <div class="space-y-3">
                    <div>
                        <label class="text-sm text-gray-600">Location</label>
                        <p class="font-medium">
                            {{ $visit->client->governorate->name_en }}, {{ $visit->client->city->name_en }}
                        </p>
                        <p class="text-sm text-gray-600">{{ $visit->client->area }}</p>
                    </div>
                    @if($visit->client->latitude && $visit->client->longitude)
                    <div>
                        <label class="text-sm text-gray-600">Coordinates</label>
                        <p class="font-medium">
                            {{ number_format($visit->client->latitude, 6) }}, 
                            {{ number_format($visit->client->longitude, 6) }}
                        </p>
                    </div>
                    @endif
                    @if($visit->client->contact_person)
                    <div>
                        <label class="text-sm text-gray-600">Contact Person</label>
                        <p class="font-medium">{{ $visit->client->contact_person }}</p>
                    </div>
                    @endif
                    @if($visit->client->phone)
                    <div>
                        <label class="text-sm text-gray-600">Phone</label>
                        <p class="font-medium">{{ $visit->client->phone }}</p>
                    </div>
                    @endif
                </div>
            </div>
        </div>

        <!-- Middle Column - Map -->
        <div class="lg:col-span-2">
            <div class="bg-white rounded-lg shadow p-4 h-full">
                <h3 class="text-lg font-semibold mb-4">Location Map</h3>
                <div id="map" style="height: 500px;" class="rounded-lg"></div>
                
                @if($visit->status == 'started')
                <!-- Tracking Controls -->
                <div class="mt-4 p-4 bg-blue-50 rounded-lg">
                    <h4 class="font-medium text-blue-800 mb-2">
                        <i class="fas fa-satellite-dish mr-2"></i> Live Tracking Active
                    </h4>
                    <p class="text-sm text-blue-600 mb-3">
                        Your location is being tracked. You can update your location manually if needed.
                    </p>
                    <form action="{{ route('tracking.update-location', $visit) }}" method="POST" class="flex items-center space-x-2">
                        @csrf
                        <button type="button" onclick="updateMyLocation()" class="btn btn-primary btn-sm">
                            <i class="fas fa-location-arrow mr-2"></i> Update My Location
                        </button>
                        <span class="text-sm text-gray-600" id="last-update">
                            Last update: {{ now()->format('h:i:s A') }}
                        </span>
                    </form>
                </div>
                @endif
                
                <!-- Visit Comments -->
                @if($visit->status == 'completed')
                <div class="mt-6">
                    <h4 class="font-medium mb-2">Visit Comments</h4>
                    <div class="bg-gray-50 p-4 rounded-lg">
                        @if($visit->employee_comment)
                        <p class="text-gray-700">{{ $visit->employee_comment }}</p>
                        @else
                        <p class="text-gray-500 italic">No comments added for this visit.</p>
                        @endif
                    </div>
                </div>
                @elseif($visit->status == 'started')
                <div class="mt-6">
                    <h4 class="font-medium mb-2">Add Comment (Optional)</h4>
                    <form action="{{ route('employee.visits.complete', $visit) }}" method="POST" id="complete-form">
                        @csrf
                        <textarea name="comment" rows="3" class="form-textarea" 
                                  placeholder="Add any notes or comments about this visit..."></textarea>
                    </form>
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

@push('styles')
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
@endpush

@push('scripts')
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
let map;
let clientMarker;
let employeeMarker;
let polyline;

function initMap() {
    // Default to Cairo if no coordinates
    const defaultLat = 30.0444;
    const defaultLng = 31.2357;
    
    // Use client coordinates if available, otherwise default
    const clientLat = {{ $visit->client->latitude ?? 'defaultLat' }};
    const clientLng = {{ $visit->client->longitude ?? 'defaultLng' }};
    
    map = L.map('map').setView([clientLat, clientLng], 13);
    
    // Add OpenStreetMap tiles
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);
    
    // Add client marker
    clientMarker = L.marker([clientLat, clientLng])
        .addTo(map)
        .bindPopup('<b>Client: {{ $visit->client->name }}</b><br>{{ $visit->client->area }}')
        .openPopup();
    
    // Add employee current location if visit is in progress
    @if($visit->status == 'started' && $visit->start_latitude && $visit->start_longitude)
    employeeMarker = L.marker([{{ $visit->start_latitude }}, {{ $visit->start_longitude }}])
        .addTo(map)
        .bindPopup('<b>Your Location</b><br>Visit started here')
        .openPopup();
        
    // Draw line between employee and client
    polyline = L.polyline([
        [{{ $visit->start_latitude }}, {{ $visit->start_longitude }}],
        [clientLat, clientLng]
    ], {color: 'blue'}).addTo(map);
    @endif
    
    // If visit is completed, show end location
    @if($visit->status == 'completed' && $visit->end_latitude && $visit->end_longitude)
    L.marker([{{ $visit->end_latitude }}, {{ $visit->end_longitude }}])
        .addTo(map)
        .bindPopup('<b>Visit Ended Here</b>');
    @endif
}

function startThisVisit() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            document.getElementById('start-lat').value = position.coords.latitude;
            document.getElementById('start-lng').value = position.coords.longitude;
            event.target.closest('form').submit();
        }, function(error) {
            alert('Please enable location services to start the visit.');
        });
    } else {
        alert('Geolocation is not supported.');
    }
}

function completeThisVisit() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            document.getElementById('complete-lat').value = position.coords.latitude;
            document.getElementById('complete-lng').value = position.coords.longitude;
            document.getElementById('complete-form').submit();
        }, function(error) {
            alert('Please enable location services to complete the visit.');
        });
    } else {
        alert('Geolocation is not supported.');
    }
}

function updateMyLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            // Send AJAX request to update location
            fetch('{{ route("tracking.update-location", $visit) }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude
                })
            }).then(response => {
                if (response.ok) {
                    document.getElementById('last-update').textContent = 
                        'Last update: ' + new Date().toLocaleTimeString();
                    
                    // Update marker on map
                    if (employeeMarker) {
                        employeeMarker.setLatLng([position.coords.latitude, position.coords.longitude]);
                    }
                }
            });
        });
    }
}

// Initialize map when page loads
document.addEventListener('DOMContentLoaded', initMap);
</script>
@endpush
@endsection