<?php
error_reporting(E_ALL ^ E_NOTICE);
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=utf-8");

include_once '../conexion.php';
include_once '../clases/TokenValidator.php';

// Llama la validación antes de cualquier consulta
$usuarioId = TokenValidator::validar($conn);

$bodyRequest = file_get_contents("php://input");
$datos = json_decode($bodyRequest, true);
$rows = [];

try {
    $sql = "SELECT id, nombre FROM tipos_pago_contado WHERE activo = true ORDER BY id;";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_response("Error al ejecutar la consulta: " . $e->getMessage());
}

$conn = null;
print_json($rows);

function print_json($data) {
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    switch (json_last_error()) {
        case JSON_ERROR_NONE: break;
        case JSON_ERROR_UTF8: error_response('Malformed UTF-8 characters'); break;
        default: error_response('Unknown JSON error'); break;
    }
}

function error_response($message) {
    http_response_code(500);
    echo json_encode(['error' => $message], JSON_UNESCAPED_UNICODE);
    exit();
}
?>
