<?php
/**
 * API pour la gestion des Lignes
 * 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'] ?? '';
$siteFilter = $_GET['site'] ?? null;

try {
    if ($method === 'GET') {
        if ($action === 'list') {
            $query = "SELECT * FROM Lignes WHERE 1=1";
            $params = [];
            
            if ($siteFilter && $siteFilter !== 'Siège') {
                $query .= " AND Site = ?";
                $params[] = $siteFilter;
            }
            
            $query .= " ORDER BY LigneID";
            
            $stmt = $pdo->prepare($query);
            $stmt->execute($params);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            exit;
        }
        
        if ($action === 'get' && isset($_GET['id'])) {
            $stmt = $pdo->prepare("SELECT * FROM Lignes WHERE LigneID = ?");
            $stmt->execute([$_GET['id']]);
            $ligne = $stmt->fetch();
            echo json_encode(['success' => (bool)$ligne, 'data' => $ligne]);
            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') {
        $ligneId = $input['LigneID'] ?? null;
        $nomLigne = $input['NomLigne'] ?? null;
        
        if (!$ligneId || !$nomLigne) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Champs requis manquants']);
            exit;
        }

        $stmt = $pdo->prepare("SELECT COUNT(*) FROM Lignes WHERE LigneID = ?");
        $stmt->execute([$ligneId]);
        if ($stmt->fetchColumn() > 0) {
            http_response_code(409);
            echo json_encode(['success' => false, 'message' => "La ligne $ligneId existe déjà"]);
            exit;
        }

        $stmt = $pdo->prepare("
            INSERT INTO Lignes (LigneID, NomLigne, Type_Ligne, RedevencePassager, Site, UserID, Date_Modif) 
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        
        $ok = $stmt->execute([
            $ligneId,
            $input['NomLigne'] ?? '',
            $input['Type_Ligne'] ?? '',
            $input['RedevencePassager'] ?? 0,
            $input['Site'] ?? '',
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s')
        ]);
        
        logAction($pdo, $auth['user_id'], 'CREATE_LIGNE', $ligneId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

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

        $stmt = $pdo->prepare("
            UPDATE Lignes SET 
                NomLigne = ?, Type_Ligne = ?, RedevencePassager = ?, 
                UserID = ?, Date_Modif = ?
            WHERE LigneID = ?
        ");
        
        $ok = $stmt->execute([
            $input['NomLigne'] ?? '',
            $input['Type_Ligne'] ?? '',
            $input['RedevencePassager'] ?? 0,
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s'),
            $ligneId
        ]);
        
        // Mettre à jour les trajets aussi
        $stmtTrajets = $pdo->prepare("
            UPDATE Trajets SET Redevance = ?, PrixTotal = Prix + ?, 
            UserID = ?, Date_Modif = ? WHERE LigneID = ?
        ");
        $stmtTrajets->execute([
            $input['RedevencePassager'] ?? 0,
            $input['RedevencePassager'] ?? 0,
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s'),
            $ligneId
        ]);
        
        logAction($pdo, $auth['user_id'], 'UPDATE_LIGNE', $ligneId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

    if ($method === 'DELETE') {
        $ligneId = $input['LigneID'] ?? ($_GET['id'] ?? null);
        if (!$ligneId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'LigneID requis']);
            exit;
        }
        
        // Supprimer les trajets d'abord
        $stmtTrajets = $pdo->prepare("DELETE FROM Trajets WHERE LigneID = ?");
        $stmtTrajets->execute([$ligneId]);
        
        $stmt = $pdo->prepare("DELETE FROM Lignes WHERE LigneID = ?");
        $ok = $stmt->execute([$ligneId]);
        
        logAction($pdo, $auth['user_id'], 'DELETE_LIGNE', $ligneId);
        
        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 Lignes: ' . $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
    }
}
?>
