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

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

$reservationId   = (int)($_POST['reservation_id'] ?? 0);
$newDate         = $_POST['date'] ?? '';
$newTime         = $_POST['time'] ?? '';
$newChauffeurId  = (int)($_POST['chauffeur_id'] ?? 0);

$stmt = $pdo->prepare("SELECT id, status, reservation_date FROM reservations WHERE id = ? AND user_id = ?");
$stmt->execute([$reservationId, $_SESSION['user_id']]);
$res = $stmt->fetch();

if (!$res) redirect('my_reservations.php');

if ($res['status'] !== 'confirmée' || strtotime($res['reservation_date']) < strtotime(date('Y-m-d'))) {
    $_SESSION['error'] = "Cette réservation ne peut plus être modifiée.";
    redirect('my_reservations.php');
}

if (!isTimeSlotAvailable($pdo, $newChauffeurId, $newDate, $newTime, $reservationId)) {
    $_SESSION['error'] = "Ce créneau n'est pas disponible. Veuillez en choisir un autre.";
    redirect("edit_reservation.php?id=$reservationId");
}

$stmt = $pdo->prepare("UPDATE reservations SET reservation_date=?, reservation_time=?, chauffeur_id=? WHERE id=?");
if ($stmt->execute([$newDate, $newTime, $newChauffeurId, $reservationId])) {
    $_SESSION['flash'] = "Réservation modifiée avec succès.";
} else {
    $_SESSION['error'] = "Erreur lors de la modification.";
}
redirect('my_reservations.php');