<?php
require_once 'config.php';
require_once 'functions.php';
requireLogin();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') redirect('dashboard.php');
csrf_verify();

$userId         = (int)$_SESSION['user_id'];
$carId          = (int)($_POST['car_id'] ?? 0);
$chauffeurId    = (int)($_POST['chauffeur_id'] ?? 0);
$date           = $_POST['date'] ?? '';
$time           = $_POST['time'] ?? '';
$pickupAddress  = trim($_POST['pickup_address'] ?? '');
$dropoffAddress = trim($_POST['dropoff_address'] ?? '');

// Vérification des données requises
if (empty($date) || empty($time) || empty($pickupAddress) || empty($dropoffAddress) || !$carId || !$chauffeurId) {
    $_SESSION['error'] = "Tous les champs sont requis.";
    redirect("book.php?car_id=$carId");
}

// 1. Chauffeur disponible à ce créneau ?
$available = getAvailableChauffeurs($pdo, $date, $time);
$found = false;
foreach ($available as $ch) {
    if ($ch['id'] == $chauffeurId) { $found = true; break; }
}
if (!$found) {
    $_SESSION['error'] = "Ce chauffeur n'est pas disponible à cette heure.";
    redirect("book.php?car_id=$carId");
}

// 2. Créneau encore libre ?
if (!isTimeSlotAvailable($pdo, $chauffeurId, $date, $time)) {
    $_SESSION['error'] = "Ce créneau vient d'être pris. Veuillez en choisir un autre.";
    redirect("book.php?car_id=$carId");
}

// 3. Voiture valide ?
$stmt = $pdo->prepare("SELECT id FROM cars WHERE id = ? AND active = 1");
$stmt->execute([$carId]);
if (!$stmt->fetch()) {
    $_SESSION['error'] = "Véhicule invalide.";
    redirect('dashboard.php');
}

// 4. Insertion
try {
    $stmt = $pdo->prepare("INSERT INTO reservations
        (user_id, car_id, chauffeur_id, pickup_address, dropoff_address, reservation_date, reservation_time)
        VALUES (?, ?, ?, ?, ?, ?, ?)");

    if ($stmt->execute([$userId, $carId, $chauffeurId, $pickupAddress, $dropoffAddress, $date, $time])) {
        $newId = $pdo->lastInsertId();

        // Récupérer les infos complètes pour l'email
        $stmt2 = $pdo->prepare("SELECT r.*, c.name as car_name, ch.name as chauffeur_name, u.email as user_email, u.name as user_name
                                 FROM reservations r
                                 JOIN cars c ON r.car_id = c.id
                                 JOIN chauffeurs ch ON r.chauffeur_id = ch.id
                                 JOIN users u ON r.user_id = u.id
                                 WHERE r.id = ?");
        $stmt2->execute([$newId]);
        $resData = $stmt2->fetch();

        // Envoyer email de confirmation (simulé en développement)
        $resData['reservation_date'] = date('d/m/Y', strtotime($resData['reservation_date']));
        $resData['reservation_time'] = substr($resData['reservation_time'], 0, 5);
        
        // Appel à la fonction d'email (maintenant simulée)
        sendBookingConfirmation($resData['user_email'], $resData['user_name'], $resData);
        
        redirect("booking_confirmed.php?id=$newId");
    } else {
        $_SESSION['error'] = "Erreur lors de la réservation. Veuillez réessayer.";
        redirect("book.php?car_id=$carId");
    }
} catch (PDOException $e) {
    error_log("Erreur confirm_booking: " . $e->getMessage());
    $_SESSION['error'] = "Erreur technique. Veuillez réessayer.";
    redirect("book.php?car_id=$carId");
}
?>