<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/header.php';

// Fetch All Available Cars
try {
    $db = db();
    $cars = $db->query("SELECT c.*, b.name as branch_name 
                        FROM cars c 
                        JOIN branches b ON c.branch_id = b.id 
                        WHERE c.status = 'Available' 
                        ORDER BY c.is_featured DESC, c.created_at DESC")->fetchAll();
} catch (Exception $e) {
    $cars = [];
}
?>

<section class="container" style="padding-top: 4rem;">
    <div class="section-title">
        <div>
            <h1>Premium Marketplace</h1>
            <p>Explore our complete inventory of elite vehicles across Afghanistan.</p>
        </div>
        <div>
            <span style="background: var(--accent-color); color: #000; padding: 0.6rem 1.2rem; border-radius: 30px; font-weight: 800; font-size: 0.8rem; border: 1px solid var(--border-color);">
                <?= count($cars) ?> VEHICLES FOUND
            </span>
        </div>
    </div>

    <div class="grid">
        <?php foreach ($cars as $car): ?>
        <div class="car-card">
            <div class="car-image">
                <?php if ($car['is_featured']): ?>
                    <span class="car-badge">FEATURED</span>
                <?php endif; ?>
                <img src="<?= htmlspecialchars($car['image_url']) ?>" alt="<?= htmlspecialchars($car['brand']) ?>">
            </div>
            <div class="car-content">
                <div class="car-title"><?= htmlspecialchars($car['year'] . ' ' . $car['brand'] . ' ' . $car['model']) ?></div>
                <div class="car-price">$<?= number_format((float)$car['price'], 0) ?></div>
                
                <div class="car-meta">
                    <span><i class="fas fa-cog"></i> <?= htmlspecialchars($car['transmission'] ?? 'Auto') ?></span>
                    <span><i class="fas fa-tachometer-alt"></i> <?= number_format((float)$car['mileage'], 0) ?> KM</span>
                    <span><i class="fas fa-gas-pump"></i> <?= htmlspecialchars($car['fuel_type'] ?? 'Gas') ?></span>
                </div>
                
                <div class="car-meta">
                    <span><i class="fas fa-map-marker-alt"></i> <strong><?= htmlspecialchars($car['branch_name']) ?></strong></span>
                </div>

                <div class="installment-box">
                    Installment Plan: <strong>$<?= number_format($car['price'] / 60, 0) ?>/mo</strong> for 60 months
                </div>
                
                <div style="margin-top: 1.5rem;">
                    <a href="#" class="btn" style="width: 100%;">Reserve Vehicle</a>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</section>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
