<?php
/**
 * API pour la gestion des Types de 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'] ?? '';

try {
    if ($method === 'GET') {
        if ($action === 'list') {
            $stmt = $pdo->query("SELECT * FROM TypesLignes ORDER BY Type_LigneID");
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            exit;
        }
        
        if ($action === 'get' && isset($_GET['id'])) {
            $stmt = $pdo->prepare("SELECT * FROM TypesLignes WHERE Type_LigneID = ?");
            $stmt->execute([$_GET['id']]);
            $type = $stmt->fetch();
            echo json_encode(['success' => (bool)$type, 'data' => $type]);
            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') {
        $typeId = $input['Type_LigneID'] ?? null;
        $libelle = $input['Libelle_Type'] ?? null;
        
        if (!$typeId || !$libelle) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Champs requis manquants']);
            exit;
        }

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

        $stmt = $pdo->prepare("
            INSERT INTO TypesLignes (Type_LigneID, Libelle_Type, DST, UserID, DateModif) 
            VALUES (?, ?, ?, ?, ?)
        ");
        
        $ok = $stmt->execute([
            $typeId,
            $input['Libelle_Type'] ?? '',
            $input['DST'] ?? 0,
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s')
        ]);
        
        logAction($pdo, $auth['user_id'], 'CREATE_TYPELIGNE', $typeId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

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

        $stmt = $pdo->prepare("
            UPDATE TypesLignes SET 
                Libelle_Type = ?, DST = ?, UserID = ?, DateModif = ?
            WHERE Type_LigneID = ?
        ");
        
        $ok = $stmt->execute([
            $input['Libelle_Type'] ?? '',
            $input['DST'] ?? 0,
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s'),
            $typeId
        ]);
        
        logAction($pdo, $auth['user_id'], 'UPDATE_TYPELIGNE', $typeId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

    if ($method === 'DELETE') {
        $typeId = $input['Type_LigneID'] ?? ($_GET['id'] ?? null);
        if (!$typeId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Type_LigneID requis']);
            exit;
        }
        
        $stmt = $pdo->prepare("DELETE FROM TypesLignes WHERE Type_LigneID = ?");
        $ok = $stmt->execute([$typeId]);
        
        logAction($pdo, $auth['user_id'], 'DELETE_TYPELIGNE', $typeId);
        
        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 TypesLignes: ' . $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
    }
}
?>
