<?php
require_once '../admin/includes/config.php';
require_once '../admin/includes/branding.php';

// Session check
if (!isset($_SESSION['user_id'])) {
    header("Location: user_authentication.html");
    exit;
}
?>
<!DOCTYPE html>
<html class="dark" lang="en">
<head>
    <meta charset="utf-8"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>Book a Delivery - <?= htmlspecialchars(getBrandName()) ?></title>
    <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400,500,600,700&display=swap" rel="stylesheet"/>
    <link href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:wght,FILL@100..700,0..1&display=swap" rel="stylesheet"/>
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>
    <script src="../admin/includes/tailwind_config.js"></script>
    <link rel="stylesheet" href="../admin/includes/responsive.css">
</head>
<body class="font-display bg-background-light dark:bg-background-dark text-slate-900 dark:text-white antialiased min-h-screen pb-32">
    <div class="relative flex w-full flex-col overflow-x-hidden">
        <header class="flex items-center bg-background-light dark:bg-background-dark p-4 sticky top-0 z-50 border-b border-slate-200 dark:border-slate-800">
            <div class="responsive-container flex items-center w-full">
                <a href="index.php" class="text-primary flex size-10 items-center justify-center rounded-full hover:bg-primary/10 transition-colors">
                    <span class="material-symbols-outlined text-xl">arrow_back</span>
                </a>
                <h2 class="text-slate-900 dark:text-white text-clamp-lg font-bold leading-tight tracking-tight flex-1 text-center pr-10">Book a Delivery</h2>
            </div>
        </header>

        <main class="responsive-container w-full p-4 space-y-8">
            <!-- Step 1: Select Delivery Service -->
            <section>
                <h3 class="text-slate-900 dark:text-white text-clamp-xl font-bold leading-tight tracking-tight mb-4">1. Choose Delivery Service</h3>
                <div id="servicesList" class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- Services will be loaded here -->
                    <div class="animate-pulse bg-white dark:bg-[#192633] p-6 rounded-2xl border border-slate-200 dark:border-slate-800">
                        <div class="h-6 bg-slate-200 dark:bg-slate-800 rounded w-1/2 mb-2"></div>
                        <div class="h-4 bg-slate-200 dark:bg-slate-800 rounded w-3/4"></div>
                    </div>
                </div>
            </section>

            <!-- Step 2: Pickup & Dropoff Details -->
            <section id="locationSection" class="hidden space-y-6">
                <h3 class="text-slate-900 dark:text-white text-clamp-xl font-bold leading-tight tracking-tight mb-4">2. Delivery Details</h3>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <!-- Pickup -->
                    <div class="space-y-4">
                        <div class="flex items-center gap-2 text-primary">
                            <span class="material-symbols-outlined">location_on</span>
                            <h4 class="font-bold">Pickup Information</h4>
                        </div>
                        <div class="space-y-3">
                            <input id="pickupLocation" type="text" class="w-full rounded-xl border border-slate-300 dark:border-[#324d67] bg-white dark:bg-[#192633] py-3 px-4 text-slate-900 dark:text-white" placeholder="Exact Pickup Address">
                            <textarea id="pickupDescription" rows="2" class="w-full rounded-xl border border-slate-300 dark:border-[#324d67] bg-white dark:bg-[#192633] py-3 px-4 text-slate-900 dark:text-white" placeholder="Pickup instructions (e.g. Look for blue house)"></textarea>
                            <div id="pickupMap" class="w-full h-48 rounded-xl border border-slate-200 dark:border-slate-800 z-0"></div>
                            <input type="hidden" id="pickupLat">
                            <input type="hidden" id="pickupLng">
                        </div>
                    </div>

                    <!-- Dropoff -->
                    <div class="space-y-4">
                        <div class="flex items-center gap-2 text-rose-500">
                            <span class="material-symbols-outlined">location_on</span>
                            <h4 class="font-bold">Dropoff Information</h4>
                        </div>
                        <div class="space-y-3">
                            <input id="dropoffLocation" type="text" class="w-full rounded-xl border border-slate-300 dark:border-[#324d67] bg-white dark:bg-[#192633] py-3 px-4 text-slate-900 dark:text-white" placeholder="Exact Dropoff Address">
                            <textarea id="dropoffDescription" rows="2" class="w-full rounded-xl border border-slate-300 dark:border-[#324d67] bg-white dark:bg-[#192633] py-3 px-4 text-slate-900 dark:text-white" placeholder="Dropoff instructions (e.g. Leave at front desk)"></textarea>
                            <div id="dropoffMap" class="w-full h-48 rounded-xl border border-slate-200 dark:border-slate-800 z-0"></div>
                            <input type="hidden" id="dropoffLat">
                            <input type="hidden" id="dropoffLng">
                        </div>
                    </div>
                </div>

                <div class="space-y-4">
                    <h4 class="font-bold">Delivery Date & Time</h4>
                    <input id="deliveryDate" type="datetime-local" class="w-full rounded-xl border border-slate-300 dark:border-[#324d67] bg-white dark:bg-[#192633] py-3 px-4 text-slate-900 dark:text-white">
                </div>
            </section>

            <!-- Summary & Proceed -->
            <section id="summarySection" class="hidden">
                <div class="bg-primary/10 rounded-2xl p-6 border-2 border-primary border-dashed">
                    <div class="flex justify-between items-center">
                        <div>
                            <p class="text-primary text-xs font-bold uppercase tracking-widest">Selected Service</p>
                            <h4 id="selectedServiceName" class="text-xl font-bold">---</h4>
                        </div>
                        <div class="text-right">
                            <p class="text-slate-500 text-xs uppercase font-bold">Total Amount</p>
                            <p id="totalAmount" class="text-2xl font-black text-primary">₱0.00</p>
                        </div>
                    </div>
                </div>
            </section>
        </main>

        <footer class="fixed bottom-0 left-0 right-0 bg-white/80 dark:bg-background-dark/80 backdrop-blur-md p-4 border-t border-slate-200 dark:border-slate-800 z-50">
            <div class="responsive-container">
                <button id="submitBooking" disabled class="w-full bg-primary disabled:opacity-50 text-white font-bold py-4 rounded-xl shadow-lg shadow-primary/20 flex items-center justify-center gap-2">
                    <span class="material-symbols-outlined">bolt</span>
                    Confirm Delivery Booking
                </button>
            </div>
        </footer>
    </div>

    <script>
        let selectedService = null;
        let pickupMap, dropoffMap, pickupMarker, dropoffMarker;

        async function loadServices() {
            try {
                const response = await fetch('../api/delivery_services.php');
                const data = await response.json();

                const list = document.getElementById('servicesList');
                if (data.success && data.data.length > 0) {
                    list.innerHTML = data.data.map(service => `
                        <div onclick='selectService(${JSON.stringify(service)})' id="service-${service.id}" class="service-card group cursor-pointer bg-white dark:bg-[#192633] p-6 rounded-2xl border-2 border-slate-200 dark:border-slate-800 hover:border-primary transition-all">
                            <div class="flex justify-between items-start mb-2">
                                <h4 class="font-bold text-lg group-hover:text-primary">${service.service_name}</h4>
                                <p class="font-black text-primary">₱${parseFloat(service.amount).toFixed(2)}</p>
                            </div>
                            <p class="text-sm text-slate-500 dark:text-slate-400">${service.description}</p>
                        </div>
                    `).join('');
                } else {
                    list.innerHTML = `
                        <div class="col-span-full bg-yellow-50 dark:bg-yellow-900/20 p-8 rounded-2xl border border-yellow-200 dark:border-yellow-800 text-center">
                            <span class="material-symbols-outlined text-4xl text-yellow-500 mb-2">error</span>
                            <h4 class="font-bold text-lg text-yellow-800 dark:text-yellow-500">No services available</h4>
                            <p class="text-yellow-700 dark:text-yellow-600/80 mb-4">Please contact admin to setup delivery services.</p>
                            <button onclick="loadServices()" class="text-primary font-bold flex items-center justify-center gap-2 mx-auto">
                                <span class="material-symbols-outlined">refresh</span> Retry
                            </button>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('Error loading services:', error);
            }
        }

        function selectService(service) {
            selectedService = service;

            // UI Updates
            document.querySelectorAll('.service-card').forEach(c => c.classList.remove('border-primary', 'bg-primary/5'));
            document.getElementById(`service-${service.id}`).classList.add('border-primary', 'bg-primary/5');

            document.getElementById('locationSection').classList.remove('hidden');
            document.getElementById('summarySection').classList.remove('hidden');
            document.getElementById('submitBooking').disabled = false;

            document.getElementById('selectedServiceName').textContent = service.service_name;
            document.getElementById('totalAmount').textContent = `₱${parseFloat(service.amount).toFixed(2)}`;

            // Initialize maps if not done
            if (!pickupMap) initMaps();
        }

        function initMaps() {
            const manila = [14.5995, 120.9842];

            pickupMap = L.map('pickupMap').setView(manila, 13);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(pickupMap);
            pickupMarker = L.marker(manila, {draggable: true}).addTo(pickupMap);

            dropoffMap = L.map('dropoffMap').setView(manila, 13);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(dropoffMap);
            dropoffMarker = L.marker(manila, {draggable: true}).addTo(dropoffMap);

            const updateCoords = (marker, latId, lngId) => {
                const pos = marker.getLatLng();
                document.getElementById(latId).value = pos.lat;
                document.getElementById(lngId).value = pos.lng;
            };

            pickupMarker.on('dragend', () => updateCoords(pickupMarker, 'pickupLat', 'pickupLng'));
            dropoffMarker.on('dragend', () => updateCoords(dropoffMarker, 'dropoffLat', 'dropoffLng'));

            updateCoords(pickupMarker, 'pickupLat', 'pickupLng');
            updateCoords(dropoffMarker, 'dropoffLat', 'dropoffLng');

            setTimeout(() => {
                pickupMap.invalidateSize();
                dropoffMap.invalidateSize();
            }, 100);
        }

        document.getElementById('submitBooking').addEventListener('click', async function() {
            const btn = this;
            const payload = {
                booking_type: 'delivery',
                delivery_service_id: selectedService.id,
                pickup_location: document.getElementById('pickupLocation').value,
                pickup_description: document.getElementById('pickupDescription').value,
                pickup_latitude: document.getElementById('pickupLat').value,
                pickup_longitude: document.getElementById('pickupLng').value,
                dropoff_location: document.getElementById('dropoffLocation').value,
                dropoff_description: document.getElementById('dropoffDescription').value,
                dropoff_latitude: document.getElementById('dropoffLat').value,
                dropoff_longitude: document.getElementById('dropoffLng').value,
                pickup_date: document.getElementById('deliveryDate').value,
                dropoff_date: document.getElementById('deliveryDate').value, // Use same for delivery
                user_id: <?= $_SESSION['user_id'] ?>
            };

            if (!payload.pickup_location || !payload.dropoff_location || !payload.pickup_date) {
                alert('Please fill in all required fields');
                return;
            }

            btn.disabled = true;
            btn.innerHTML = 'Creating Booking...';

            try {
                const response = await fetch('../api/bookings.php', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify(payload)
                });
                const data = await response.json();

                if (data.success) {
                    window.location.href = `payment_proof_upload.php?booking_id=${data.data.booking_id}`;
                } else {
                    alert(data.error || 'Booking failed');
                    btn.disabled = false;
                    btn.innerHTML = 'Confirm Delivery Booking';
                }
            } catch (error) {
                console.error('Booking error:', error);
                btn.disabled = false;
                btn.innerHTML = 'Confirm Delivery Booking';
            }
        });

        // Set default date to now
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        document.getElementById('deliveryDate').value = now.toISOString().slice(0, 16);
        document.getElementById('deliveryDate').min = now.toISOString().slice(0, 16);

        loadServices();
    </script>
</body>
</html>
