<?php
/**
 * API: Dernière rotation d'un bus
 * GET /apipcc/rotations_last.php?bus_id=XXX
 */
require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    sendError('Méthode non autorisée', 405);
}

$bus_id = $_GET['bus_id'] ?? '';

if (empty($bus_id)) {
    sendError('bus_id requis');
}

$conn = getConnection(DB_NAME_PARCS);

$sql = "SELECT RotationID, BusID, ChauffeurID_Sortie, ChauffeurID_Entree, HeureSortie, HeureEntree, Autorisation 
        FROM rotations WHERE BusID = ? ORDER BY RotationID DESC LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $bus_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    sendSuccess($row, 'Dernière rotation récupérée');
} else {
    sendSuccess([], 'Aucune rotation trouvée');
}

$stmt->close();
$conn->close();