<?php
// D:\quadrata_app\htdocs\appquadrata\home\clientes\view\ajax\get_regimen_fiscal_por_tipo.php
header('Content-Type: application/json; charset=utf-8');

try {
    // Validar parámetro
    $tipo = isset($_GET['tipo']) ? intval($_GET['tipo']) : 0;
    if ($tipo <= 0) {
        echo json_encode(["ok" => false, "msg" => "Parámetro 'tipo' inválido", "data" => []]);
        exit;
    }

    // Incluir conexión (4 brincos hasta appquadrata)
    require_once(__DIR__ . '/../../../../odbconexion/config.php');
    $Odbj_conexion = new odbconexion;
    $cn = $Odbj_conexion->openconection();

    // Consulta segura
    $sql = "SELECT Id_Regimen_Fiscal, Regimen_Tributario 
            FROM regimen_fiscal 
            WHERE Id_Fk_Tipo_Persona = ? 
            ORDER BY Regimen_Tributario ASC";

    $stmt = $cn->prepare($sql);
    if (!$stmt) {
        echo json_encode(["ok" => false, "msg" => "Error en prepare: " . $cn->error, "data" => []]);
        exit;
    }
    $stmt->bind_param("i", $tipo);
    $stmt->execute();
    $res = $stmt->get_result();

    $data = [];
    while ($row = $res->fetch_assoc()) {
        $data[] = [
            "id"   => (int)$row['Id_Regimen_Fiscal'],
            "text" => $row['Regimen_Tributario']
        ];
    }

    $stmt->close();
    $cn->close();

    echo json_encode(["ok" => true, "msg" => "", "data" => $data], JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    echo json_encode(["ok" => false, "msg" => $e->getMessage(), "data" => []]);
}
