<?php
require_once 'config/config.php';

// Get featured cars (special offers)
try {
    $stmt = $db->query("
        SELECT c.*, 
               (SELECT image_path FROM car_images WHERE car_id = c.id AND is_primary = 1 LIMIT 1) as primary_image,
               (SELECT GROUP_CONCAT(image_path ORDER BY display_order SEPARATOR '|') FROM car_images WHERE car_id = c.id) as all_images
        FROM cars c 
        WHERE c.featured = 1 AND c.status = 'available'
        ORDER BY c.created_at DESC
    ");
    $featuredCars = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Error fetching featured cars: " . $e->getMessage());
    $featuredCars = [];
}

$pageTitle = 'Special Offers';
include 'includes/header.php';
?>

<style>
.car-gallery {
    transition: transform 0.5s ease;
}
</style>

<!-- Hero Section -->
<section class="bg-gradient-to-r from-primary-blue to-blue-800 text-white py-16">
    <div class="container mx-auto px-4 text-center">
        <h1 class="text-4xl md:text-5xl font-bold mb-4">⭐ Special Offers</h1>
        <p class="text-xl">Featured Vehicles with Exclusive Deals</p>
    </div>
</section>

<!-- Featured Cars Grid -->
<section class="py-12">
    <div class="container mx-auto px-4">
        <?php if (empty($featuredCars)): ?>
            <div class="bg-white rounded-lg shadow-md p-12 text-center max-w-2xl mx-auto">
                <div class="text-6xl mb-4">🚗</div>
                <h3 class="text-2xl font-bold text-gray-800 mb-2">No Special Offers Available</h3>
                <p class="text-gray-600 mb-6">Check back soon for exclusive deals on quality vehicles.</p>
                <a href="<?php echo SITE_URL; ?>/cars-for-sale.html" class="inline-block bg-primary-blue text-white px-6 py-3 rounded-lg font-semibold hover:bg-opacity-90 transition">
                    View All Cars
                </a>
            </div>
        <?php else: ?>
            <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php foreach ($featuredCars as $car): 
                    $images = $car['all_images'] ? explode('|', $car['all_images']) : [];
                ?>
                <a href="car-details.php?id=<?php echo $car['id']; ?>" class="block bg-white rounded-xl shadow-lg hover:shadow-2xl transition-all">
                    <!-- Car Image Gallery -->
                    <div class="relative h-56 overflow-hidden rounded-t-xl group">
                        <?php if (!empty($images)): ?>
                            <div class="flex transition-transform duration-500 h-full car-gallery" id="gallery<?php echo $car['id']; ?>">
                                <?php foreach ($images as $image): ?>
                                <img src="<?php echo SITE_URL . '/' . htmlspecialchars(trim($image)); ?>" 
                                     alt="<?php echo htmlspecialchars($car['title']); ?>" 
                                     class="w-full h-full object-cover flex-shrink-0">
                                <?php endforeach; ?>
                            </div>
                            <?php if (count($images) > 1): ?>
                            <button onclick="event.preventDefault(); navCarousel(<?php echo $car['id']; ?>, -1)" 
                                    class="absolute left-2 top-1/2 -translate-y-1/2 bg-black/60 hover:bg-black/80 text-white rounded-full p-2 opacity-0 group-hover:opacity-100 transition">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
                                </svg>
                            </button>
                            <button onclick="event.preventDefault(); navCarousel(<?php echo $car['id']; ?>, 1)" 
                                    class="absolute right-2 top-1/2 -translate-y-1/2 bg-black/60 hover:bg-black/80 text-white rounded-full p-2 opacity-0 group-hover:opacity-100 transition">
                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/>
                                </svg>
                            </button>
                            <div class="absolute bottom-2 left-1/2 -translate-x-1/2 flex gap-1">
                                <?php foreach ($images as $idx => $img): ?>
                                <div class="w-1.5 h-1.5 rounded-full bg-white/70" id="dot<?php echo $car['id']; ?>_<?php echo $idx; ?>"></div>
                                <?php endforeach; ?>
                            </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <div class="w-full h-full bg-gray-200 flex items-center justify-center text-gray-400 text-4xl">
                                🚗
                            </div>
                        <?php endif; ?>
                        <div class="absolute top-3 left-3">
                            <span class="bg-primary-green text-white px-3 py-1 rounded-full text-sm font-semibold shadow-lg">
                                ⭐ Featured
                            </span>
                        </div>
                        <div class="absolute top-3 right-3">
                            <span class="bg-primary-blue text-white px-3 py-1 rounded-full text-sm font-semibold shadow-lg">
                                <?php echo ucfirst($car['listing_type']); ?>
                            </span>
                        </div>
                    </div>
                    
                    <!-- Car Details -->
                    <div class="p-6">
                        <h3 class="text-xl font-bold text-gray-800 mb-2"><?php echo htmlspecialchars($car['title']); ?></h3>
                        <p class="text-sm text-gray-600 mb-4">
                            <?php echo $car['year']; ?> | <?php echo number_format($car['mileage']); ?> km | <?php echo $car['fuel_type']; ?>
                        </p>
                        
                        <?php if ($car['features']): 
                            $features = array_filter(array_map('trim', explode("\n", $car['features'])));
                            $displayFeatures = array_slice($features, 0, 3);
                        ?>
                        <div class="text-sm text-gray-700 mb-4 space-y-1">
                            <?php foreach ($displayFeatures as $feature): ?>
                            <p>• <?php echo htmlspecialchars($feature); ?></p>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                        
                        <div class="pt-4 border-t">
                            <div class="flex justify-between items-end mb-2">
                                <div>
                                    <p class="text-xs text-gray-500 mb-1">Pay as low as</p>
                                    <p class="text-3xl font-bold text-primary-blue"><?php echo formatCurrency($car['price'] / 24); ?><span class="text-base">/month</span></p>
                                    <p class="text-xs text-gray-400 mt-1">Total: <?php echo formatCurrency($car['price']); ?> • 24 months</p>
                                </div>
                                <span class="bg-primary-blue text-white px-4 py-2 rounded-lg font-semibold hover:bg-opacity-90 transition text-sm whitespace-nowrap">
                                    View Details
                                </span>
                            </div>
                        </div>
                    </div>
                </a>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</section>

<!-- CTA Section -->
<section class="bg-primary-blue text-white py-12">
    <div class="container mx-auto px-4 text-center">
        <h2 class="text-3xl font-bold mb-4">Need Financing?</h2>
        <p class="text-lg mb-6">We offer flexible payment plans and competitive interest rates</p>
        <a href="<?php echo SITE_URL; ?>/contact.html" class="inline-block bg-primary-green text-white px-8 py-3 rounded-lg font-semibold hover:bg-opacity-90 transition">
            Contact Us Today
        </a>
    </div>
</section>

<script>
const carouselStates = {};

function navCarousel(carId, direction) {
    if (!carouselStates[carId]) {
        carouselStates[carId] = { currentSlide: 0, totalSlides: 0 };
        const gallery = document.getElementById('gallery' + carId);
        if (gallery) {
            carouselStates[carId].totalSlides = gallery.children.length;
        }
    }
    
    const state = carouselStates[carId];
    state.currentSlide = (state.currentSlide + direction + state.totalSlides) % state.totalSlides;
    
    const gallery = document.getElementById('gallery' + carId);
    if (gallery) {
        gallery.style.transform = `translateX(-${state.currentSlide * 100}%)`;
    }
    
    // Update dots
    for (let i = 0; i < state.totalSlides; i++) {
        const dot = document.getElementById(`dot${carId}_${i}`);
        if (dot) {
            if (i === state.currentSlide) {
                dot.classList.remove('bg-white/70');
                dot.classList.add('bg-white');
            } else {
                dot.classList.remove('bg-white');
                dot.classList.add('bg-white/70');
            }
        }
    }
}
</script>

<?php include 'includes/footer.php'; ?>
