<?php

// Session + Node (DB access must be in Node)
include '../includes/session_control.php';
include __DIR__ . '/api/_node.php';
include($_SERVER['DOCUMENT_ROOT'] . '/funciones/funciones.php');

// Avoid corrupting PNG output
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);
date_default_timezone_set('America/Bogota');

// Params
$id_cotizacion = isset($_GET['id_cotizacion']) ? (int)$_GET['id_cotizacion'] : 0;
$offset = isset($_GET['desde']) ? (int)$_GET['desde'] : 0;
$pag = isset($_GET['pag']) ? (int)$_GET['pag'] : 1;
$pags = isset($_GET['pags']) ? (int)$_GET['pags'] : 1;
$tipo = isset($_GET['tipo']) ? (int)$_GET['tipo'] : 1;

if ($id_cotizacion <= 0) {
    http_response_code(400);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Parámetro id_cotizacion inválido.';
    exit;
}
if ($offset < 0) $offset = 0;
if ($pag < 1) $pag = 1;
if ($pags < 1) $pags = 1;
if ($tipo !== 1 && $tipo !== 2) $tipo = 1;

// Fetch page data from Node
$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$url = $base . '/api/cotizaciones/' . $id_cotizacion . '/pdf/page'
    . '?tipo=' . urlencode((string)$tipo)
    . '&offset=' . urlencode((string)$offset)
    . '&limit=9'
    . '&pag=' . urlencode((string)$pag)
    . '&pags=' . urlencode((string)$pags);

$resp = cpn_node_request('GET', $url, $token);
if (!isset($resp['ok']) || $resp['ok'] !== true) {
    $http = $resp['_http'] ?? 500;
    $msg = $resp['error']['message'] ?? 'Error consultando datos en Node.';
    http_response_code((int)$http);
    header('Content-Type: text/plain; charset=utf-8');
    echo $msg;
    exit;
}

$data = $resp['data'] ?? null;
if (!is_array($data) || !is_array($data['header'] ?? null)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Respuesta inválida de Node.';
    exit;
}

$row = $data['header'];
$items = is_array($data['items'] ?? null) ? $data['items'] : [];
$totals = is_array($data['totals'] ?? null) ? $data['totals'] : null;

$fondoblanco = $_SERVER['DOCUMENT_ROOT'] . '/cotizaciones/fondos/tipo1.png';
$rutafondo = $_SERVER['DOCUMENT_ROOT'] . '/cotizaciones/fondos/tipo1.png';
$anchoposter = 1650;
$altoposter = 1275;

$fondo = imagecreatetruecolor($anchoposter, $altoposter);
$fondo = imagenposter($fondoblanco, $anchoposter, $altoposter);

$idCotizacion = $row['idCotizacion'] ?? $id_cotizacion;
$usuario = trim(($row['nombre'] ?? '') . ' ' . ($row['apellido'] ?? ''));
$telefono = $row['telefono'] ?? '';
$email = $row['email'] ?? '';
$ciudad = trim(($row['departamento'] ?? '') . ' - ' . ($row['ciudad'] ?? ''));
$fechaFormateada = '';
if (!empty($row['fechaCreacion'])) {
    try {
        $fechaFormateada = (new DateTime($row['fechaCreacion']))->format('d-M-y');
    } catch (Exception $e) {
        $fechaFormateada = '';
    }
}

centrartexto($idCotizacion, "Poppins-SemiBold.otf", $fondo, 25, 'ffffff', 3000, 113, 0);
izqtexto($usuario, "Poppins-Regular.otf", $fondo, 16, '000000', 230, 210, 0, 1000);
izqtexto($telefono, "Poppins-Regular.otf", $fondo, 16, '000000', 870, 210, 0, 1000);
izqtexto($fechaFormateada, "Poppins-Regular.otf", $fondo, 16, '000000', 1290, 210, 0, 1000);
izqtexto($ciudad, "Poppins-Regular.otf", $fondo, 16, '000000', 230, 260, 0, 1000);
izqtexto($email, "Poppins-Regular.otf", $fondo, 16, '000000', 870, 260, 0, 1000);
centrartexto($pag . ' de ' . $pags, "Poppins-SemiBold.otf", $fondo, 18, '4c4b4b', 3200, 303, 0);

if ($tipo == 1 && is_array($totals)) {
    $totalcotizacion = 'Subtotal: $ ' . number_format((float)($totals['subtotal'] ?? 0), 0, '', ',')
        . ' /  IVA: $ ' . number_format((float)($totals['iva'] ?? 0), 0, '', ',')
        . ' / Total: $ ' . number_format((float)($totals['total'] ?? 0), 0, '', ',');
    centrartexto($totalcotizacion, "Poppins-SemiBold.otf", $fondo, 16, 'ffffff', 2500, 1240, 0);
}

$xinicial = 520;
$incremento = 80;

foreach ($items as $row2) {
    if (!is_array($row2)) continue;
    $referenciaCPN = $row2['referenciaCPN'] ?? '';
    $imgproducto = str_replace('J:/images', 'https://sistema.compranet.com.co/images', (string)($row2['linkImagen'] ?? ''));
    $descripcion = trim(($row2['nombre'] ?? '') . ' - ' . ($row2['txtColor'] ?? ''));
    $txtMedidas = isset($row2['txtMedidas']) && $row2['txtMedidas'] !== '' ? $row2['txtMedidas'] : '-';
    $cantNum = (float)($row2['cantidad'] ?? 0);
    $precioNum = (float)($row2['precioVenta'] ?? 0);
    $impVal = (float)($row2['impuestoValor'] ?? 0);

    $cantidad = number_format($cantNum, 0, '', '.');
    $precioVenta = '$' . number_format($precioNum, 0, '', ',');
    $subtotal = '$' . number_format($cantNum * $precioNum, 0, '', ',');
    $iva = '$' . number_format($cantNum * $precioNum * $impVal, 0, '', ',');
    $total = '$' . number_format(($cantNum * $precioNum * $impVal) + ($cantNum * $precioNum), 0, '', ',');
    $observaciones = $row2['observaciones'] ?? '';

    if ($imgproducto) {
        nuevaimagen($fondo, $imgproducto, 100, 100, 60, $xinicial - 55);
    }
    centrartexto($referenciaCPN, "Poppins-Regular.otf", $fondo, 14, '000000', 495, $xinicial, 0);
    izqtexto($descripcion, "Poppins-Regular.otf", $fondo, 12, '000000', 350, $xinicial - 15, 0, 190);
    centrartextolineas($txtMedidas, "Poppins-Regular.otf", $fondo, 10, '000000', 610, $xinicial - 10, 0, 130);
    centrartexto($cantidad, "Poppins-Regular.otf", $fondo, 14, '000000', 1475, $xinicial, 0);
    centrartexto($precioVenta, "Poppins-Regular.otf", $fondo, 14, '000000', 1730, $xinicial, 0);
    centrartexto($subtotal, "Poppins-Regular.otf", $fondo, 14, '000000', 2050, $xinicial, 0);
    centrartexto($iva, "Poppins-Regular.otf", $fondo, 14, '000000', 2290, $xinicial, 0);
    centrartexto($total, "Poppins-Regular.otf", $fondo, 14, '000000', 2550, $xinicial, 0);
    izqtexto($observaciones, "Poppins-Regular.otf", $fondo, 10, '000000', 1380, $xinicial - 15, 0, 190);

    $xinicial += $incremento;
}


if (function_exists('ob_get_length') && ob_get_length()) {
    @ob_clean();
}
Header("Content-type: image/png");
imagepng($fondo);
imagedestroy($fondo);
