<?php
/**
 * API: Insertion d'une nouvelle rotation
 * POST /apipcc/rotations_insert.php
 * Paramètres: bus_id, chauffeur_id, type (sortie/entree), autorisation (optionnel), creer_par
 */
require_once __DIR__ . '/config.php';

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

$data = getPostData();
$bus_id = $data['bus_id'] ?? '';
$chauffeur_id = $data['chauffeur_id'] ?? '';
$type = $data['type'] ?? ''; // 'sortie' ou 'entree'
$autorisation = $data['autorisation'] ?? null;
$creer_par = $data['creer_par'] ?? '';

if (empty($bus_id) || empty($chauffeur_id) || empty($type) || empty($creer_par)) {
    sendError('bus_id, chauffeur_id, type et creer_par sont requis');
}

if (!in_array($type, ['sortie', 'entree'])) {
    sendError('Type doit être "sortie" ou "entree"');
}

$conn = getConnection(DB_NAME_PARCS);

if ($type === 'sortie') {
    if ($autorisation) {
        $sql = "INSERT INTO rotations (BusID, ChauffeurID_Sortie, HeureSortie, Autorisation, CreerPar, DateCreation) VALUES (?, ?, NOW(), ?, ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssss", $bus_id, $chauffeur_id, $autorisation, $creer_par);
    } else {
        $sql = "INSERT INTO rotations (BusID, ChauffeurID_Sortie, HeureSortie, CreerPar, DateCreation) VALUES (?, ?, NOW(), ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sss", $bus_id, $chauffeur_id, $creer_par);
    }
} else { // entree
    if ($autorisation) {
        $sql = "INSERT INTO rotations (BusID, ChauffeurID_Entree, HeureEntree, Autorisation, CreerPar, DateCreation) VALUES (?, ?, NOW(), ?, ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssss", $bus_id, $chauffeur_id, $autorisation, $creer_par);
    } else {
        $sql = "INSERT INTO rotations (BusID, ChauffeurID_Entree, HeureEntree, CreerPar, DateCreation) VALUES (?, ?, NOW(), ?, NOW())";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sss", $bus_id, $chauffeur_id, $creer_par);
    }
}

if ($stmt->execute()) {
    $rotation_id = $stmt->insert_id;
    sendSuccess(['RotationID' => $rotation_id], 'Rotation insérée avec succès');
} else {
    sendError('Erreur lors de l\'insertion: ' . $stmt->error);
}

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