<?
header('Content-Type: application/json');
$r="../../";
require_once($r."inc/funciones.php");
$mysqli = connectDB($r);
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $nombre = isset($_POST['empresa']) ? trim($_POST['empresa']) : '';
    $nit    = isset($_POST['nit']) ? trim($_POST['nit']) : '';

    if ($nombre === '' && $nit === '') {
        echo json_encode([
            "status" => "error",
            "message" => "Debe enviar al menos NIT o Nombre"
        ]);
        exit;
    }

    if ($nit !== '') {
        $sql = "SELECT * FROM `z_cotizacion` WHERE `nit` = ? ORDER BY `id` DESC LIMIT 1";
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("s", $nit);
    } else {
        $sql = "SELECT * FROM `z_cotizacion` WHERE `empresa` = ? ORDER BY `id` DESC LIMIT 1";
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("s", $nombre);
    }

    $stmt->execute();
    $result = $stmt->get_result();

    if ($row = $result->fetch_assoc()) {
        echo json_encode([
            "status" => "success",
            "cotizacion" => $row
        ]);
    } else {
        echo json_encode([
            "status" => "not_found",
            "message" => "No se encontraron cotizaciones"
        ]);
    }

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

} else {
    echo json_encode([
        "status" => "error",
        "message" => "Método no permitido"
    ]);
}