<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
include_once __DIR__ . '/../auth_check.php';

$pdo = getDbConnection();
$action = $_REQUEST['action'] ?? '';

switch ($action) {
    case 'getOpen':
        $siteName = $_REQUEST['site'] ?? '';
        try {
            $sql = "SELECT d.*, b.Modele_Bus, b.Capacite_Bus, b.Ligne_Bus, b.Operateur_Bus, b.Id_Ligne 
                    FROM Departs d 
                    LEFT JOIN BusGares b ON d.BusID = b.Modele_Bus AND d.Site = b.Site
                    WHERE d.Etat_Depart = 'O'";
            $params = [];
            if (!empty($siteName) && $siteName !== 'Siège') {
                $sql .= " AND d.Site = ?";
                $params[] = $siteName;
            }
            $sql .= " ORDER BY d.DateDepart DESC";
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'getById':
        $departID = $_REQUEST['departID'] ?? '';
        $siteName = $_REQUEST['site'] ?? '';
        try {
            $stmt = $pdo->prepare("SELECT * FROM Departs WHERE DepartID = ? AND Site = ?");
            $stmt->execute([$departID, $siteName]);
            echo json_encode(['success' => true, 'data' => $stmt->fetch()]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'create':
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) { $data = $_REQUEST; }
        try {
            $sql = "INSERT INTO Departs (DepartID, Site, BusID, DateDepart, TimeDepart, LigneID, Id_Ligne, ArretDepart, ArretArriver, 
                    Prix, Redevance, NbrePassagers, NbrePassagersReelle, Observation, UserID, TypeBus, Date_Ouverture, 
                    Time_Ouverture, Heure_Depart_Reelle, Nbre_Places_ restantes, PrixTotal, FeuilleID, Type_Ligne, 
                    VilleDepart, VilleArrive, CodeGareDepart, CodeGareArriver, DateArriveePrevue, TimeArriveePrevue, 
                    Chef_Module, Chef_Gare, Superviseur, SuperviseurGare, TypeDeService,Etat_Depart) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([
                $data['DepartID'] ?? '', $data['Site'] ?? '', $data['BusID'] ?? '', $data['DateDepart'] ?? '',
                $data['TimeDepart'] ?? '', $data['LigneID'] ?? '', $data['Id_Ligne'] ?? '', $data['ArretDepart'] ?? '',
                $data['ArretArriver'] ?? '', $data['Prix'] ?? 0, $data['Redevance'] ?? 0, $data['NbrePassagers'] ?? 0,
                $data['NbrePassagersReelle'] ?? 0, $data['Observation'] ?? '', $data['UserID'] ?? '', $data['TypeBus'] ?? '',
                $data['Date_Ouverture'] ?? '', $data['Time_Ouverture'] ?? '', $data['Heure_Depart_Reelle'] ?? '',
                $data['Nbre_Places_ restantes'] ?? 0, $data['PrixTotal'] ?? 0, $data['FeuilleID'] ?? '',
                $data['Type_Ligne'] ?? '', $data['VilleDepart'] ?? '', $data['VilleArrive'] ?? '',
                $data['CodeGareDepart'] ?? '', $data['CodeGareArriver'] ?? '', $data['DateArriveePrevue'] ?? '',
                $data['TimeArriveePrevue'] ?? '', $data['Chef_Module'] ?? '', $data['Chef_Gare'] ?? '',
                $data['Superviseur'] ?? '', $data['SuperviseurGare'] ?? '', $data['TypeDeService'] ?? '', 'O'
            ]);
            echo json_encode(['success' => true, 'message' => 'Depart créé']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'close':
        $departID = $_REQUEST['departID'] ?? '';
        $siteName = $_REQUEST['site'] ?? '';
        try {
            $stmt = $pdo->prepare("UPDATE Departs SET NbrePassagersReelle = (
                SELECT COALESCE(SUM(PassConv), 0) FROM Tickets WHERE DepartID = ? AND Site = ?
            ), Nbre_Places_ restantes = 0, Et_Depart = 'F', Date_Fin = NOW() WHERE DepartID = ? AND Site = ?");
            $stmt->execute([$departID, $siteName, $departID, $siteName]);
            echo json_encode(['success' => true, 'message' => 'Depart fermé']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    case 'update':
        $data = json_decode(file_get_contents('php://input'), true);
        if (!$data) { $data = $_REQUEST; }
        try {
            $sql = "UPDATE Departs SET NbrePassagersReelle = ?, Observation = ? WHERE DepartID = ? AND Site = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$data['NbrePassagersReelle'] ?? 0, $data['Observation'] ?? '', $data['DepartID'] ?? '', $data['Site'] ?? '']);
            echo json_encode(['success' => true, 'message' => 'Depart mis à jour']);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        break;
        
    default:
        try {
            $stmt = $pdo->query("SELECT * FROM Departs WHERE Et_Depart = 'O' ORDER BY DateDepart DESC LIMIT 50");
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
}