<!-- Path: app/Views/emergency/report.view.php -->
<div class="bg-slate-100 min-h-screen py-10">
    <div class="max-w-2xl mx-auto px-4 sm:px-6 lg:px-8">
        
        <div class="bg-alert text-white rounded-t-xl p-6 shadow-md text-center">
            <h1 class="text-2xl font-bold mb-2 flex items-center justify-center gap-3">
                <i class="fas fa-exclamation-triangle fa-fade"></i> REPORT EMERGENCY
            </h1>
            <p class="text-sm opacity-90">Please stay calm and fill out the details accurately. Help will be dispatched immediately.</p>
        </div>

        <div class="bg-white rounded-b-xl shadow-lg border border-slate-200 p-6 md:p-8">
            
            <!-- GPS Status Banner -->
            <div id="gps-status" class="mb-6 p-4 rounded-md bg-blue-50 border border-blue-200 text-blue-700 flex items-start gap-3">
                <i class="fas fa-spinner fa-spin mt-1 text-xl"></i>
                <div>
                    <strong class="block">Detecting your location...</strong>
                    <span class="text-sm">Please allow location access when prompted by your browser.</span>
                </div>
            </div>

            <form id="emergencyReportForm" enctype="multipart/form-data">
                <!-- Hidden GPS Fields -->
                <input type="hidden" name="latitude" id="lat_input" required>
                <input type="hidden" name="longitude" id="lng_input" required>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-2">Your Name</label>
                        <input type="text" name="full_name" value="{{ isset($user) && $user ? $user['full_name'] : '' }}" required placeholder="John Doe" class="w-full px-4 py-3 rounded-md bg-slate-50 border border-slate-300 focus:bg-white focus:border-alert focus:ring-2 focus:ring-red-200 outline-none transition-all">
                    </div>
                    <div>
                        <label class="block text-sm font-semibold text-slate-700 mb-2">Phone Number</label>
                        <input type="tel" name="phone_number" value="{{ isset($user) && $user ? $user['phone_number'] : '' }}" required placeholder="08012345678" class="w-full px-4 py-3 rounded-md bg-slate-50 border border-slate-300 focus:bg-white focus:border-alert focus:ring-2 focus:ring-red-200 outline-none transition-all">
                    </div>
                </div>

                <div class="mb-6">
                    <label class="block text-sm font-semibold text-slate-700 mb-2">What is the emergency?</label>
                    <select name="category_id" required class="w-full px-4 py-3 rounded-md bg-slate-50 border border-slate-300 focus:bg-white focus:border-alert focus:ring-2 focus:ring-red-200 outline-none transition-all cursor-pointer">
                        <option value="" disabled selected>Select emergency type...</option>
                        @if(isset($categories))
                            @foreach($categories as $cat)
                                <option value="{{ $cat['id'] }}">{{ $cat['name'] }}</option>
                            @endforeach
                        @endif
                    </select>
                </div>

                <div class="mb-6">
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Description (Optional but helpful)</label>
                    <textarea name="description" rows="3" placeholder="Briefly describe what happened, injuries, or specific landmarks..." class="w-full px-4 py-3 rounded-md bg-slate-50 border border-slate-300 focus:bg-white focus:border-alert focus:ring-2 focus:ring-red-200 outline-none transition-all resize-none"></textarea>
                </div>

                <div class="mb-8">
                    <label class="block text-sm font-semibold text-slate-700 mb-2">Photo Evidence (Optional)</label>
                    <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-slate-300 border-dashed rounded-md bg-slate-50 hover:bg-slate-100 transition-colors">
                        <div class="space-y-1 text-center">
                            <i class="fas fa-camera text-3xl text-slate-400 mb-2"></i>
                            <div class="flex text-sm text-slate-600 justify-center">
                                <label for="file-upload" class="relative cursor-pointer rounded-md font-medium text-brandBlue-600 hover:text-brandBlue-500 focus-within:outline-none">
                                    <span>Upload a photo</span>
                                    <input id="file-upload" name="image" type="file" class="sr-only" accept="image/*">
                                </label>
                            </div>
                            <p class="text-xs text-slate-500" id="file-name-display">PNG, JPG up to 5MB</p>
                        </div>
                    </div>
                </div>

                <button type="submit" id="submitBtn" disabled class="w-full bg-slate-400 text-white font-bold py-4 rounded-lg shadow-md transition-all text-lg flex items-center justify-center gap-2 cursor-not-allowed">
                    <i class="fas fa-lock"></i> Waiting for GPS...
                </button>
            </form>

        </div>
    </div>
</div>

@addScript
<script>
$(document).ready(function() {
    
    // 1. File Upload Name display
    $('#file-upload').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        if(fileName) {
            $('#file-name-display').text('Selected: ' + fileName).addClass('text-brandBlue-600 font-bold');
        }
    });

    // 2. HTML5 Geolocation Logic
    const $gpsStatus = $('#gps-status');
    const $submitBtn = $('#submitBtn');
    
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {
                // Success
                $('#lat_input').val(position.coords.latitude);
                $('#lng_input').val(position.coords.longitude);
                
                $gpsStatus.removeClass('bg-blue-50 border-blue-200 text-blue-700')
                          .addClass('bg-green-50 border-green-200 text-green-700')
                          .html('<i class="fas fa-check-circle mt-1 text-xl"></i><div><strong class="block">Location Acquired</strong><span class="text-sm">We have your exact coordinates.</span></div>');
                
                // Unlock submit button
                $submitBtn.removeClass('bg-slate-400 cursor-not-allowed')
                          .addClass('bg-alert hover:bg-red-600 cursor-pointer shadow-red-500/40')
                          .prop('disabled', false)
                          .html('<i class="fas fa-paper-plane"></i> SEND EMERGENCY ALERT');
            },
            function(error) {
                // Error (Denied or Unavailable)
                let errorMsg = "Unable to retrieve location.";
                if(error.code === 1) errorMsg = "Location access was denied. Please allow location tracking to submit an emergency.";
                
                $gpsStatus.removeClass('bg-blue-50 border-blue-200 text-blue-700')
                          .addClass('bg-red-50 border-red-200 text-red-700')
                          .html('<i class="fas fa-times-circle mt-1 text-xl"></i><div><strong class="block">GPS Failed</strong><span class="text-sm">'+errorMsg+'</span></div>');
                
                Swal.fire({
                    icon: 'error',
                    title: 'Location Required',
                    text: errorMsg,
                    confirmButtonText: 'Understood',
                    confirmButtonColor: '#ef4444'
                });
            },
            {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 0
            }
        );
    } else {
        $gpsStatus.html('<div class="text-red-600"><i class="fas fa-exclamation-triangle"></i> Geolocation is not supported by your browser.</div>');
    }

    // 3. Form Submission via AJAX (with File support)
    $('#emergencyReportForm').on('submit', function(e) {
        e.preventDefault();
        
        let formData = new FormData(this);
        let originalBtnHtml = $submitBtn.html();
        
        $submitBtn.html('<i class="fas fa-spinner fa-spin"></i> TRANSMITTING...').prop('disabled', true);
        
        $.ajax({
            url: '{{APP_URL}}/emergency/report',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {
                        // Check if response is a string (if server returns HTML/JSON string) and parse if necessary
                        let res = typeof response === 'string' ? JSON.parse(response) : response;
                        
                        if (res.status === 'success' && res.redirect) {
                            window.location.href = '{{APP_URL}}' + res.redirect;
                        } else {
                            Swal.fire('Error', 'An unexpected error occurred.', 'error');
                            $submitBtn.html(originalBtnHtml).prop('disabled', false);
                        }
                    },
                    error: function(xhr) {
                        let msg = 'Failed to submit report. Please call emergency services directly.';
                        if(xhr.responseJSON && xhr.responseJSON.errors) {
                            // Handle validation errors safely depending on your error structure
                            let errs = xhr.responseJSON.errors;
                            msg = Array.isArray(errs) ? errs[0] : Object.values(errs)[0];
                        }
                        Swal.fire('Transmission Error', msg, 'error');
                        $submitBtn.html(originalBtnHtml).prop('disabled', false);
                    }
                });
    });
});
</script>
@endAddScript