<?php
/**
 * API pour la gestion des Tarifications
 * 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 Tarifications WHERE 1=1";
            $params = [];
            
            if ($siteFilter && $siteFilter !== 'Siège') {
                $query .= " AND Site = ?";
                $params[] = $siteFilter;
            }
            
            $query .= " ORDER BY ID";
            
            $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 Tarifications WHERE ID = ?");
            $stmt->execute([$_GET['id']]);
            $tarif = $stmt->fetch();
            echo json_encode(['success' => (bool)$tarif, 'data' => $tarif]);
            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') {
        $tarifId = $input['ID'] ?? null;
        
        if (!$tarifId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ID requis']);
            exit;
        }

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

        $stmt = $pdo->prepare("
            INSERT INTO Tarifications (ID, ArretDepart, ArretArrive, Prix, Site, IDUsers, Date_Modif) 
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        
        $ok = $stmt->execute([
            $tarifId,
            $input['ArretDepart'] ?? '',
            $input['ArretArrive'] ?? '',
            $input['Prix'] ?? 0,
            $input['Site'] ?? '',
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s')
        ]);
        
        logAction($pdo, $auth['user_id'], 'CREATE_TARIF', $tarifId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

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

        $stmt = $pdo->prepare("
            UPDATE Tarifications SET 
                ArretDepart = ?, ArretArrive = ?, Prix = ?, Site = ?, IDUsers = ?, Date_Modif = ?
            WHERE ID = ?
        ");
        
        $ok = $stmt->execute([
            $input['ArretDepart'] ?? '',
            $input['ArretArrive'] ?? '',
            $input['Prix'] ?? 0,
            $input['Site'] ?? '',
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s'),
            $tarifId
        ]);
        
        // Mettre à jour les trajets aussi
        $stmtTrajets = $pdo->prepare("
            UPDATE Trajets SET Prix = ?, PrixTotal = Prix + Redevance, 
            UserID = ?, Date_Modif = ? 
            WHERE ArretDepartID = ? AND ArretArriveeID = ?
        ");
        $stmtTrajets->execute([
            $input['Prix'] ?? 0,
            $auth['user_id'] ?? 'System',
            date('Y-m-d H:i:s'),
            $input['ArretDepart'] ?? '',
            $input['ArretArrive'] ?? ''
        ]);
        
        logAction($pdo, $auth['user_id'], 'UPDATE_TARIF', $tarifId);
        
        echo json_encode(['success' => $ok]);
        exit;
    }

    if ($method === 'DELETE') {
        $tarifId = $input['ID'] ?? ($_GET['id'] ?? null);
        $arretDepart = $input['ArretDepart'] ?? '';
        $arretArrive = $input['ArretArrive'] ?? '';
        
        if (!$tarifId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ID requis']);
            exit;
        }
        
        // Supprimer les trajets d'abord
        $stmtTrajets = $pdo->prepare("DELETE FROM Trajets WHERE ArretDepartID = ? AND ArretArriveeID = ?");
        $stmtTrajets->execute([$arretDepart, $arretArrive]);
        
        $stmt = $pdo->prepare("DELETE FROM Tarifications WHERE ID = ?");
        $ok = $stmt->execute([$tarifId]);
        
        logAction($pdo, $auth['user_id'], 'DELETE_TARIF', $tarifId);
        
        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 Tarifications: ' . $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
    }
}
?>
