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

$driver_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$driver_id) {
    header('Location: browse_cars.php');
    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>Driver Profile - <?= htmlspecialchars(getBrandName()) ?></title>
    <script src="https://cdn.tailwindcss.com?plugins=forms,container-queries"></script>
    <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"/>
    <script src="../admin/includes/tailwind_config.js"></script>
    <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">Driver Profile</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 driver profile...</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">Driver 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>

        <!-- Driver Content -->
        <div id="driverContent" class="hidden">
            <!-- Driver Profile Card -->
            <div class="bg-white dark:bg-card-dark rounded-2xl p-6 shadow-sm border border-slate-100 dark:border-slate-800/50 mb-6">
                <div class="flex flex-col sm:flex-row items-center gap-6">
                    <div class="relative">
                        <div class="size-28 rounded-full bg-slate-200 dark:bg-slate-700 overflow-hidden border-4 border-primary/20">
                            <img id="driverImage" src="" alt="Driver" class="w-full h-full object-cover">
                        </div>
                        <div id="verifiedBadge" class="absolute -bottom-1 -right-1 bg-emerald-500 text-white p-1.5 rounded-full border-4 border-white dark:border-card-dark">
                            <span class="material-symbols-outlined text-sm fill-1">verified</span>
                        </div>
                    </div>
                    <div class="flex-1 text-center sm:text-left">
                        <h1 id="driverName" class="text-clamp-3xl font-black tracking-tight mb-1"></h1>
                        <p id="driverId" class="text-slate-500 dark:text-slate-400 text-clamp-sm mb-3"></p>
                        
                        <div class="flex flex-wrap items-center justify-center sm:justify-start gap-4">
                            <div class="flex items-center gap-1 text-rating-gold">
                                <span class="material-symbols-outlined text-clamp-base fill-1">star</span>
                                <span id="driverRating" class="font-bold text-clamp-lg">0.0</span>
                                <span id="reviewCount" class="text-slate-400 text-clamp-xs">(0 reviews)</span>
                            </div>
                            <span class="text-slate-300">|</span>
                            <div class="flex items-center gap-1 text-slate-600 dark:text-slate-400">
                                <span class="material-symbols-outlined text-sm">local_taxi</span>
                                <span id="totalTrips" class="text-sm font-medium">0 trips</span>
                            </div>
                            <span class="text-slate-300">|</span>
                            <div class="flex items-center gap-1 text-slate-600 dark:text-slate-400">
                                <span class="material-symbols-outlined text-sm">schedule</span>
                                <span id="experience" class="text-sm font-medium">0 years exp</span>
                            </div>
                        </div>
                    </div>
                    <div id="statusBadge" class="px-4 py-2 rounded-full text-sm font-bold uppercase">
                        Active
                    </div>
                </div>
            </div>

            <!-- Stats Grid -->
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4 mb-6">
                <div class="bg-white dark:bg-card-dark rounded-xl p-4 text-center border border-slate-100 dark:border-slate-800/50">
                    <p class="text-clamp-xs text-slate-500 uppercase font-bold mb-1">Vehicle Rating</p>
                    <div class="flex items-center justify-center gap-1 text-rating-gold">
                        <span class="material-symbols-outlined text-clamp-xs fill-1">star</span>
                        <span id="avgVehicleRating" class="text-clamp-xl font-bold">0.0</span>
                    </div>
                </div>
                <div class="bg-white dark:bg-card-dark rounded-xl p-4 text-center border border-slate-100 dark:border-slate-800/50">
                    <p class="text-clamp-xs text-slate-500 uppercase font-bold mb-1">Service Rating</p>
                    <div class="flex items-center justify-center gap-1 text-rating-gold">
                        <span class="material-symbols-outlined text-clamp-xs fill-1">star</span>
                        <span id="avgServiceRating" class="text-clamp-xl font-bold">0.0</span>
                    </div>
                </div>
                <div class="bg-white dark:bg-card-dark rounded-xl p-4 text-center border border-slate-100 dark:border-slate-800/50">
                    <p class="text-xs text-slate-500 uppercase font-bold mb-1">Punctuality</p>
                    <div class="flex items-center justify-center gap-1 text-emerald-500">
                        <span class="material-symbols-outlined text-sm fill-1">schedule</span>
                        <span class="text-xl font-bold">98%</span>
                    </div>
                </div>
                <div class="bg-white dark:bg-card-dark rounded-xl p-4 text-center border border-slate-100 dark:border-slate-800/50">
                    <p class="text-xs text-slate-500 uppercase font-bold mb-1">Response</p>
                    <div class="flex items-center justify-center gap-1 text-primary">
                        <span class="material-symbols-outlined text-sm fill-1">chat</span>
                        <span class="text-xl font-bold">100%</span>
                    </div>
                </div>
            </div>

            <!-- Reviews Section -->
            <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 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">
                    <p class="text-slate-500 text-center py-4">No reviews yet for this driver.</p>
                </div>
            </div>
        </div>
    </main>

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

        async function loadDriverDetails() {
            if (!driverId) {
                showError();
                return;
            }

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

                if (data.success && data.data && data.data.driver) {
                    displayDriver(data.data.driver, data.data.reviews);
                } else {
                    showError();
                }
            } catch (error) {
                console.error('Error loading driver:', error);
                showError();
            }
        }

        function displayDriver(driver, reviews) {
            document.getElementById('loadingState').classList.add('hidden');
            document.getElementById('driverContent').classList.remove('hidden');

            document.title = `${driver.first_name} ${driver.last_name} - Driver Profile`;
            
            // Driver Image
            const driverImage = document.getElementById('driverImage');
            driverImage.src = `https://ui-avatars.com/api/?name=${encodeURIComponent(driver.first_name + '+' + driver.last_name)}&background=random&size=256`;
            
            // Driver Info
            document.getElementById('driverName').textContent = `${driver.first_name} ${driver.last_name}`;
            document.getElementById('driverId').textContent = `ID: ${driver.employee_id || 'N/A'}`;
            document.getElementById('driverRating').textContent = parseFloat(driver.rating || 0).toFixed(1);
            document.getElementById('reviewCount').textContent = `(${driver.total_reviews || 0} reviews)`;
            document.getElementById('totalTrips').textContent = `${driver.total_trips || 0} trips`;
            document.getElementById('experience').textContent = `${driver.experience_years || 0} years exp`;
            document.getElementById('avgRatingDisplay').textContent = parseFloat(driver.rating || 0).toFixed(1);

            // Status Badge
            const statusBadge = document.getElementById('statusBadge');
            if (driver.status === 'active') {
                statusBadge.className = 'px-4 py-2 rounded-full text-sm font-bold uppercase bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300';
                statusBadge.textContent = 'Active';
            } else {
                statusBadge.className = 'px-4 py-2 rounded-full text-sm font-bold uppercase bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-400';
                statusBadge.textContent = driver.status || 'Inactive';
            }

            // Calculate average ratings
            if (reviews && reviews.length > 0) {
                const avgVehicle = reviews.reduce((sum, r) => sum + parseFloat(r.vehicle_rating || 0), 0) / reviews.length;
                const avgService = reviews.reduce((sum, r) => sum + parseFloat(r.service_rating || 0), 0) / reviews.length;
                
                document.getElementById('avgVehicleRating').textContent = avgVehicle.toFixed(1);
                document.getElementById('avgServiceRating').textContent = avgService.toFixed(1);
            }

            // Display Reviews
            displayReviews(reviews);
            checkReviewEligibility(driver.id);
        }

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

            try {
                const response = await fetch(`../api/reviews.php?action=check_eligibility&driver_id=${dId}&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);
            }
        }

        function displayReviews(reviews) {
            const reviewsList = document.getElementById('reviewsList');
            
            if (!reviews || reviews.length === 0) {
                reviewsList.innerHTML = '<p class="text-slate-500 text-center py-4">No reviews yet for this driver.</p>';
                return;
            }

            reviewsList.innerHTML = reviews.map(review => {
                const driverStars = Array(5).fill(0).map((_, i) => `
                    <span class="material-symbols-outlined text-[14px] ${i < Math.floor(review.driver_rating || 0) ? '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>
                    
                    <!-- Driver Rating & Comment -->
                    <div class="mb-2">
                        <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 Service</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>
                    
                    <!-- Vehicle Info -->
                    ${review.make ? `
                    <div class="mt-3 pt-3 border-t border-slate-100 dark:border-slate-800">
                        <div class="flex items-center gap-2 text-xs text-slate-500">
                            <span class="material-symbols-outlined text-[14px]">directions_car</span>
                            <span>Rented: ${review.make} ${review.model}</span>
                        </div>
                    </div>
                    ` : ''}
                </div>
                `;
            }).join('');
        }

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

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