<?php
require_once "./pdocontroller.php";

$id_encabezado = $_POST['idfactura'] ?? $_REQUEST['idfactura'] ?? '';
$codempresa = $_POST['codemp'] ?? $_REQUEST['codemp'] ?? '';

if (empty($id_encabezado) || empty($codempresa)) {
    echo json_encode(["error" => "Faltan datos"]);
    exit;
}

if ($codempresa !== 'DND') {
    $DBclase = "PDO" . $codempresa;
} else {
    echo json_encode(["error" => "Empresa no válida"]);
    exit;
}
$DBconex = new $DBclase;

$query = "SELECT compras.nriper, compras.nomper, actres.nrores, actres.preres, comprasdet.artcod, comprasdet.canart, comprasdet.nomdet as dspdcm, 
    comprasdet.vlrdcm, comprasdet.pordto, comprasdet.poriva, compras.codfte, comprasdet.pjefte, comprasdet.nrodud, comprasdet.artser, compras.vlrant, 
    compras.fchini, compras.numfel, compras.fchcmp, compras.fincmp, compras.nrorem, respfiscal.coddat as resfiscal,
    CASE WHEN compras.tpocmp = 1 THEN 'DEBITO' ELSE 'CREDITO' END AS fpgod,
    CASE WHEN compras.obscmp = '' THEN 'FE' ELSE compras.obscmp END AS observacion,
    actper.emlper, actper.telper as telter, actper.tidper, actper.tipper, actper.resfis, actper.tipreg, 
    actper.codciu, actper.dirper as dirter, actper.paiper, actper.no1per, actper.ap1per 
FROM actres, compras, comprasdet, actper, respfiscal 
WHERE compras.Id = comprasdet.idfactura 
  AND actper.nriper = compras.nriper 
  AND compras.codfte = actres.codfte 
  AND compras.estado != 'Eliminado' 
  AND actper.resfis = respfiscal.codres 
  AND actres.estres != 'Inactiva' 
  AND compras.Id = :idfactura";

$parametros = [':idfactura' => $id_encabezado];

try {
    $datos = $DBconex->executeconsulta($query, $parametros);
    if (!is_array($datos) || count($datos) === 0) {
        echo json_encode(["error" => "Factura no encontrada"]);
        exit;
    }

    $items = [];
    $qdatos = $datos[0];

    $vAnt = $qdatos["vlrant"];
    $preFe = $qdatos["preres"];
    $numfel = $qdatos["numfel"];
    $cFactura = $preFe . $numfel;

    $DBconexLic = new PDOCONTROLLER;
    $datosFe = $DBconexLic->executeconsulta(
        "SELECT conedb, apifel, keyemp, keyfel, prvfel, noemail FROM licemp WHERE conedb = :empresa",
        [':empresa' => $codempresa]
    );

    if (empty($datosFe)) {
        echo json_encode(["error" => "Empresa no habilitada para FE"]);0 
        exit;
    }

    $qLoc = $datosFe[0];
    $gRutaApi = trim($qLoc['apifel']) . "?keyemp=" . trim($qLoc['keyfel']);
    $gKey = trim($qLoc['keyemp']);
    $noEmail = trim($qLoc['noemail']);
    $email = !empty($qdatos["emlper"]) ? $qdatos["emlper"] : $noEmail;

    foreach ($datos as $detalle) {
        $items[] = [
            "sku" => $detalle["artcod"],
            "quantity" => floatval($detalle["canart"]),
            "description" => $detalle["dspdcm"] . " GUIA",
            "price" => floatval($detalle["vlrdcm"])
        ];
    }

    $invoice = [
        "items" => $items
    ];

    $support_doc = [
        "env" => "PRODUCCION",
        "send_dian" => true,
        "send_email" => true,
        "number" => $numfel,
        "issue_date" => $qdatos["fchcmp"],
        "payment_date" => $qdatos["fincmp"],
        "resident_type" => "RESIDENTE",
        "generation_type" => "POR_OPERACION",
        "order_reference" => $qdatos["nrorem"],
        "payment_means" => "CASH",
        "payment_means_type" => "CREDITO",
        "currency" => "COP",
        "numbering" => [
            "resolution_number" => $qdatos["nrores"],
            "prefix" => $qdatos["preres"],
            "flexible" => true
        ],
        "notes" => [$qdatos["observacion"]],
        "customer" => [
            "email" => $email,
            "phone" => $qdatos["telter"],
            "party_identification_type" => ($qdatos["tipper"] === 'JUR') ? 'PERSONA_JURIDICA' : 'PERSONA_NATURAL',
            "party_identification" => $qdatos["nriper"],
            "party_type" => ($qdatos["tipper"] === 'JUR') ? 'PERSONA_JURIDICA' : 'PERSONA_NATURAL',
            "tax_level_code" => ($qdatos["tipreg"] === '49') ? 'SIMPLIFICADO' : 'RESPONSABLE_DE_IVA',
            "regimen" => trim($qdatos["resfiscal"]),
            "department" => substr($qdatos["codciu"], 0, 2),
            "city" => substr($qdatos["codciu"], -3),
            "address_line" => $qdatos["dirter"],
            "country_code" => "CO",
            "company_name" => $qdatos["nomper"],
            "first_name" => $qdatos["no1per"],
            "family_name" => $qdatos["ap1per"]
        ],
        "invoice" => $invoice
    ];

    $jsond = json_encode(["support_doc" => $support_doc], JSON_UNESCAPED_UNICODE);
    $gRutafe = $gRutaApi . "&numero=" . $numfel . "&chkfte=1&documento=" . $cFactura . "&prefijo=" . $preFe . "&empresa=" . $codempresa . "&accion=D";

    $queryFe = "INSERT INTO documentos (codigo, codemp, chkfte, nombre, email, fecha, insfch, codfte, prefijo, consecutive, estructura, jsond, rutaenvio) 
                VALUES (:codigo, :codemp, 1, :nombre, :email, :fecha, :insfch, :codfte, :prefijo, :consecutive, :jsond, :jsond, :rutaenvio)";
    
    $paramFe = [
        ':codigo' => $cFactura,
        ':codemp' => $codempresa,
        ':nombre' => $qdatos["nomper"],
        ':email' => $email,
        ':fecha' => $qdatos["fchcmp"],
        ':insfch' => $qdatos["fchcmp"],
        ':codfte' => $qdatos["codfte"],
        ':prefijo' => $qdatos["preres"],
        ':consecutive' => $numfel,
        ':jsond' => $jsond,
        ':rutaenvio' => $gRutafe
    ];

    $insertado = $DBconex->execute_insert($queryFe, $paramFe);

    if ($insertado) {
        echo json_encode(["success" => true, "rutaFE" => $gRutafe]);
    } else {
        echo json_encode(["error" => "Error al insertar en documentos"]);
    }

} catch (Exception $ex) {
    echo json_encode(["error" => $ex->getMessage()]);
}
?>
