<?php
if (!file_exists(__DIR__ . '/../admin/includes/config.php')) {
    header("Location: ../admin/install.php");
    exit;
}
require_once '../admin/includes/config.php';
require_once '../admin/includes/branding.php';
?>
<!DOCTYPE html>
<html class="dark" lang="en">
<head>
    <meta charset="utf-8"/>
    <meta content="width=device-width, initial-scale=1.0" name="viewport"/>
    <title>Vehicle Details - <?= htmlspecialchars(getBrandName()) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&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"/>
    <?php
    $base_path = "../admin/";
    include '../admin/includes/tailwind_config_include.php';
    ?>
    <link rel="stylesheet" href="../admin/includes/responsive.css">
    <style>
        .hide-scrollbar::-webkit-scrollbar { display: none; }
        .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
    </style>
</head>
<body class="bg-background-light dark:bg-background-dark text-slate-900 dark:text-white min-h-screen pb-24">
    <header class="sticky top-0 z-50 bg-background-light/80 dark:bg-background-dark/80 backdrop-blur-md border-b border-slate-200 dark:border-slate-800">
        <div class="flex items-center justify-between max-w-7xl mx-auto p-4">
            <a href="javascript:history.back()" class="flex items-center justify-center size-10 rounded-full hover:bg-slate-200 dark:hover:bg-slate-800 transition-colors">
                <span class="material-symbols-outlined">arrow_back</span>
            </a>
            <h2 class="font-bold text-lg flex-1 text-center">Vehicle Details</h2>
            <div class="size-10"></div>
        </div>
    </header>

    <main class="max-w-4xl mx-auto p-4">
        <!-- Loading State -->
        <div id="loadingState" class="py-20 text-center">
            <div class="inline-block h-12 w-12 animate-spin rounded-full border-4 border-solid border-primary border-r-transparent"></div>
            <p class="mt-4 text-slate-500">Loading vehicle details...</p>
        </div>

        <!-- Error State -->
        <div id="errorState" class="py-20 text-center hidden">
            <span class="material-symbols-outlined text-6xl text-slate-400 mb-4">error_outline</span>
            <p class="text-slate-500 mb-4">Vehicle not found or an error occurred.</p>
            <a href="browse_cars.php" class="px-6 py-2 bg-primary text-white rounded-lg font-semibold">Back to Browse</a>
        </div>

        <!-- Vehicle Content -->
        <div id="vehicleContent" class="hidden">
            <!-- Image Gallery -->
            <div class="relative rounded-2xl overflow-hidden aspect-video bg-slate-200 dark:bg-slate-800 mb-6 shadow-lg">
                <img id="mainImage" src="" alt="Vehicle Image" class="w-full h-full object-cover">
                <div id="featuredBadge" class="absolute top-4 left-4 hidden bg-white/90 dark:bg-black/80 backdrop-blur-sm px-3 py-1.5 rounded-full border border-rating-gold/30 shadow-sm flex items-center gap-1">
                    <span class="material-symbols-outlined text-[18px] text-rating-gold fill-1">star</span>
                    <span class="text-xs font-bold text-slate-800 dark:text-white uppercase tracking-tight">Top Rated</span>
                </div>
                <button id="favoriteBtn" class="absolute top-4 right-4 size-12 bg-white/90 dark:bg-black/80 backdrop-blur-sm rounded-full flex items-center justify-center shadow-lg transition-all active:scale-90">
                    <span class="material-symbols-outlined text-2xl">favorite</span>
                </button>
            </div>

            <!-- Thumbnail List (if multiple images) -->
            <div id="thumbnailList" class="flex gap-2 mb-6 overflow-x-auto pb-2 hide-scrollbar"></div>

            <div class="bg-white dark:bg-card-dark rounded-2xl p-6 shadow-sm border border-slate-100 dark:border-slate-800/50">
                <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
                    <div>
                        <p id="vehicleType" class="text-primary text-clamp-sm font-bold uppercase tracking-widest mb-1"></p>
                        <h1 id="vehicleName" class="text-clamp-3xl font-black tracking-tight heading-responsive"></h1>
                        <div class="flex items-center gap-2 mt-1">
                            <div class="flex items-center gap-0.5 text-rating-gold">
                                <span class="material-symbols-outlined text-clamp-base fill-1">star</span>
                                <span id="vehicleRating" class="text-clamp-sm font-bold">0.0</span>
                            </div>
                            <span class="text-slate-400">•</span>
                            <span id="vehicleReviewCount" class="text-clamp-xs text-slate-500 dark:text-slate-400 font-medium">0 reviews</span>
                        </div>
                        <p id="vehicleYear" class="text-slate-500 dark:text-slate-400 mt-2 text-clamp-sm"></p>
                    </div>
                    <div class="text-left md:text-right">
                        <p class="text-slate-500 text-clamp-xs uppercase font-bold tracking-wider">Daily Rate</p>
                        <p class="text-clamp-3xl font-black text-primary"><span id="vehiclePrice"></span><span class="text-clamp-sm font-normal text-slate-500">/day</span></p>
                    </div>
                </div>

                <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-8">
                    <div class="flex flex-col items-center justify-center p-4 rounded-xl bg-slate-50 dark:bg-background-dark border border-slate-100 dark:border-slate-800">
                        <span class="material-symbols-outlined text-primary mb-2">settings_input_component</span>
                        <span class="text-xs text-slate-500 uppercase font-bold">Transmission</span>
                        <span id="vehicleTransmission" class="text-sm font-bold mt-1"></span>
                    </div>
                    <div class="flex flex-col items-center justify-center p-4 rounded-xl bg-slate-50 dark:bg-background-dark border border-slate-100 dark:border-slate-800">
                        <span class="material-symbols-outlined text-primary mb-2">local_gas_station</span>
                        <span class="text-xs text-slate-500 uppercase font-bold">Fuel Type</span>
                        <span id="vehicleFuel" class="text-sm font-bold mt-1"></span>
                    </div>
                    <div class="flex flex-col items-center justify-center p-4 rounded-xl bg-slate-50 dark:bg-background-dark border border-slate-100 dark:border-slate-800">
                        <span class="material-symbols-outlined text-primary mb-2">group</span>
                        <span class="text-xs text-slate-500 uppercase font-bold">Seats</span>
                        <span id="vehicleSeats" class="text-sm font-bold mt-1"></span>
                    </div>
                    <div class="flex flex-col items-center justify-center p-4 rounded-xl bg-slate-50 dark:bg-background-dark border border-slate-100 dark:border-slate-800">
                        <span class="material-symbols-outlined text-primary mb-2">work</span>
                        <span class="text-xs text-slate-500 uppercase font-bold">Luggage</span>
                        <span id="vehicleLuggage" class="text-sm font-bold mt-1"></span>
                    </div>
                </div>

                <div class="mb-8">
                    <h3 class="text-lg font-bold mb-3">Description</h3>
                    <p id="vehicleDescription" class="text-slate-600 dark:text-slate-300 leading-relaxed"></p>
                </div>

                <div id="featuresSection" class="mb-8 hidden">
                    <h3 class="text-lg font-bold mb-3">Key Features</h3>
                    <div id="featuresList" class="grid grid-cols-1 sm:grid-cols-2 gap-2"></div>
                </div>

                <a id="bookNowBtn" href="#" class="block w-full text-center py-4 bg-primary text-white font-bold rounded-xl shadow-lg shadow-primary/25 hover:bg-primary/90 transition-all active:scale-[0.98]">
                    Book This Car Now
                </a>
            </div>

            <!-- Reviews Section -->
            <div class="mt-8 bg-white dark:bg-card-dark rounded-2xl p-6 shadow-sm border border-slate-100 dark:border-slate-800/50">
                <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
                    <h3 class="text-xl font-bold">Customer Reviews</h3>
                    <div class="flex items-center gap-4">
                        <div id="overallRatingSection" class="flex items-center gap-2">
                            <span id="avgRatingDisplay" class="text-2xl font-black">0.0</span>
                            <div class="flex text-rating-gold">
                                <span class="material-symbols-outlined fill-1">star</span>
                            </div>
                        </div>
                        <div id="rateNowContainer" class="hidden">
                            <a id="rateNowBtn" href="#" class="px-4 py-2 bg-primary text-white text-sm font-bold rounded-lg shadow-md hover:bg-primary/90 transition-all">Rate Now</a>
                        </div>
                    </div>
                </div>

                <div id="reviewsList" class="space-y-6">
                    <!-- Reviews will be loaded here -->
                    <p class="text-slate-500 text-center py-4">No reviews yet for this vehicle.</p>
                </div>
            </div>
        </div>
    </main>

    <script>
        const urlParams = new URLSearchParams(window.location.search);
        const vehicleId = urlParams.get('id');

        async function loadVehicleDetails() {
            if (!vehicleId) {
                showError();
                return;
            }

            try {
                const response = await fetch(`../api/vehicles.php?id=${vehicleId}`);
                const data = await response.json();

                if (data.success && data.data && data.data.length > 0) {
                    displayVehicle(data.data[0]);
                } else {
                    showError();
                }
            } catch (error) {
                console.error('Error loading vehicle:', error);
                showError();
            }
        }

        async function toggleFavorite(vehicleId, button) {
            try {
                const response = await fetch('../api/favorites.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ vehicle_id: vehicleId })
                });
                
                if (response.status === 401) {
                    window.location.href = 'user_authentication.html';
                    return;
                }
                
                const data = await response.json();
                if (data.success) {
                    const icon = button.querySelector('.material-symbols-outlined');
                    if (data.is_favorited) {
                        button.classList.add('text-rose-500');
                        icon.classList.add('fill-1');
                    } else {
                        button.classList.remove('text-rose-500');
                        icon.classList.remove('fill-1');
                    }
                }
            } catch (error) {
                console.error('Error toggling favorite:', error);
            }
        }

        function displayVehicle(vehicle) {
            document.getElementById('loadingState').classList.add('hidden');
            document.getElementById('vehicleContent').classList.remove('hidden');

            const favoriteBtn = document.getElementById('favoriteBtn');
            if (vehicle.is_favorited) {
                favoriteBtn.classList.add('text-rose-500');
                favoriteBtn.querySelector('.material-symbols-outlined').classList.add('fill-1');
            }
            favoriteBtn.onclick = () => toggleFavorite(vehicle.id, favoriteBtn);

            document.title = `${vehicle.make} ${vehicle.model} - <?= htmlspecialchars(getBrandName()) ?>`;
            document.getElementById('vehicleName').textContent = `${vehicle.make} ${vehicle.model}`;
            document.getElementById('vehicleRating').textContent = parseFloat(vehicle.rating || 0).toFixed(1);
            document.getElementById('vehicleReviewCount').textContent = `${vehicle.total_reviews || 0} reviews`;
            document.getElementById('avgRatingDisplay').textContent = parseFloat(vehicle.rating || 0).toFixed(1);
            document.getElementById('vehicleType').textContent = vehicle.vehicle_type;
            document.getElementById('vehicleYear').textContent = `${vehicle.year} • ${vehicle.color}`;
            document.getElementById('vehiclePrice').textContent = `₱${parseFloat(vehicle.daily_rate).toFixed(2)}`;
            document.getElementById('vehicleTransmission').textContent = vehicle.transmission;
            document.getElementById('vehicleFuel').textContent = vehicle.fuel_type;
            document.getElementById('vehicleSeats').textContent = `${vehicle.seats} People`;
            document.getElementById('vehicleLuggage').textContent = `${vehicle.luggage_capacity || 2} Bags`;
            document.getElementById('vehicleDescription').textContent = vehicle.description || 'No description available for this vehicle.';

            if (vehicle.is_featured) {
                document.getElementById('featuredBadge').classList.remove('hidden');
            }

            // Images
            const images = vehicle.images || [];
            const mainImage = document.getElementById('mainImage');
            mainImage.src = vehicle.display_image;

            if (images.length > 1) {
                const thumbContainer = document.getElementById('thumbnailList');
                images.forEach(img => {
                    const thumb = document.createElement('div');
                    thumb.className = 'shrink-0 size-20 rounded-lg overflow-hidden border-2 border-transparent cursor-pointer hover:border-primary transition-all';
                    thumb.innerHTML = `<img src="${img}" class="w-full h-full object-cover">`;
                    thumb.onclick = () => mainImage.src = img;
                    thumbContainer.appendChild(thumb);
                });
            }

            // Add rear camera status to features list
            document.getElementById('featuresSection').classList.remove('hidden');
            const list = document.getElementById('featuresList');
            const cameraItem = document.createElement('div');
            cameraItem.className = 'flex items-center gap-2 text-slate-600 dark:text-slate-300';
            if (vehicle.has_rear_camera == 1) {
                cameraItem.innerHTML = `<span class="material-symbols-outlined text-emerald-500 text-sm">videocam</span> <span class="text-sm font-bold">With Rear View Camera</span>`;
            } else {
                cameraItem.innerHTML = `<span class="material-symbols-outlined text-slate-400 text-sm">videocam_off</span> <span class="text-sm">Without Rear View Camera</span>`;
            }
            list.appendChild(cameraItem);

            // Features
            const features = vehicle.features;
            if (features) {
                let featuresArray = [];
                try {
                    featuresArray = typeof features === 'string' ? JSON.parse(features) : features;
                } catch(e) {}

                if (Array.isArray(featuresArray) && featuresArray.length > 0) {
                    document.getElementById('featuresSection').classList.remove('hidden');
                    const list = document.getElementById('featuresList');
                    featuresArray.forEach(f => {
                        const item = document.createElement('div');
                        item.className = 'flex items-center gap-2 text-slate-600 dark:text-slate-300';
                        item.innerHTML = `<span class="material-symbols-outlined text-primary text-sm">check_circle</span> <span class="text-sm">${f}</span>`;
                        list.appendChild(item);
                    });
                }
            }

            document.getElementById('bookNowBtn').href = `checkout_summary.html?vehicle=${vehicle.id}`;

            // Load reviews for this vehicle
            loadReviews(vehicle.id);
            checkReviewEligibility(vehicle.id);
        }

        async function checkReviewEligibility(vId) {
            const user = JSON.parse(localStorage.getItem('user') || 'null');
            if (!user) return;

            try {
                const response = await fetch(`../api/reviews.php?action=check_eligibility&vehicle_id=${vId}&user_id=${user.user_id}`);
                const data = await response.json();

                if (data.success && data.can_review) {
                    const container = document.getElementById('rateNowContainer');
                    const btn = document.getElementById('rateNowBtn');
                    btn.href = `submit_rating_review.html?booking_id=${data.booking_id}`;
                    container.classList.remove('hidden');
                }
            } catch (error) {
                console.error('Error checking review eligibility:', error);
            }
        }

        async function loadReviews(vId) {
            try {
                const response = await fetch(`../api/reviews.php?vehicle_id=${vId}`);
                const data = await response.json();

                if (data.success && data.data && data.data.length > 0) {
                    const reviewsList = document.getElementById('reviewsList');
                    reviewsList.innerHTML = data.data.map(review => {
                        const vehicleStars = Array(5).fill(0).map((_, i) => `
                            <span class="material-symbols-outlined text-[14px] ${i < Math.floor(review.vehicle_rating || 0) ? 'fill-1' : ''}">star</span>
                        `).join('');
                        
                        const driverStars = review.driver_rating ? Array(5).fill(0).map((_, i) => `
                            <span class="material-symbols-outlined text-[14px] ${i < Math.floor(review.driver_rating) ? 'fill-1' : ''}">star</span>
                        `).join('') : '';
                        
                        return `
                        <div class="border-b border-slate-100 dark:border-slate-800 pb-6 last:border-0 last:pb-0">
                            <div class="flex items-center gap-3 mb-3">
                                <div class="size-10 rounded-full bg-slate-200 dark:bg-slate-700 overflow-hidden">
                                    <img src="${review.profile_image || 'https://ui-avatars.com/api/?name=' + encodeURIComponent(review.first_name || 'User')}" alt="User" class="w-full h-full object-cover">
                                </div>
                                <div class="flex-1">
                                    <h4 class="font-bold text-sm">${review.first_name || 'Anonymous'} ${review.last_name || ''}</h4>
                                    <p class="text-xs text-slate-500">${new Date(review.created_at).toLocaleDateString('en-US', {month: 'long', day: 'numeric', year: 'numeric'})}</p>
                                </div>
                                <div class="flex items-center gap-1 text-rating-gold">
                                    <span class="material-symbols-outlined text-[16px] fill-1">star</span>
                                    <span class="font-bold text-sm">${parseFloat(review.overall_rating || 0).toFixed(1)}</span>
                                </div>
                            </div>
                            
                            <!-- Vehicle Rating -->
                            <div class="mb-3">
                                <div class="flex items-center gap-2 mb-1">
                                    <span class="material-symbols-outlined text-[16px] text-slate-400">directions_car</span>
                                    <span class="text-xs text-slate-500 font-medium">Vehicle</span>
                                    <div class="flex items-center gap-0.5 text-rating-gold">${vehicleStars}</div>
                                </div>
                                ${review.vehicle_comment ? `<p class="text-sm text-slate-600 dark:text-slate-300 italic ml-6">"${review.vehicle_comment}"</p>` : ''}
                            </div>
                            
                            <!-- Driver Rating (if exists) -->
                            ${review.driver_rating ? `
                            <div class="mb-3">
                                <div class="flex items-center gap-2 mb-1">
                                    <span class="material-symbols-outlined text-[16px] text-slate-400">person</span>
                                    <span class="text-xs text-slate-500 font-medium">Driver</span>
                                    <div class="flex items-center gap-0.5 text-rating-gold">${driverStars}</div>
                                </div>
                                ${review.driver_comment ? `<p class="text-sm text-slate-600 dark:text-slate-300 italic ml-6">"${review.driver_comment}"</p>` : ''}
                            </div>
                            ` : ''}
                        </div>
                    `}).join('');
                }
            } catch (error) {
                console.error('Error loading reviews:', error);
            }
        }

        function showError() {
            document.getElementById('loadingState').classList.add('hidden');
            document.getElementById('errorState').classList.remove('hidden');
        }

        loadVehicleDetails();
    </script>
    <?php include '../admin/includes/floating_chat_include.php'; ?>
</body>
</html>
