<?php
    require_once '../../autoload.php';
    header('Content-Type: application/json; charset=utf-8');

    // Whitelist des colonnes pour ORDER BY
    $allowed_columns = ['lro_id', 'name'];


    $draw   = intval($_GET['draw']   ?? 0);
    $start  = intval($_GET['start']  ?? 0);
    $length = intval($_GET['length'] ?? 10);

    // Whitelist ORDER BY
    $columns  = $_GET['columns'] ?? [];
    $order    = $_GET['order']   ?? [];
    $orderCol = intval($order[0]['column'] ?? 0);

    $orderColName = $columns[$orderCol]['data'] ?? 'name';
    if(!in_array($orderColName, $allowed_columns, true))
        $orderColName = 'name';

    $orderDir = (strtoupper($order[0]['dir'] ?? '') === 'DESC') ? 'DESC' : 'ASC';
    $orderby  = " ORDER BY {$orderColName} {$orderDir}";

    $limit = ($length != -1) ? " OFFSET {$start} LIMIT {$length}" : '';

    $empty_response = json_encode([
        "draw"            => $draw,
        "recordsTotal"    => 0,
        "recordsFiltered" => 0,
        "data"            => []
    ]);

    $conn = get_dbconnection();
    if(!$conn)
    {
        echo $empty_response;
        exit();
    }
    $base_sql = "
        SELECT lro_id, name
        FROM login_role
        WHERE lro_id <> -1
          AND removed = false";

    // --- Comptage ---
    if(!pg_prepare($conn, 'stmt_count', "SELECT COUNT(*) FROM ({$base_sql}) AS count_query"))
    {
        error_log('pg_prepare stmt_count failed: ' . pg_last_error($conn));
        echo $empty_response;
        exit();
    }
    $count_result    = pg_execute($conn, 'stmt_count', []);
    $recordsFiltered = 0;
    if($count_result)
        $recordsFiltered = intval(pg_fetch_row($count_result)[0]);

    // --- Données paginées et triées ---
    if(!pg_prepare($conn, 'stmt_data', $base_sql . $orderby . $limit))
    {
        error_log('pg_prepare stmt_data failed: ' . pg_last_error($conn));
        echo $empty_response;
        exit();
    }
    $data_result = pg_execute($conn, 'stmt_data', []);
    $data = [];
    if($data_result)
        while($row = pg_fetch_assoc($data_result))
            $data[] = $row;

    echo json_encode([
        "draw"            => $draw,
        "recordsTotal"    => $recordsFiltered,
        "recordsFiltered" => $recordsFiltered,
        "data"            => $data
    ]);
?>