<?php
// ImprimirNV.php - Versión con QR Encriptado Seguro y Formato Balanceado

class PDF_Documento extends FPDF {
    public $idu; 
    private $urlValidacion = "http://167.172.224.160/a/l.php"; 

    // --- FUNCIÓN DE ENCRIPTACIÓN ---
    private function generarTokenSeguro($folio) {
        $llaveSecreta = "MS_Key_2025_#"; 
        $cadena = $this->idu . "|" . $folio . "|" . $llaveSecreta;
        // Retorna Base64 amigable para URL
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($cadena));
    }

    public function generarContenido($datos, $conf, $ancho) {
        $this->SetAutoPageBreak(false);
        if ($ancho > 100) {
            $this->disenoEstacionario($datos, $conf);
        } else {
            $this->disenoTicket($datos, $conf, $ancho);
        }
    }

    // --- FUNCIÓN DE LOGO (Mantiene el confinamiento seguro) ---
    private function insertarLogo($x, $y, $w_max, $h_max, $base64) {
        if (empty($base64) || empty($this->idu)) return 0;
        if (strpos($base64, ',') !== false) $base64 = explode(',', $base64)[1];
        $imgData = base64_decode($base64);
        if (!$imgData) return 0;

        $nombreArchivo = $this->idu . "-temp_logo.png";
        $rutaCompleta = dirname(__FILE__) . DIRECTORY_SEPARATOR . $nombreArchivo;

        $recursoImagen = @imagecreatefromstring($imgData);
        if (!$recursoImagen) return 0;
        imagepng($recursoImagen, $rutaCompleta);
        imagedestroy($recursoImagen);

        $alturaRender = 0;
        if (file_exists($rutaCompleta)) {
            $size = getimagesize($rutaCompleta);
            $ratio = $size[0] / $size[1];
            $w = $w_max; $h = $w / $ratio;
            if ($h > $h_max) { $h = $h_max; $w = $h * $ratio; }

            try {
                $this->Image($rutaCompleta, $x, $y, $w, $h, 'PNG');
                $alturaRender = $h;
            } catch (Exception $e) { $alturaRender = 0; }
            @unlink($rutaCompleta);
        }
        return $alturaRender;
    }

    private function textoAjustable($texto, $anchoMax, $tamanoInicial, $estilo = '') {
        $this->SetFont('Arial', $estilo, $tamanoInicial);
        while($this->GetStringWidth(utf8_decode($texto)) > $anchoMax && $tamanoInicial > 6) {
            $tamanoInicial--;
            $this->SetFont('Arial', $estilo, $tamanoInicial);
        }
        return $tamanoInicial;
    }

    public function disenoEstacionario($datos, $conf) {
        $w = $this->GetPageWidth(); 
        $h = $this->GetPageHeight(); 
        $m = 10; 
        $utilW = $w - ($m * 2);

        // Generar Token para QR
        $token = $this->generarTokenSeguro($datos['folio']);
        $urlFinal = $this->urlValidacion . "?token=" . $token;

        // --- 1. IZQUIERDA: LOGO ---
        $this->insertarLogo($m, $m, 45, 28, $conf['Logo_Base64']);

        // --- 2. DERECHA: RECUADRO DE FOLIO ---
        $anchoFolio = 45; $altoFolio = 28; $xFolio = $w - $m - $anchoFolio;
        $this->SetFillColor(245, 245, 245);
        $this->RoundedRect($xFolio, $m, $anchoFolio, $altoFolio, 3, 'DF');
        $this->SetXY($xFolio, $m + 2); 
        $this->SetFont('Arial', 'B', 9);
        $this->Cell($anchoFolio, 4, utf8_decode("NOTA DE VENTA"), 0, 1, 'C');
        $this->SetXY($xFolio, $m + 7); 
        $this->SetFont('Arial', 'B', 16); 
        $this->SetTextColor(180, 0, 0); 
        $this->Cell($anchoFolio, 10, utf8_decode($datos['folio'] ?? '000'), 0, 1, 'C'); 
        $this->SetTextColor(0);
        $this->SetXY($xFolio, $m + 18); 
        $this->SetFont('Arial', 'B', 7); 
        $this->Cell($anchoFolio, 4, "F E C H A", 'TB', 1, 'C', true);
        $this->SetXY($xFolio, $m + 22); 
        $this->SetFont('Arial', '', 8);
        $this->Cell($anchoFolio, 5, utf8_decode($datos['fecha'] ?? date('d/m/Y')), 0, 1, 'C');

        // --- 3. CENTRO: CABECERA INTELIGENTE ---
        $xCentro = $m + 48;
        $anchoCentro = ($xFolio - $xCentro) - 5;
        $yActual = $m;
        $lineas = explode("\n", $conf['Cabecera_Texto'] ?? '');
        foreach($lineas as $i => $linea) {
            if (empty(trim($linea))) continue;
            $size = ($i === 0) ? $this->textoAjustable($linea, $anchoCentro, 14, 'B') : $this->textoAjustable($linea, $anchoCentro, 9, '');
            $this->SetXY($xCentro, $yActual);
            $this->Cell($anchoCentro, ($i === 0 ? 6 : 4), utf8_decode($linea), 0, 1, 'L');
            $yActual += ($i === 0 ? 7 : 4.5);
        }

        // --- 4. BLOQUE CLIENTE ---
        $yC = 42; 
        $this->SetY($yC); 
        $this->RoundedRect($m, $yC, $utilW, 22, 4, 'D');
        $this->SetXY($m + 3, $yC + 2); 
        $this->SetFont('Arial', 'B', 9); $this->Cell(18, 5, "CLIENTE: ", 0, 0);
        $this->SetFont('Arial', '', 9); $this->Cell(0, 5, utf8_decode($datos['cliente'] ?? ''), 'B', 1);
        $this->SetXY($m + 3, $yC + 10); 
        $this->SetFont('Arial', 'B', 9); $this->Cell(10, 6, "TEL: ", 0, 0);
        $this->SetFont('Arial', '', 9); $this->Cell($utilW * 0.4, 6, utf8_decode($datos['telefono'] ?? 'S/N'), 'B', 0);
        $this->SetFont('Arial', 'B', 9); $this->Cell(16, 6, "  E-MAIL: ", 0, 0);
        $this->SetFont('Arial', '', 9); $this->Cell(0, 6, utf8_decode($datos['email'] ?? 'S/N'), 'B', 1);

        // --- 5. TABLA ZEBRA ---
        $yT = 68; $yPie = $h - 45; $hT = $yPie - $yT - 5;
        $this->SetFillColor(80, 80, 80); $this->SetTextColor(255); $this->SetFont('Arial', 'B', 9);
        $c1 = $utilW * 0.12; $c2 = $utilW * 0.53; $c3 = $utilW * 0.15; $c4 = $utilW * 0.20;
        $this->RoundedRect($m, $yT, $utilW, $hT, 4, 'D'); 
        $this->SetXY($m, $yT);
        $this->Cell($c1, 8, "CANT.", 1, 0, 'C', true); 
        $this->Cell($c2, 8, "DESCRIPCION", 1, 0, 'C', true);
        $this->Cell($c3, 8, "P. UNIT.", 1, 0, 'C', true); 
        $this->Cell($c4, 8, "IMPORTE", 1, 1, 'C', true);
        $this->SetTextColor(0); $this->SetFont('Arial', '', 9);
        $fill = false;
        foreach ($datos['items'] ?? [] as $it) {
            if ($this->GetY() + 7 > ($yT + $hT - 2)) break;
            $this->SetFillColor(245, 245, 245); 
            $this->SetX($m);
            $this->Cell($c1, 7, ($it['qty'] ?? '1'), 0, 0, 'C', $fill);
            $this->Cell($c2, 7, " ".utf8_decode(substr($it['nombre'] ?? '', 0, 50)), 0, 0, 'L', $fill);
            $this->Cell($c3, 7, "$ ".number_format($it['price']??0, 2), 0, 0, 'R', $fill);
            $this->Cell($c4, 7, "$ ".number_format(($it['qty']??1)*($it['price']??0), 2), 0, 1, 'R', $fill);
            $fill = !$fill;
        }

        // --- 6. PIE DE PÁGINA ---
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=".urlencode($urlFinal), $m, $yPie, 28, 28, 'PNG');
        $this->SetXY($m + 32, $yPie); 
        $this->SetFillColor(235, 235, 235); $this->SetFont('Arial', 'B', 11);
        $this->Cell($utilW - 32 - ($utilW * 0.25), 10, "TOTAL A PAGAR $ ", 1, 0, 'R', true);
        $this->Cell($utilW * 0.25, 10, "$ ".number_format($datos['total']??0, 2), 1, 1, 'R', true);
        $this->SetXY($m + 32, $yPie + 12); 
        $this->SetFont('Arial', 'I', 8); 
        $this->MultiCell($utilW - 32, 4, utf8_decode($conf['Pie_Pagina_Texto'] ?? ''), 0, 'R');
        $this->SetY($h - 10); $this->SetFont('Arial', '', 7); $this->SetTextColor(150);
        $this->Cell(0, 5, "UUID: " . ($conf['UUID_Unico'] ?? 'N/A'), 0, 0, 'C');
    }

    public function disenoTicket($datos, $conf, $ancho) {
        $token = $this->generarTokenSeguro($datos['folio']);
        $urlFinal = $this->urlValidacion . "?token=" . $token;

        $this->SetMargins(4, 2, 4); $this->SetY(4);
        $altoL = $this->insertarLogo(($ancho/2)-15, $this->GetY(), 30, 20, $conf['Logo_Base64']);
        if($altoL > 0) $this->SetY($this->GetY() + $altoL + 3);
        $this->SetFont('Arial', 'B', 8);
        $this->MultiCell(0, 4, utf8_decode($conf['Cabecera_Texto'] ?? ''), 0, 'C'); $this->Ln(2);
        $this->SetFillColor(0); $this->SetTextColor(255); $this->SetFont('Arial', 'B', 11);
        $this->Cell(0, 8, "FOLIO: " . ($datos['folio'] ?? '000'), 0, 1, 'C', true);
        $this->SetTextColor(0); $this->SetFont('Arial', '', 8);
        $this->Cell(0, 4, "FECHA: ".date('d/m/Y H:i'), 0, 1, 'L');
        $this->MultiCell(0, 4, "CLIENTE: ".utf8_decode($datos['cliente']??'PUBLICO'), 0, 'L');
        $this->Cell(0, 4, "TEL: ".utf8_decode($datos['telefono']??'S/N'), 0, 1, 'L'); $this->Ln(2);
        $this->SetFont('Arial', 'B', 8);
        $this->Cell(($ancho-8)*0.20, 6, "CANT", 'B', 0, 'L');
        $this->Cell(($ancho-8)*0.50, 6, "DESCRIP", 'B', 0, 'L');
        $this->Cell(($ancho-8)*0.30, 6, "TOTAL", 'B', 1, 'R');
        $fill = false;
        foreach ($datos['items'] ?? [] as $it) {
            $this->SetFillColor(245, 245, 245); $this->SetFont('Arial', '', 8);
            $this->Cell(($ancho-8)*0.20, 6, $it['qty'], 0, 0, 'L', $fill);
            $this->Cell(($ancho-8)*0.50, 6, utf8_decode(substr($it['nombre'], 0, 18)), 0, 0, 'L', $fill);
            $this->Cell(($ancho-8)*0.30, 6, "$".number_format(($it['qty']??1)*($it['price']??0), 2), 0, 1, 'R', $fill);
            $fill = !$fill;
        }
        $this->Ln(2); $this->SetFont('Arial', 'B', 11);
        $this->Cell(0, 8, "TOTAL: $ ".number_format($datos['total']??0, 2), 'T', 1, 'R');
        $this->Ln(3); $yQR = $this->GetY();
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=".urlencode($urlFinal), ($ancho/2)-12, $yQR, 24, 24, 'PNG');
        $this->SetY($yQR + 26);
        $this->SetFont('Arial', 'I', 7); $this->MultiCell(0, 4, utf8_decode($conf['Pie_Pagina_Texto'] ?? ''), 0, 'C');
        $this->Ln(1); $this->SetFont('Arial', '', 6);
        $this->Cell(0, 4, "ID: " . ($conf['UUID_Unico'] ?? 'N/A'), 0, 1, 'C');
        return $this->GetY();
    }

    public function RoundedRect($x, $y, $w, $h, $r, $style = '', $corners = '1234') {
        $k = $this->k; $hp = $this->h;
        if($style=='F') $op='f'; elseif($style=='FD' || $style=='DF') $op='B'; else $op='S';
        $MyArc = 4/3 * (sqrt(2) - 1);
        $this->_out(sprintf('%.2F %.2F m',($x+$r)*$k,($hp-$y)*$k));
        $xc = $x+$w-$r; $yc = $y+$r;
        $this->_out(sprintf('%.2F %.2F l',$xc*$k,($hp-$y)*$k));
        $this->_Arc($xc + $r*$MyArc, $yc - $r, $xc + $r, $yc - $r*$MyArc, $xc + $r, $yc);
        $xc = $x+$w-$r; $yc = $y+$h-$r;
        $this->_out(sprintf('%.2F %.2F l',($x+$w)*$k,($hp-$yc)*$k));
        $this->_Arc($xc + $r, $yc + $r*$MyArc, $xc + $r*$MyArc, $yc + $r, $xc, $yc + $r);
        $xc = $x+$r; $yc = $y+$h-$r;
        $this->_out(sprintf('%.2F %.2F l',$xc*$k,($hp-($y+$h))*$k));
        $this->_Arc($xc - $r*$MyArc, $yc + $r, $xc - $r, $yc + $r*$MyArc, $xc - $r, $yc);
        $xc = $x+$r; $yc = $y+$r;
        $this->_out(sprintf('%.2F %.2F l',($x)*$k,($hp-$yc)*$k));
        $this->_Arc($xc - $r, $yc - $r*$MyArc, $xc - $r*$MyArc, $yc - $r, $xc, $yc - $r);
        $this->_out($op);
    }

    public function _Arc($x1, $y1, $x2, $y2, $x3, $y3) {
        $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c ', $x1*$this->k, ($this->h-$y1)*$this->k, $x2*$this->k, ($this->h-$y2)*$this->k, $x3*$this->k, ($this->h-$y3)*$this->k));
    }
}