<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($title ?? 'Emergency Response Coordination System', ENT_QUOTES, 'UTF-8') ?></title>
    <meta name="description" content="<?= htmlspecialchars($meta_description ?? 'Rapid emergency reporting and dispatch system.', ENT_QUOTES, 'UTF-8') ?>">
    
    <!-- Google Fonts: Inter for clean, highly legible UI -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/4.0.0/jquery.min.js"></script>

    <!-- FontAwesome for standard icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <!-- Tailwind CSS CDN -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>

        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                    colors: {
                        navy: {
                            800: '#1e3a8a',
                            900: '#1e3a8a', // Deep professional navy
                            950: '#172554',
                        },
                        brandBlue: {
                            500: '#3b82f6', // Bright, actionable blue
                            600: '#2563eb',
                        },
                        alert: '#ef4444', // Red for emergencies
                    }
                }
            }
        }
    </script>

    <!-- SweetAlert2 CSS & JS for elegant notifications -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <!-- Coreflux Head Injection -->
    <?= htmlspecialchars(Core\View::renderHead(), ENT_QUOTES, 'UTF-8') ?>

    <style>
        
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc; 
            display: flex;
            flex-direction: column;
            min-height: 100vh;
        }
        main {
            flex: 1;
        }
        
        ::-webkit-scrollbar {
            width: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1; 
        }
        ::-webkit-scrollbar-thumb {
            background: #cbd5e1; 
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #94a3b8; 
        }
    </style>
</head>
<body class="text-slate-800 antialiased">

    <!-- Navbar -->
    <nav class="bg-navy-950 text-white shadow-lg sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-16">
                <!-- Logo & Brand -->
                <div class="flex items-center">
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/" class="flex-shrink-0 flex items-center gap-2 group">
                        <div class="w-10 h-10 bg-alert text-white rounded-lg flex items-center justify-center font-bold text-xl shadow-md group-hover:scale-105 transition-transform">
                            <i class="fas fa-shield-alt"></i>
                        </div>
                        <span class="font-bold text-xl tracking-tight hidden sm:block">ERCS</span>
                    </a>
                </div>

                <!-- Desktop Menu -->
                <div class="hidden md:flex items-center space-x-4">
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/" class="px-3 py-2 rounded-md text-sm font-medium hover:bg-navy-800 transition-colors">Home</a>
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/about" class="px-3 py-2 rounded-md text-sm font-medium hover:bg-navy-800 transition-colors">About</a>
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/contact" class="px-3 py-2 rounded-md text-sm font-medium hover:bg-navy-800 transition-colors">Contact</a>
                    
                    <!-- Primary Call to Action -->
                    <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/emergency/report" class="ml-4 px-4 py-2 bg-alert hover:bg-red-600 text-white font-semibold rounded-md shadow-md transition-colors flex items-center gap-2 pulse-animation">
                        <i class="fas fa-exclamation-triangle"></i> Report Emergency
                    </a>

                    <!-- Auth Links / Dynamic State -->
                    <?php if (Core\Auth::check()): ?>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/dashboard" class="ml-2 px-3 py-2 text-sm font-medium text-brandBlue-500 hover:text-white transition-colors">
                            <i class="fas fa-user-circle mr-1"></i> Dashboard
                        </a>
                    <?php else: ?>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/login" class="ml-2 px-3 py-2 text-sm font-medium text-slate-300 hover:text-white transition-colors">
                            Login
                        </a>
                    <?php endif; ?>
                </div>

                <!-- Mobile menu button -->
                <div class="md:hidden flex items-center">
                    <button id="mobile-menu-btn" class="text-slate-300 hover:text-white focus:outline-none">
                        <i class="fas fa-bars text-2xl"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- Mobile Menu (Hidden by default) -->
        <div id="mobile-menu" class="hidden md:hidden bg-navy-900 border-t border-navy-800 pb-4 shadow-inner">
            <div class="px-2 pt-2 space-y-1">
                <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-navy-800">Home</a>
                <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/about" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-navy-800">About</a>
                <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/contact" class="block px-3 py-2 rounded-md text-base font-medium hover:bg-navy-800">Contact</a>
                
                <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/emergency/report" class="block mt-2 px-3 py-3 bg-alert text-white rounded-md text-base font-bold text-center shadow">
                    <i class="fas fa-exclamation-triangle mr-2"></i> Report Emergency
                </a>
                
                <div class="border-t border-navy-800 mt-2 pt-2">
                    <?php if (Core\Auth::check()): ?>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/dashboard" class="block px-3 py-2 rounded-md text-base font-medium text-brandBlue-500 hover:bg-navy-800">Dashboard</a>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/logout" class="block px-3 py-2 rounded-md text-base font-medium text-slate-300 hover:bg-navy-800">Logout</a>
                    <?php else: ?>
                        <a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/login" class="block px-3 py-2 rounded-md text-base font-medium text-slate-300 hover:bg-navy-800">Login</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Content Area where individual views are injected -->
    <main>
        <!-- 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="<?= htmlspecialchars(isset($user) && $user ? $user['full_name'] : '', ENT_QUOTES, 'UTF-8') ?>" 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="<?= htmlspecialchars(isset($user) && $user ? $user['phone_number'] : '', ENT_QUOTES, 'UTF-8') ?>" 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>
                        <?php if (isset($categories)): ?><?php foreach ($categories as $cat): ?>
                                <option value="<?= htmlspecialchars($cat['id'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($cat['name'], ENT_QUOTES, 'UTF-8') ?></option>
                            <?php endforeach; ?><?php 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>


    </main>

    <!-- Footer -->
    <footer class="bg-slate-900 text-slate-300 py-10 mt-auto border-t border-slate-800">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
                <div>
                    <h3 class="text-white text-lg font-bold mb-4 flex items-center gap-2">
                        <i class="fas fa-shield-alt text-alert"></i> ERCS
                    </h3>
                    <p class="text-sm text-slate-400">
                        Rapid emergency reporting and intelligent responder coordination. Saving lives through instant communication and real-time location tracking.
                    </p>
                </div>
                <div>
                    <h3 class="text-white text-lg font-bold mb-4">Quick Links</h3>
                    <ul class="space-y-2 text-sm">
                        <li><a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/emergency/report" class="hover:text-white transition-colors text-alert font-semibold">Report Emergency</a></li>
                        <li><a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/about" class="hover:text-white transition-colors">How it Works</a></li>
                        <li><a href="<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/login" class="hover:text-white transition-colors">Responder Login</a></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-white text-lg font-bold mb-4">Emergency Contacts</h3>
                    <ul class="space-y-2 text-sm text-slate-400">
                        <li><i class="fas fa-phone-alt mr-2 text-brandBlue-500"></i> Toll-Free: 112</li>
                        <li><i class="fas fa-ambulance mr-2 text-brandBlue-500"></i> Medical: 911</li>
                        <li><i class="fas fa-fire mr-2 text-brandBlue-500"></i> Fire Service: 101</li>
                    </ul>
                </div>
            </div>
            <div class="border-t border-slate-800 mt-8 pt-8 text-sm text-center text-slate-500">
                &copy; <?= htmlspecialchars(date('Y'), ENT_QUOTES, 'UTF-8') ?> Emergency Response Coordination System. All rights reserved.
            </div>
        </div>
    </footer>

    <!-- jQuery for seamless AJAX requests (Chat, Location updates) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    <!-- Global Layout Scripts -->
    <script>
        $(document).ready(function() {

            $('#mobile-menu-btn').on('click', function() {
                $('#mobile-menu').slideToggle('fast');
            });

            $.ajaxSetup({
                error: function(jqXHR, textStatus, errorThrown) {
                    let errorMessage = "An unexpected error occurred.";
                    if (jqXHR.responseJSON && jqXHR.responseJSON.message) {
                        errorMessage = jqXHR.responseJSON.message;
                    }


                    if (this.global !== false) {
                        Swal.fire({
                            icon: 'error',
                            title: 'System Error',
                            text: errorMessage,
                            confirmButtonColor: '#1e3a8a'
                        });
                    }
                }
            });
        });

        function showNotification(type, title, message) {
            Swal.fire({
                icon: type, // 'success', 'error', 'warning', 'info'
                title: title,
                text: message,
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 4000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer)
                    toast.addEventListener('mouseleave', Swal.resumeTimer)
                }
            });
        }
    </script>

    <!-- Coreflux Injected View Scripts (e.g. Google Maps, Chat scripts added via @addScript) -->
    <?= htmlspecialchars(Core\View::renderScripts(), ENT_QUOTES, 'UTF-8') ?>
<script>
$(document).ready(function() {

    $('#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');
        }
    });

    const $gpsStatus = $('#gps-status');
    const $submitBtn = $('#submitBtn');
    
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function(position) {

                $('#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>');

                $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) {

                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>');
    }

    $('#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: '<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>/emergency/report',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            success: function(response) {

                        let res = typeof response === 'string' ? JSON.parse(response) : response;
                        
                        if (res.status === 'success' && res.redirect) {
                            window.location.href = '<?= htmlspecialchars(APP_URL, ENT_QUOTES, 'UTF-8') ?>' + 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) {

                            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>
</body>
</html>