<?php

// Session control + Node API helper
include '../includes/session_control.php';
include __DIR__ . '/api/_node.php';
include($_SERVER['DOCUMENT_ROOT'] . '/funciones/funciones.php');

// Avoid corrupting binary image output with warnings/notices
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);
date_default_timezone_set('America/Bogota');
// Get the id_cotizacion_detalle from the URL
$id_cotizacion_detalle = isset($_GET['id_cotizacion_detalle']) ? (int)$_GET['id_cotizacion_detalle'] : 0;
if ($id_cotizacion_detalle <= 0) {
    http_response_code(400);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'Parámetro id_cotizacion_detalle inválido.';
    exit;
}

// Fetch the details from Node API (DB access must live in Node)
$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$url = $base . '/api/cotizaciones/items/' . $id_cotizacion_detalle . '/imgwp';

$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;
}

$row = $resp['data'] ?? null;
if (!is_array($row) || empty($row)) {
    http_response_code(404);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'No se encontró el ítem solicitado.';
    exit;
}

$fondoblanco = $_SERVER['DOCUMENT_ROOT'] . '/cotizaciones/formatowp.png';
if (!file_exists($fondoblanco)) {
    http_response_code(500);
    header('Content-Type: text/plain; charset=utf-8');
    echo 'No se encontró la plantilla para generar la imagen.';
    exit;
}
$rutafondo = str_replace('J:/images', 'https://sistema.compranet.com.co/images', $row['linkImagen']);
$anchoposter = 1080;
$altoposter = 1350;

imagecreatetruecolor($anchoposter, $altoposter);
$fondo = imagenposter($fondoblanco, $anchoposter, $altoposter);

nuevaimagen($fondo, $fondoblanco, 1080, 1350, 0, 0);



//Variables
$imgproducto = str_replace('J:/images', 'https://sistema.compranet.com.co/images', $row['linkImagen']);
$fecha = date('d-M-y', strtotime('today'));
$referenciaCPN = 'SKU: ' . $row['referenciaCPN'];
$txtColor = $row['txtColor'];
$cantidad = 'Cantidad: ' . number_format($row['cantidad'], 0, ',', '.') . ' unds';
$precioVenta = 'Precio und antes de IVA: $' . number_format($row['precioVenta'], 0, ',', '.');
$precioVentaIvaInc = 'Precio und con IVA: $' . number_format(($row['precioVenta'] * (1 + $row['impuesto'])), 0, ',', '.');
$titulo = $row['nombre'];
$descripcion = $row['descripcion'] . ' Color/Tipo: ' . $txtColor;
$txtMedidas = !empty($row['txtMedidas']) ? $row['txtMedidas'] : '-';
$txtMaterial = !empty($row['txtMaterial']) ? $row['txtMaterial'] : '-';
$txtMarca = !empty($row['txtMarca']) ? $row['txtMarca'] : '-';
$txtAreaLogo = !empty($row['txtAreaLogo']) ? $row['txtAreaLogo'] : '-';
$txtEmpaque = !empty($row['txtEmpaque']) ? $row['txtEmpaque'] : '-';
$txtObservaciones = 'Observaciones: ' . (!empty($row['Observaciones']) ? $row['Observaciones'] : '-');


nuevaimagen($fondo, $imgproducto, 500, 500, 290, 198);

centrartexto($titulo, "Poppins-SemiBold.otf", $fondo, 25, '000000', 1080, 180, 0);
centrartextolineas($descripcion, "Poppins-Regular.otf", $fondo, 10, '000000', 540, 205, 0, 1000);
centrartexto($referenciaCPN . ' / ' . $fecha, "Poppins-SemiBold.otf", $fondo, 18, 'ffffff', 1750, 95, 0);
centrartexto($cantidad, "Poppins-SemiBold.otf", $fondo, 16, 'ffffff', 1080, 795, 0);
centrartexto($precioVenta, "Poppins-SemiBold.otf", $fondo, 16, 'ffffff', 570, 870, 0);
centrartexto($precioVentaIvaInc, "Poppins-SemiBold.otf", $fondo, 16, 'ffffff', 1570, 870, 0);
izqtexto($txtObservaciones, "Poppins-Regular.otf", $fondo, 16, 'ffffff', 90, 950, 0, 1000);
izqtexto($txtMaterial, "Poppins-Regular.otf", $fondo, 14, '000000', 210, 1075, 0, 1000);
izqtexto($txtMedidas, "Poppins-Regular.otf", $fondo, 14, '000000', 740, 1079, 0, 500);
izqtexto($txtMarca . ' - ' . $txtAreaLogo, "Poppins-Regular.otf", $fondo, 13, '000000', 110, 1135, 0, 980);



// Replace the path

//error_log("Background image path: " . $background_image);

//$fondoblanco='fondoblanco.png';



if (function_exists('ob_get_length') && ob_get_length()) {
    @ob_clean();
}
Header("Content-type: image/png");
imagepng($fondo);
imagedestroy($fondo);
