<?php
/**
 * API pour la gestion des Arrêts
 * Répertoire: Includes/Tables/
 * Sécurisée avec authentification
 */

include_once __DIR__ . '/../auth_check.php';

checkRateLimit($_SERVER['REMOTE_ADDR'] ?? 'unknown');

$pdo = getDbConnection();

$auth = checkApiAuth($pdo);
if (!$auth['success']) {
    $method = $_SERVER['REQUEST_METHOD'];
    if ($method !== 'GET') {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => $auth['message']]);
        exit;
    }
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    if ($method === 'GET') {
        if ($action === 'list') {
            $stmt = $pdo->query("SELECT * FROM Arrets ORDER BY ArretID");
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            exit;
        }
        
        if ($action === 'get' && isset($_GET['id'])) {
            $stmt = $pdo->prepare("SELECT * FROM Arrets WHERE ArretID = ?");
            $stmt->execute([$_GET['id']]);
            $arret = $stmt->fetch();
            echo json_encode(['success' => (bool)$arret, 'data' => $arret]);
            exit;
        }
        
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Action GET invalide']);
        exit;
    }

    if (!$auth['success']) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Authentification requise']);
        exit;
    }

    $inputJson = file_get_contents('php://input');
    $input = json_decode($inputJson, true);
    $input = sanitizeInput($input);

    if ($method === 'POST') {
        $nomArret = $input['Nom_Arret'] ?? null;
        
        if (!$nomArret) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Nom_Arret requis']);
            exit;
        }

        $stmt = $pdo->prepare("
            INSERT INTO Arrets (Nom_Arret, Localisation_Arret, UserID, Date_Modif) 
            VALUES (?, ?, ?, ?)
        ");
        
        $ok = $stmt->execute([
            $input['Nom_Arret'] ?? '',
            $input['Localisation_Arret'] ?? '',
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s')
        ]);
        
        logAction($pdo, $auth['user_id'], 'CREATE_ARRET', $nomArret);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

    if ($method === 'PUT') {
        $arretId = $input['ArretID'] ?? null;
        if (!$arretId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ArretID requis']);
            exit;
        }

        $stmt = $pdo->prepare("
            UPDATE Arrets SET 
                Nom_Arret = ?, Localisation_Arret = ?, UserID = ?, Date_Modif = ?
            WHERE ArretID = ?
        ");
        
        $ok = $stmt->execute([
            $input['Nom_Arret'] ?? '',
            $input['Localisation_Arret'] ?? '',
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s'),
            $arretId
        ]);
        
        logAction($pdo, $auth['user_id'], 'UPDATE_ARRET', $arretId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

    if ($method === 'DELETE') {
        $arretId = $input['ArretID'] ?? ($_GET['id'] ?? null);
        if (!$arretId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ArretID requis']);
            exit;
        }
        
        $stmt = $pdo->prepare("DELETE FROM Arrets WHERE ArretID = ?");
        $ok = $stmt->execute([$arretId]);
        
        logAction($pdo, $auth['user_id'], 'DELETE_ARRET', $arretId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Méthode non supportée']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur API Arrets: ' . $e->getMessage()]);
}

function logAction($pdo, $userId, $action, $target) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO Journalisation (DateJournal, TimeJournal, OperateurID, Action, Details) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            date('Y-m-d'),
            date('H:i:s'),
            $userId,
            $action,
            "API: $action sur $target"
        ]);
    } catch (Exception $e) {
        // Ne pas bloquer
    }
}
?>
