<?php
// @php83-utf8-shim
if (!function_exists('utf8_encode')) { function utf8_encode($s) { return mb_convert_encoding($s, 'UTF-8', 'ISO-8859-1'); } }
if (!function_exists('utf8_decode')) { function utf8_decode($s) { return mb_convert_encoding($s, 'ISO-8859-1', 'UTF-8'); } }
session_start();
require('fpdf186/fpdf.php');
require_once('QRcode/qrcode.class.php');
header('Content-Type: text/html; charset=UTF-8');

date_default_timezone_set("America/La_Paz");
include "core/autoload.php";

include "core/app/model/ChanceData.php";
include "core/app/model/PersonData.php";
include "core/app/model/ContactData.php";
include "core/app/model/PaymentData.php";
include "core/app/model/ProductData.php";
include "core/app/model/ProductosData.php";
include "core/app/model/ProductStockData.php";
include "core/app/model/ProposalData.php";
include "core/app/model/ProposalDetailData.php";
include "core/app/model/ProposalQuoteData.php";
include "core/app/model/UserData.php";
include "core/app/model/BrandData.php";

class PDF extends FPDF
{
	protected $widths;
	protected $aligns;


	// Método para dibujar una fila con alineaciones específicas
	function SimpleRow($data, $widths, $aligns)
	{
		// Recorremos los datos para imprimir cada celda
		foreach ($data as $key => $value) {
			$this->MultiCell(
				$widths[$key],  // Ancho de la celda
				0,             // Altura de la celda
				$value,         // Texto a mostrar
				0,              // Sin bordes
				$aligns[$key]   // Alineación de la celda
			);
			$this->SetXY($this->GetX() + $widths[$key], $this->GetY()); // Ajuste la posición para la siguiente celda
		}
		$this->Ln(); // Salto de línea al terminar la fila
	}

	function SetWidths($w)
	{
		// Set the array of column widths
		$this->widths = $w;
	}

	function SetAligns($a)
	{
		// Set the array of column alignments
		$this->aligns = $a;
	}

	function Row($data)
	{
		// Calculate the height of the row
		$nb = 0;
		for ($i = 0; $i < count($data); $i++)
			$nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
		$h = 5 * $nb;
		// Issue a page break first if needed
		$this->CheckPageBreak($h);
		// Draw the cells of the row
		for ($i = 0; $i < count($data); $i++) {
			$w = $this->widths[$i];
			$a = isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';
			// Save the current position
			$x = $this->GetX();
			$y = $this->GetY();
			// Draw the border
			//$this->Rect($x, $y, $w, $h);
			// Print the text
			$this->MultiCell($w, 5, $data[$i], 0, $a);
			// Put the position to the right of the cell
			$this->SetXY($x + $w, $y);
		}
		// Go to the next line
		$this->Ln($h);
	}

	function CheckPageBreak($h)
	{
		// If the height h would cause an overflow, add a new page immediately
		if ($this->GetY() + $h > $this->PageBreakTrigger)
			$this->AddPage($this->CurOrientation);
	}

	function NbLines($w, $txt)
	{
		// Compute the number of lines a MultiCell of width w will take
		if (!isset($this->CurrentFont))
			$this->Error('No font has been set');
		$cw = $this->CurrentFont['cw'];
		if ($w == 0)
			$w = $this->w - $this->rMargin - $this->x;
		$wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize;
		$s = str_replace("\r", '', (string) $txt);
		$nb = strlen($s);
		if ($nb > 0 && $s[$nb - 1] == "\n")
			$nb--;
		$sep = -1;
		$i = 0;
		$j = 0;
		$l = 0;
		$nl = 1;
		while ($i < $nb) {
			$c = $s[$i];
			if ($c == "\n") {
				$i++;
				$sep = -1;
				$j = $i;
				$l = 0;
				$nl++;
				continue;
			}
			if ($c == ' ')
				$sep = $i;
			$l += $cw[$c];
			if ($l > $wmax) {
				if ($sep == -1) {
					if ($i == $j)
						$i++;
				} else
					$i = $sep + 1;
				$sep = -1;
				$j = $i;
				$l = 0;
				$nl++;
			} else
				$i++;
		}
		return $nl;
	}
	function createQRCode($x, $y, $data, $size = 30)
	{
		$qrcode = new QRcode(utf8_encode($data), 'H');
		$qrcode->disableBorder();
		$qrcode->displayFPDF($this, $x, $y, $size);
	}
	function Header()
	{
		$prop = ProposalData::getById($_GET["id"]);
		$pay = PaymentData::getById(1);
		$us = UserData::getById($prop->user_id);
		$client = PersonData::getById($prop->getChance()->person_id);

		// Create QR code data string
		$qrData = "COT:" . $GLOBALS['nbill'] . "\n";
		$qrData .= "FECHA:" . $GLOBALS['dia'] . "/" . $GLOBALS['mes'] . "/" . $GLOBALS['anio'] . "\n";
		$qrClientName = trim((string)($GLOBALS['client']->name_c ?? ''));
		if ($qrClientName === '') {
			$qrClientName = trim((string)($GLOBALS['client']->name ?? 'Sin cliente'));
		}
		$qrData .= "CLIENTE:" . $qrClientName . "\n";
		$qrData .= "TOTAL:Bs." . number_format($GLOBALS['total'], 2);

		if ($this->PageNo() == 1) {


			// Add QR Code to bottom left
			$this->createQRCode(110, 15, $qrData, 20); // Reduced size from 30 to 20
			$this->SetY(-10);
			$this->SetFont('Arial', 'B', 8);

			//Logo
			$this->SetFillColor(0, 0, 0);
			$this->Image('logo_tykun.png', 140, 10, 60);
			$this->Cell(189, 20, '', 0, 1); //end of line
			//Arial bold 15
			$this->SetFont('Arial', 'B', 8);
			//Movernos a la derecha
			$this->Cell(30);
			// TITULO
			$this->SetFont('Arial', 'B', 18);
			$this->SetXY(14, 10);
			$this->Cell(50, 10, mb_convert_encoding('COTIZACIÓN', 'ISO-8859-1'), 0, 0, 'L');
			// NUMERO DE COTIZACIÓN
			$this->SetTextColor(0, 153, 255);
			$this->SetFont('Arial', 'B', 10);
			$this->SetXY(14, 20);
			$this->Cell(5, 4, str_pad($prop->id, 5, '0', STR_PAD_LEFT) . '/' . date('Y'), 0, 0);
			$this->SetTextColor(0, 0, 0);
			// FECHA
			$this->SetXY(14, 25);
			$this->Cell(40, 10, mb_convert_encoding('Fecha: ', 'ISO-8859-1'), 0, 0, 'L');
			$this->SetFont('Arial', '', 10);
			$this->SetXY(28, 25);
			$this->Cell(40, 10, $GLOBALS['dia'] . '/' . $GLOBALS['mes'] . '/' . $GLOBALS['anio'], 0, 0, 'L');
			// VALIDEZ
			$this->SetXY(14, 30);
			$this->SetFont('Arial', 'B', 10);
			$this->Cell(40, 10, mb_convert_encoding('Validez: ', 'ISO-8859-1'), 0, 0, 'L');
			$this->SetFont('Arial', '', 10);
			$this->SetXY(28, 30);
			$this->Cell(40, 10, $prop->validity . mb_convert_encoding(' días calendario ', 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');
			// LINEA AZUL
			$this->SetDrawColor(0, 153, 255); // RGB para azul
			$this->SetLineWidth(0.6);
			$this->Line(14, 42, 130, 42); // (x1, y1, x2, y2)
			// DIRECCION TYKUN
			$this->SetXY(200, 30);
			$this->Cell(1, 1, mb_convert_encoding('Calle Manuel Mariaca Nro 1280', 'ISO-8859-1', 'UTF-8'), 0, 0, 'R');
			$this->SetXY(200, 35);
			$this->Cell(1, 1, mb_convert_encoding('Edificio Espacio Miraflores', 'ISO-8859-1', 'UTF-8'), 0, 0, 'R');
			$this->SetXY(200, 40);
			$this->Cell(1, 1, mb_convert_encoding('La Paz - Bolivia', 'ISO-8859-1', 'UTF-8'), 0, 0, 'R');
			$this->SetXY(200, 45);
			$this->Cell(1, 1, mb_convert_encoding('63167327 - 60695047', 'ISO-8859-1'), 0, 0, 'R');
			$this->SetXY(200, 50);
			$this->Cell(1, 1, mb_convert_encoding('info@consultora-tykun.com', 'ISO-8859-1', 'UTF-8'), 0, 0, 'R');
			// CLIENTE
			$this->SetFont('Arial', 'B', 10);
			$this->SetXY(14, 55);
			$this->Cell(40, 10, mb_convert_encoding('Cliente: ', 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');
			$this->SetFont('Arial', '', 10);
			$this->SetXY(35, 55);
			$client_name = trim((string)($client->name_c ?? ''));
			if ($client_name === '') {
				$client_name = trim((string)($client->name ?? 'Sin cliente'));
			}
			$this->Cell(80, 10, mb_convert_encoding(html_entity_decode($client_name, ENT_QUOTES | ENT_HTML5, 'UTF-8'), 'ISO-8859-1', 'UTF-8'), 0, 0, 'L');

			// // REFERENCIA
			// $this->SetFont('Arial', 'B', 10);
			// $this->SetXY(14, 65);
			// $this->Cell(40, 10, mb_convert_encoding('Referencia: ', 'ISO-8859-1'), 0, 0, 'L');
			// $this->SetFont('Arial', '', 10);
			// $this->SetXY(35, 65);
			// $this->Cell(40, 10, mb_convert_encoding(html_entity_decode($prop->description, ENT_QUOTES | ENT_HTML5, 'UTF-8'), 'ISO-8859-1', 'UTF-8'), 0, 1, 'L');
			// LINEA PLOMA
			$this->SetDrawColor(211, 211, 211);
			$this->Line(14, 65, 200, 65);
			// TÉRMINOS Y CONDICIONES

			$this->SetXY(14, 73);
			$lineHeight = 6;
			$labelWidth = 50;
			$valueWidth = 150;

			// Garantia
			$this->SetFont("Arial", "B", 10);
			$this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Garantía:", "ISO-8859-1"), 0, 0, "L");
			$this->SetFont("Arial", "", 10);
			$warranty = isset($prop->warranty) ? $prop->warranty : 12;
			$this->Cell($valueWidth, $lineHeight, mb_convert_encoding($warranty . " meses", "ISO-8859-1"), 0, 1, "L");
			$this->SetXY(14, 79);
			// Tiempo de Entrega
			$this->SetFont("Arial", "B", 10);
			$this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Tiempo de Entrega:", "ISO-8859-1"), 0, 0, "L");
			$this->SetFont("Arial", "", 10);
			$delivery = isset($prop->delivery) ? html_entity_decode($prop->delivery, ENT_QUOTES | ENT_HTML5, "UTF-8") : "Inmediata";
			$this->Cell($valueWidth, $lineHeight, mb_convert_encoding($delivery, "ISO-8859-1"), 0, 0, "L");
			$this->SetXY(14, 85);
			// Lugar de Entrega
			$this->SetFont("Arial", "B", 10);
			$this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Lugar de Entrega:", "ISO-8859-1"), 0, 0, "L");
			$this->SetFont("Arial", "", 10);
			$place = isset($prop->place) ? html_entity_decode($prop->place, ENT_QUOTES | ENT_HTML5, "UTF-8") : "";
			$this->Cell($valueWidth, $lineHeight, mb_convert_encoding($place ?: "-", "ISO-8859-1"), 0, 1, "L");
			$this->SetXY(14, 91);
			// Condiciones de Pago
			$this->SetFont("Arial", "B", 10);
			$this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Condiciones de Pago:", "ISO-8859-1"), 0, 0, "L");
			$this->SetFont("Arial", "", 10);
			$conditions_text = trim((string)($prop->conditions ?? ""));
			if ($conditions_text !== "") {
				$this->MultiCell($valueWidth, $lineHeight, mb_convert_encoding(html_entity_decode($conditions_text, ENT_QUOTES | ENT_HTML5, "UTF-8"), "ISO-8859-1", "UTF-8"), 0, "L");
			} else {
				$this->MultiCell($valueWidth, $lineHeight, mb_convert_encoding("20% - con el pedido de compra;\n30% - a 30 días del pedido;\n50% - con el aviso de embarque", "ISO-8859-1"), 0, "L");
			}
			$this->SetXY(14, 97);
			// Formas de Pago
			$this->SetFont("Arial", "B", 10);
			$this->Cell($labelWidth, $lineHeight, mb_convert_encoding("Formas de Pago:", "ISO-8859-1"), 0, 0, "L");
			$this->SetFont("Arial", "", 10);
			$forma_text = trim((string)($prop->note ?? ""));
			if ($forma_text !== "") {
				$this->MultiCell($valueWidth, $lineHeight, mb_convert_encoding(html_entity_decode($forma_text, ENT_QUOTES | ENT_HTML5, "UTF-8"), "ISO-8859-1", "UTF-8"), 0, "L");
			} else {
				$this->MultiCell($valueWidth, $lineHeight, mb_convert_encoding("CHEQUE, EFECTIVO, VÍA SIGEP", "ISO-8859-1"), 0, "L");
			}
			//Salto de linea
			$this->Ln(10);
		}
	}

	function Footer()
	{
		$this->SetY(-10);
		$this->SetFont('Arial', 'B', 8);
		$totalWidth = 60 + 60 + 60; // Suma de los anchos de las celdas
		$pageWidth = $this->GetPageWidth(); // Ancho de la página
		$startX = ($pageWidth - $totalWidth) / 2; // Calcular inicio centrado
		$this->SetX($startX); // Mover al centro
		$this->SetDrawColor(0, 0, 0); // Negro para las celdas normales
		$this->SetLineWidth(0.2); // Grosor estándar
		$this->SetDrawColor(255, 255, 255);
		$this->Cell(60, 5, 'TYKUN', 1, 0, 'C');
		$this->Cell(60, 5, 'Codigo: CTZ-' . str_pad($prop->id, 5, '0', STR_PAD_LEFT), 1, 0, 'C');
		$this->Cell(60, 5, 'V: 31/12/2026', 1, 1, 'C');
		// Configurar el color azul solo para la línea inferior
		$this->SetDrawColor(211, 211, 211); // Azul
		$this->SetLineWidth(0.6);
		$this->Line(14, 267, 200, 267); // (x1, y1, x2, y2)
	}

	protected $B = 0;
	protected $I = 0;
	protected $U = 0;
	protected $HREF = '';

	function WriteHTML($html)
	{
		// HTML parser
		$html = str_replace("\n", ' ', $html);
		$a = preg_split('/<(.*)>/U', $html, -1, PREG_SPLIT_DELIM_CAPTURE);
		foreach ($a as $i => $e) {
			if ($i % 2 == 0) {
				// Text
				if ($this->HREF)
					$this->PutLink($this->HREF, $e);
				else
					$this->Write(5, $e);
			} else {
				// Tag
				if ($e[0] == '/')
					$this->CloseTag(strtoupper(substr($e, 1)));
				else {
					// Extract attributes
					$a2 = explode(' ', $e);
					$tag = strtoupper(array_shift($a2));
					$attr = array();
					foreach ($a2 as $v) {
						if (preg_match('/([^=]*)=["\']?([^"\']*)/', $v, $a3))
							$attr[strtoupper($a3[1])] = $a3[2];
					}
					$this->OpenTag($tag, $attr);
				}
			}
		}
	}

	function OpenTag($tag, $attr)
	{
		// Opening tag
		if ($tag == 'B' || $tag == 'I' || $tag == 'U')
			$this->SetStyle($tag, true);
		if ($tag == 'A')
			$this->HREF = $attr['HREF'];
		if ($tag == 'BR')
			$this->Ln(5);
	}

	function CloseTag($tag)
	{
		// Closing tag
		if ($tag == 'B' || $tag == 'I' || $tag == 'U')
			$this->SetStyle($tag, false);
		if ($tag == 'A')
			$this->HREF = '';
	}

	function SetStyle($tag, $enable)
	{
		// Modify style and select corresponding font
		$this->$tag += ($enable ? 1 : -1);
		$style = '';
		foreach (array('B', 'I', 'U') as $s) {
			if ($this->$s > 0)
				$style .= $s;
		}
		$this->SetFont('', $style);
	}

	function PutLink($URL, $txt)
	{
		// Put a hyperlink
		$this->SetTextColor(0, 0, 255);
		$this->SetStyle('U', true);
		$this->Write(5, $txt, $URL);
		$this->SetStyle('U', false);
		$this->SetTextColor(0);
	}
}
$prop = ProposalData::getById($_GET["id"]);
$pay = PaymentData::getById(1);
$us = UserData::getById($prop->user_id);
$client = PersonData::getById($prop->getChance()->person_id);

$selectedProducts = [];
if (isset($_GET['products'])) {
	// Check if it's a single product or multiple products
	if (strpos($_GET['products'], ',') !== false) {
		$selectedProducts = explode(',', $_GET['products']);
	} else {
		$selectedProducts = [$_GET['products']];
	}
}

$bill = $prop->id;
$nbill = str_pad($prop->id, 5, '0', STR_PAD_LEFT);
$sdate = $prop->created_at;
$hora = date('h:m:s', strtotime($sdate));
$dia = date('d', strtotime($sdate));
$anio = date('Y', strtotime($sdate));
$mes = date('m', strtotime($sdate));
$total = 0;

if ($mes == '01')
	$letra = 'Enero';
if ($mes == '02')
	$letra = 'Febrero';
if ($mes == '03')
	$letra = 'Marzo';
if ($mes == '04')
	$letra = 'Abril';
if ($mes == '05')
	$letra = 'Mayo';
if ($mes == '06')
	$letra = 'Junio';
if ($mes == '07')
	$letra = 'Julio';
if ($mes == '08')
	$letra = 'Agosto';
if ($mes == '09')
	$letra = 'Septiembre';
if ($mes == '10')
	$letra = 'Octubre';
if ($mes == '11')
	$letra = 'Noviembre';
if ($mes == '12')
	$letra = 'Diciembre';

$pdf = new PDF('P', 'mm', 'letter');
$pdf->AliasNbPages();
$pdf->AddPage();
$widths = [20, 76, 22, 30, 23];
// $widths = [2, 100, 30, 35];
$pdf->SetXY(14, 120);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell($widths[0], 5, 'CANT.', 0, 0, 'C');
$pdf->Cell($widths[1], 5, 'DESCRIPCION', 0, 0, 'C');
$pdf->Cell($widths[2], 5, 'UNID.', 0, 0, 'C');
$pdf->Cell($widths[3], 5, 'P. UNIT.', 0, 0, 'C');
$pdf->Cell($widths[4], 5, 'SUBTOTAL', 0, 1, 'C');


// LINEA PLOMA
$pdf->SetDrawColor(211, 211, 211); // RGB para azul
$pdf->SetLineWidth(0.6);
$pdf->Line(14, 127, 200, 127); // (x1, y1, x2, y2)
$pdf->SetDrawColor(0, 0, 0);
$pdf->SetLineWidth(0.0);
$pdf->SetXY(10, 130);
$pdf->SetFont('Arial', '', 10);

// Configuración de anchos y alineaciones
// $widths = [30, 90, 35, 30];      // Anchos de las columnas
$widths = [20, 76, 22, 30, 23];      // Anchos de las columnas
$aligns = ['C', 'L', 'C', 'R', 'R'];   // Alineaciones de las columnas

$total = 0;

$details = ProposalDetailData::getAllByProposal($prop->id);
foreach ($details as $d) {
	// Obtener producto (prioriza tabla productos)
	$product = $d->getProduct();
	if (!$product) continue;

	// Obtener datos del producto
	$nombre = trim((string)($product->nombre ?? $product->name ?? 'Sin nombre'));
	$marca = trim((string)($product->marca ?? $product->marca_text ?? ''));
	$modelo = trim((string)($product->modelo ?? ''));
	$descripcion_prod = trim((string)($product->producto_descripcion ?? $product->description ?? ''));

	// Construir texto de descripción: solo el campo descripción del detalle
	$custom_description = trim((string)($d->description ?? ''));
	if ($custom_description !== '') {
		$text = utf8_decode(html_entity_decode($custom_description, ENT_QUOTES, 'UTF-8'));
	} else {
		$text = utf8_decode(html_entity_decode($nombre, ENT_QUOTES, 'UTF-8'));
	}

	// Obtener cantidad
	$quantity = (int)($d->q ?? 1);

	// Obtener precio sugerido
	if (isset($d->price) && (float)$d->price > 0) {
		// Usar precio guardado
		$unit_price = (float)$d->price;
	} else {
		// Calcular precio: (precio_base * 0.87) * 1.4, redondeado al entero superior
		$precio_raw = isset($product->precio) ? (float)$product->precio : (isset($product->price) ? (float)$product->price : 0);
		$precio_base = $precio_raw / 100;
		$unit_price = ceil(($precio_base * 0.87) * 1.4);
	}

	// Calcular subtotal
	$subtotal = $quantity * $unit_price;

	// Establecer anchos y alineaciones solo una vez antes de la creación de la fila
	$pdf->SetWidths($widths);           // Anchos de las columnas
	$pdf->SetAligns($aligns);           // Alineaciones de las columnas

	// Unidad de medida
	$unit = trim((string)($d->unit ?? 'UNIDAD'));

	// Crear la fila en la tabla con los datos alineados
	$pdf->Row(array(
		$quantity,                                  // Cantidad (centrado)
		$text,                                      // Descripción del producto (izquierda)
		$unit,                                      // Unidad (centrado)
		number_format($unit_price, 2, ".", ","),   // Precio unitario (derecha)
		number_format($subtotal, 2, ".", ",")      // Total (derecha)
	));

	// Restablecer la posición de las celdas
	$pdf->SetXY($pdf->GetX(), $pdf->GetY() + 3); // Ajusta según la altura de las celdas

	// Acumular el total
	$total += $subtotal;
}

$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(148, 0, 'TOTAL Bs.', 0, 0, 'R');
$pdf->Cell(23, 0, number_format(round($total, 0, PHP_ROUND_HALF_UP), 2, '.', ','), 0, 1, 'R'); //end of line

$pdf->Ln(8);

$formatterES = new NumberFormatter("es-ES", NumberFormatter::SPELLOUT);
$n = $total;
$izquierda = intval(floor($n));
$derecha = intval(($n - floor($n)) * 100);
$litdec = explode('.', $total);
$literal = $formatterES->format($izquierda) . " CON 00/100";
$txt = iconv('utf-8', 'cp1252', $literal);
$pdf->SetFont('Arial', 'B', 10);
$pdf->SetX(14); // Establece la posición en X = 14
$pdf->Cell(40, 5, " *SON: " . strtoupper($txt) . ' BOLIVIANOS', 0, 1);
$pdf->SetFont('Arial', '', 10);
$pdf->SetX(15); // Asegura que la siguiente línea también comience en X = 14
if ((int)($prop->billed ?? 0) === 1) { $pdf->Cell(40, 5, '*Precio facturado.', 0, 1); }
$pdf->Ln(80);
$pdf->Ln(8);
$n_c = 'Presupuesto - VNP_COT_' . $bill . '_2024';

// Verificar si estamos regenerando el PDF para unir_pdfs.php
if (isset($_GET['regenerate']) && $_GET['regenerate'] == '1') {
	// Crear directorio temporal si no existe
	$tempDir = 'temp';
	if (!is_dir($tempDir)) {
		// Intentar crear el directorio con permisos adecuados
		if (!mkdir($tempDir, 0777, true)) {
			// Si no se puede crear, mostrar error
			die("Error: No se pudo crear el directorio temporal. Verifique los permisos.");
		}
	} else if (!is_writable($tempDir)) {
		// Verificar si el directorio tiene permisos de escritura
		// Intentar cambiar permisos
		chmod($tempDir, 0777);
		if (!is_writable($tempDir)) {
			die("Error: El directorio temporal no tiene permisos de escritura.");
		}
	}

	// Guardar el PDF en un archivo con nombre consistente
	$pdfFile = $tempDir . '/cotizacion_' . $prop->id . '.pdf';

	try {
		// Intentar guardar el PDF
		$pdf->Output('F', $pdfFile);

		// Verificar que el archivo se creó correctamente
		if (!file_exists($pdfFile)) {
			die("Error: No se pudo guardar el archivo PDF.");
		}

		// Redirigir de vuelta a unir_pdfs.php
		header('Location: unir_pdfs.php?id=' . $_GET["id"] . '&products=' . $_GET["products"]);
		exit;
	} catch (Exception $e) {
		// Capturar cualquier error durante la generación del PDF
		die("Error al generar el PDF: " . $e->getMessage());
	}
} else {
	// Comportamiento normal: mostrar el PDF directamente
	$pdf->Output('I', 'cot.pdf');
	exit;
}
