<?php
include '../includes/session_control.php';
include '../db/db.php';

if (isset($_GET['id'])) {
    $id = $_GET['id'];

    $query = "SELECT tb_terceros.*, tb_tipo_regimen.nombre AS regimen, tb_tipo_documento.nombre AS tipoDocumento, tb_departamentos.nombre AS departamento, tb_ciudades.nombre AS ciudad
    FROM tb_terceros
    INNER JOIN tb_tipo_regimen ON tb_terceros.idRegimen = tb_tipo_regimen.id
    INNER JOIN tb_tipo_documento ON tb_terceros.idTipoDocumento = tb_tipo_documento.id
    INNER JOIN tb_usuarios_direcciones ON tb_terceros.idDireccion = tb_usuarios_direcciones.id
    INNER JOIN tb_ciudades ON tb_usuarios_direcciones.idCiudad = tb_ciudades.id
    INNER JOIN tb_departamentos ON tb_ciudades.idDepartamento = tb_departamentos.id
    WHERE tb_terceros.id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();

    $billing = $result->fetch_assoc();

    echo json_encode($billing);

    $stmt->close();
} elseif (isset($_GET['userId'])) {
    $userId = $_GET['userId'];

    $query = "SELECT tb_terceros.id, tb_terceros.nombre, tb_terceros.apellido, tb_terceros.razonSocial
    FROM tb_terceros
    WHERE tb_terceros.idUsuario = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $result = $stmt->get_result();

    $billing = [];
    while ($row = $result->fetch_assoc()) {
        $billing[] = $row;
    }

    echo json_encode($billing);

    $stmt->close();
} else {
    http_response_code(400);
    echo json_encode(["error" => "Missing id or userId parameter"]);
}

$conn->close();
