<?php
// ImprimirPedido.php - Versión con QR Encriptado Seguro

class PDF_Pedido extends FPDF {
    public $idu;
    private $urlValidacion = "http://167.172.224.160/a/l.php";
    private $colorNavy = [44, 62, 80];
    private $colorResta = [180, 0, 0];

    // --- FUNCIÓN DE ENCRIPTACIÓN ---
    // Crea un token ilegible: IDU + Folio + Llave Secreta
    private function generarTokenSeguro($folio) {
        $llaveSecreta = "MS_Key_2025_#"; // Cambia esto por tu propia clave
        $cadena = $this->idu . "|" . $folio . "|" . $llaveSecreta;
        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);
        }
    }

    // (insertarLogo se mantiene igual que la versión anterior...)
    private function insertarLogo($x, $y, $w_max, $h_max, $base64) {
        if (empty($base64) || empty($this->idu)) return;
        if (strpos($base64, ',') !== false) $base64 = explode(',', $base64)[1];
        $imgData = base64_decode($base64);
        $ruta = dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->idu . "-temp_ped.png";
        $recurso = @imagecreatefromstring($imgData);
        if ($recurso) {
            imagepng($recurso, $ruta); imagedestroy($recurso);
            if (file_exists($ruta)) {
                $size = getimagesize($ruta);
                $ratio = $size[0] / $size[1];
                $w = $w_max; $h = $w / $ratio;
                if ($h > $h_max) { $h = $h_max; $w = $h * $ratio; }
                $this->Image($ruta, $x, $y, $w, $h, 'PNG');
                @unlink($ruta);
            }
        }
    }

    public function disenoEstacionario($d, $c) {
        $w = $this->GetPageWidth(); $h = $this->GetPageHeight(); $m = 12; $utilW = $w - ($m * 2);
        
        // GENERAMOS EL TOKEN SEGURO PARA EL QR
        $token = $this->generarTokenSeguro($d['folio']);
        $linkSeguro = $this->urlValidacion . "?token=" . $token;

        // 1. CABECERA (Logo - Texto - Folio)
        $this->insertarLogo($m, $m, 45, 22, $c['Logo_Base64']);
        $xF = $w - $m - 42;
        $this->SetDrawColor($this->colorNavy[0], $this->colorNavy[1], $this->colorNavy[2]);
        $this->SetLineWidth(0.5); $this->Rect($xF, $m, 42, 22);
        $this->SetXY($xF, $m+3); $this->SetFont('Arial','B',8); $this->Cell(42,4,utf8_decode("PEDIDO DE VENTA"),0,1,'C');
        $this->SetXY($xF, $m+9); $this->SetFont('Arial','B',14); $this->SetTextColor($this->colorNavy[0]);
        $this->Cell(42,8, $d['folio'], 0,1,'C');
        $this->SetXY($xF, $m+18); $this->SetFont('Arial','',7); $this->SetTextColor(100);
        $this->Cell(42,4, $d['fecha'], 0,0,'C');

        $xT = $m + 48; $this->SetXY($xT, $m); $this->SetTextColor(0);
        $lines = explode("\n", $c['Cabecera_Texto'] ?? '');
        foreach($lines as $i=>$l){
            $this->SetX($xT); $this->SetFont('Arial', $i==0?'B':'', $i==0 ? 12 : 7.5);
            $this->Cell($xF-$xT-3, $i==0 ? 6 : 3.5, utf8_decode($l),0,1,'L');
        }

        // 2. BLOQUE CLIENTE + QR SEGURO
        $y = 38; $this->SetDrawColor(200); $this->SetLineWidth(0.2);
        $this->Rect($m, $y, $utilW, 22); 
        $this->Line($m + $utilW - 22, $y, $m + $utilW - 22, $y + 22);
        
        $this->SetXY($m+4, $y+4); $this->SetFont('Arial','B',7); $this->SetTextColor(120); $this->Cell(0,4,"DATOS DEL CLIENTE",0,1);
        $this->SetX($m+4); $this->SetFont('Arial','B',11); $this->SetTextColor(0); $this->Cell(0,7,utf8_decode($d['cliente']),0,1);
        $this->SetX($m+4); $this->SetFont('Arial','',9); $this->Cell(0,5,"TEL: ".$d['tel'],0,1);

        // QR con el token encriptado
        $qrFinal = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" . urlencode($linkSeguro);
        $this->Image($qrFinal, $m+$utilW-20, $y+2, 18, 18, 'PNG');

        // 3. TABLA DE PRODUCTOS
        $y += 28;
        $this->SetFillColor($this->colorNavy[0], $this->colorNavy[1], $this->colorNavy[2]);
        $this->SetTextColor(255); $this->SetFont('Arial','B',8);
        $this->SetXY($m, $y);
        $this->Cell($utilW*0.1, 9, "CANT", 0, 0, 'C', true);
        $this->Cell($utilW*0.55, 9, utf8_decode(" DESCRIPCION"), 0, 0, 'L', true);
        $this->Cell($utilW*0.15, 9, "PRECIO", 0, 0, 'R', true);
        $this->Cell($utilW*0.2, 9, "TOTAL ", 0, 1, 'R', true);
        
        $this->SetTextColor(0); $this->SetFont('Arial','',9);
        $fill = false;
        foreach ($d['items'] as $it) {
            $this->SetFillColor(248); $this->SetX($m);
            $this->Cell($utilW*0.1, 8, $it['cant'], 'B', 0, 'C', $fill);
            $this->Cell($utilW*0.55, 8, " ".utf8_decode($it['producto']), 'B', 0, 'L', $fill);
            $this->Cell($utilW*0.15, 8, number_format($it['precio'], 2)." ", 'B', 0, 'R', $fill);
            $this->Cell($utilW*0.2, 8, number_format($it['total'], 2)." ", 'B', 1, 'R', $fill);
            $fill = !$fill;
        }

        // 4. MÓDULO FINAL
        $yFinal = $this->GetY() + 8;
        $this->SetDrawColor(0); $this->SetLineWidth(0.4);
        $this->Rect($m, $yFinal, $utilW*0.45, 26);
        $this->SetXY($m+4, $yFinal+4); $this->SetFont('Arial','B',8); $this->SetTextColor(100); $this->Cell(30,5,"RESUMEN:",0,1);
        $this->SetFont('Arial','',10); $this->SetTextColor(0);
        $this->SetX($m+4); $this->Cell(30,6,"TOTAL:",0,0); $this->Cell(20,6,"$ ".number_format($d['total'],2),0,1,'R');
        $this->SetX($m+4); $this->Cell(30,6,"ANTICIPO:",0,0); $this->Cell(20,6,"$ ".number_format($d['anticipo'],2),0,1,'R');
        $this->SetX($m+4); $this->SetFont('Arial','B',10); $this->SetTextColor($this->colorResta[0], 0, 0);
        $this->Cell(30,6,"RESTANTE:",0,0); $this->Cell(20,6,"$ ".number_format($d['resta'],2),0,1,'R');
        
        $this->SetTextColor(0);
        $this->Rect($m + ($utilW*0.55), $yFinal, $utilW*0.45, 26);
        $this->SetXY($m + ($utilW*0.55), $yFinal+18);
        $this->Cell($utilW*0.45, 0.1, "", 'T', 1, 'C');
        $this->SetX($m + ($utilW*0.55)); $this->SetFont('Arial','B',7);
        $this->Cell($utilW*0.45, 5, "FIRMA DE CONFORMIDAD", 0, 0, 'C');

        // 5. PIE DE PÁGINA Y TALÓN (Usando el mismo token seguro)
        $this->SetY($h - 52); $this->SetFont('Arial','I',7); $this->SetTextColor(100);
        $this->MultiCell($utilW, 3.5, utf8_decode($c['Pie_Pagina_Texto'] ?? ''), 0, 'L');

        $yTalon = $h - 35;
        $this->SetDash(1, 1); $this->Line($m, $yTalon-2, $w-$m, $yTalon-2); $this->SetDash();
        $this->SetFillColor(250); $this->Rect($m, $yTalon, $utilW, 22, 'DF');
        $this->Image($qrFinal, $m+2, $yTalon+2, 18, 18, 'PNG');
        $this->SetXY($m+22, $yTalon+3); $this->SetFont('Arial','B',10); $this->Cell(0,5,"TALON ALMACEN: ".$d['folio'],0,1);
        $this->SetX($m+22); $this->SetFont('Arial','',8); $this->Cell(0,4,"RECOLECCION: ".utf8_decode($d['cliente']),0,1);
    }

    public function disenoTicket($d, $c, $ancho) {
        $this->SetMargins(4, 2, 4); $this->SetY(4);
        $token = $this->generarTokenSeguro($d['folio']);
        $linkSeguro = $this->urlValidacion . "?token=" . $token;

        $this->insertarLogo(($ancho/2)-15, 2, 30, 15, $c['Logo_Base64']);
        $this->SetY($this->GetY()+18);
        $this->SetFont('Arial','B',8); $this->MultiCell(0,4,utf8_decode($c['Cabecera_Texto'] ?? ''),0,'C');
        $this->SetFillColor(44, 62, 80); $this->SetTextColor(255); $this->Cell(0,7,"PEDIDO: ".$d['folio'],0,1,'C',true);
        $this->SetTextColor(0); $this->Ln(2);
        foreach($d['items'] as $it) {
            $this->SetFont('Arial','',7); $this->Cell(8, 4, $it['cant']."x", 0, 0);
            $this->Cell(0, 4, utf8_decode(substr($it['producto'],0,28)), 0, 1);
        }
        $this->Ln(2); $this->SetFont('Arial','B',8);
        $this->Cell(0,4,"RESTA: $".number_format($d['resta'],2),'T',1,'R');
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=".urlencode($linkSeguro), ($ancho/2)-8, $this->GetY()+2, 16, 16, 'PNG');
        return $this->GetY() + 25;
    }

    function SetDash($black=null, $white=null) {
        if($black!==null) $s=sprintf('[%.3F %.3F] 0 d',$black*$this->k,$white*$this->k);
        else $s='[] 0 d';
        $this->_out($s);
    }
}