<?php
// ImpresoraAqua.php - Edición Elite PRO: Logística Completa y Diseño Compacto
// Ajustes: Folio, Fecha arriba, Modelo de Carro resaltado y espaciado optimizado.

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

    private function generarTokenSeguro($folio) {
        $llaveSecreta = "MS_Key_2025_#"; 
        $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);
        }
    }

    // --- SELLO DE PAGO COMPACTO ---
    private function selloCaucho($x, $y, $pago) {
        $texto = ($pago == 1) ? "PAGADO" : "PENDIENTE";
        $color = ($pago == 1) ? [22, 163, 74] : [220, 38, 38];
        $this->SetTextColor($color[0], $color[1], $color[2]);
        $this->SetDrawColor($color[0], $color[1], $color[2]);
        $this->SetLineWidth(1.2);
        $this->SetFont('Arial', 'B', 20);
        $this->Rotate(10, $x, $y);
        $this->RoundedRect($x, $y, 45, 14, 2, 'D');
        $this->SetXY($x, $y + 2);
        $this->Cell(45, 10, $texto, 0, 0, 'C');
        $this->Rotate(0);
        $this->SetTextColor(0); $this->SetDrawColor(0); $this->SetLineWidth(0.2);
    }

    // --- DISEÑO ESTACIONARIO (A4 / A5) ---
    public function disenoEstacionario($d, $c) {
        $w = $this->GetPageWidth(); $h = $this->GetPageHeight(); $m = 10;
        $utilW = $w - ($m * 2);
        $token = $this->generarTokenSeguro($d['folio']);
        $urlFinal = $this->urlValidacion . "?token=" . $token;

        // 1. CABECERA
        $this->insertarLogo($m, $m, 45, 25, $c['Logo_Base64']);
        $this->SetXY($m + 48, $m);
        $lines = explode("\n", $c['Cabecera_Texto'] ?? '');
        foreach($lines as $i => $l) {
            $this->SetX($m + 48);
            $this->SetFont('Arial', $i==0?'B':'', $i==0?14:9);
            $this->Cell($w - $m - 48 - 50, 5, utf8_decode($l), 0, 1, 'L');
        }

        // BLOQUE FOLIO (Fecha y Hora ARRIBA)
        $xF = $w - $m - 45;
        $this->SetFillColor(245, 245, 245);
        $this->RoundedRect($xF, $m, 45, 25, 2, 'DF');
        $this->SetXY($xF, $m+2); $this->SetFont('Arial','B',9);
        $this->Cell(45, 4, "FOLIO", 0, 1, 'C');
        $this->SetXY($xF, $m+6); $this->SetFont('Arial','B',16); $this->SetTextColor(180,0,0);
        $this->Cell(45, 10, $d['folio'], 0, 1, 'C');
        $this->SetTextColor(0);
        $this->SetXY($xF, $m+16); $this->SetFont('Arial','B',7.5);
        $this->Cell(45, 4, ($d['fecha'] ?? date('d/m/Y')), 0, 1, 'C');
        $this->SetX($xF); $this->Cell(45, 3, date('H:i') . " HRS", 0, 1, 'C');

        // 2. IDENTIFICACIÓN VEHÍCULO (PLACA Y CARRO)
        $yP = 42;
        $this->SetFillColor(30, 41, 59);
        $this->RoundedRect($m, $yP, $utilW, 18, 1, 'F');
        $this->SetXY($m, $yP + 5);
        $this->SetTextColor(255); $this->SetFont('Arial','B',22);
        $this->Cell($utilW, 8, strtoupper($d['placa']) . "  |  " . utf8_decode(strtoupper($d['equipo'])), 0, 1, 'C');
        $this->SetTextColor(0);

        // 3. LOGÍSTICA COMPLETA
        $yL = $yP + 22;
        $this->SetFillColor(248, 250, 252);
        $this->RoundedRect($m, $yL, $utilW, 12, 1, 'DF');
        $this->SetXY($m + 5, $yL + 3.5);
        $this->SetFont('Arial','B',9); $this->Cell(20, 5, "LAVADOR:", 0, 0);
        $this->SetFont('Arial','',10); $this->Cell($utilW*0.3, 5, utf8_decode($d['lavador']), 0, 0);
        $this->SetFont('Arial','B',9); $this->Cell(15, 5, "COLOR:", 0, 0);
        $this->SetFont('Arial','',10); $this->Cell($utilW*0.2, 5, utf8_decode($d['color']), 0, 0);
        $this->SetFont('Arial','B',9); $this->Cell(12, 5, "CAT:", 0, 0);
        $this->SetFont('Arial','',10); $this->Cell(0, 5, utf8_decode($d['categoria'] ?? 'N/A'), 0, 1);

        // 4. SERVICIO
        $yS = $yL + 16;
        $this->SetFillColor(255, 255, 255);
        $this->RoundedRect($m, $yS, $utilW, 22, 2, 'D');
        $this->SetXY($m + 5, $yS + 3);
        $this->SetFont('Arial','B',10); $this->Cell(0, 5, "CONCEPTO DEL SERVICIO:", 0, 1);
        $this->SetFont('Arial','B',20); $this->SetX($m + 10);
        $this->Cell(0, 12, "> " . utf8_decode(strtoupper($d['falla'])), 0, 1);

        // 5. TOTAL, SELLO Y QR (MÁS JUNTOS)
        $yFinal = $yS + 28;
        $this->SetXY($m, $yFinal);
        $this->SetFont('Arial','B',38);
        $this->Cell($utilW - 10, 15, "TOTAL: $ " . number_format($d['costo'], 2), 0, 1, 'R');
        
        $this->selloCaucho($m + 10, $yFinal + 2, $d['pago']);
        
        // QR más cerca del total
        $yQR = $yFinal + 18;
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=".urlencode($urlFinal), $m + 15, $yQR, 28, 28, 'PNG');
        
        $this->SetXY($m + 48, $yQR + 5);
        $this->SetFont('Arial','I',8);
        $this->MultiCell($utilW - 55, 4, utf8_decode($c['Pie_Pagina_Texto'] ?? ''), 0, 'L');
    }

    // --- DISEÑO TICKET ---
    public function disenoTicket($d, $c, $ancho) {
        $token = $this->generarTokenSeguro($d['folio']);
        $urlFinal = $this->urlValidacion . "?token=" . $token;

        $this->SetMargins(4, 2, 4); $this->SetY(4);
        $hLog = $this->insertarLogo(($ancho/2)-15, 2, 30, 18, $c['Logo_Base64']);
        if($hLog > 0) $this->SetY($this->GetY() + $hLog + 2);

        $this->SetFont('Arial','B',8);
        $this->MultiCell(0, 4, utf8_decode($c['Cabecera_Texto'] ?? ''), 0, 'C');
        
        $this->Ln(2);
        $this->SetFillColor(0); $this->SetTextColor(255); $this->SetFont('Arial','B',12);
        $this->Cell(0, 8, "FOLIO: ".$d['folio'], 0, 1, 'C', true);
        $this->SetTextColor(0);
        $this->SetFont('Arial','B',8);
        $this->Cell(0, 5, ($d['fecha'] ?? date('d/m/Y')) . " " . date('H:i'), 0, 1, 'C');

        $this->Ln(2);
        $this->SetFillColor(235); $this->SetFont('Arial','B',18);
        $this->Cell(0, 12, strtoupper($d['placa']), 1, 1, 'C', true);
        
        $this->SetFont('Arial','B',10);
        $this->Cell(0, 6, utf8_decode($d['equipo']), 0, 1, 'C');
        $this->SetFont('Arial','B',8);
        $this->Cell(0, 5, utf8_decode("LAVADOR: ".$d['lavador']), 0, 1, 'L');
        $this->Cell(0, 5, utf8_decode("COLOR: ".$d['color']), 0, 1, 'L');

        $this->Ln(1);
        $this->SetFont('Arial','B',11);
        $this->MultiCell(0, 8, utf8_decode(strtoupper($d['falla'])), 'TB', 'C');
        
        $this->Ln(4);
        $this->SetFont('Arial','B',20);
        $this->Cell(0, 10, "TOTAL: $".number_format($d['costo'], 2), 0, 1, 'R');
        
        $this->Ln(2);
        $this->selloCaucho(($ancho/2)-22, $this->GetY() + 5, $d['pago']);
        
        $this->SetY($this->GetY() + 25);
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=".urlencode($urlFinal), ($ancho/2)-10, $this->GetY(), 20, 20, 'PNG');
        $this->SetY($this->GetY() + 22);
        $this->SetFont('Arial','I',7);
        $this->MultiCell(0, 3, utf8_decode($c['Pie_Pagina_Texto'] ?? ''), 0, 'C');
        
        return $this->GetY() + 5;
    }

    // --- RECURSOS PHP GD PARA IMAGEN ---
    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);
        $imgRes = @imagecreatefromstring($imgData);
        if (!$imgRes) return 0;
        $ruta = dirname(__FILE__) . DIRECTORY_SEPARATOR . $this->idu . "-temp_logo.png";
        imagealphablending($imgRes, false); imagesavealpha($imgRes, true);
        imagepng($imgRes, $ruta); imagedestroy($imgRes);
        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); return $h;
        }
        return 0;
    }

    // --- FUNCIONES GEOMÉTRICAS ---
    function Rotate($angle, $x=-1, $y=-1) {
        if($x==-1) $x=$this->x; if($y==-1) $y=$this->y;
        if($this->angle!=0) $this->_out('Q');
        $this->angle=$angle;
        if($angle!=0) {
            $angle*=M_PI/180; $c=cos($angle); $s=sin($angle);
            $cx=$x*$this->k; $cy=($this->h-$y)*$this->k;
            $this->_out(sprintf('q %.5F %.5F %.5F %.5F %.2F %.2F cm 1 0 0 1 %.2F %.2F cm',$c,$s,-$s,$c,$cx,$cy,-$cx,-$cy));
        }
    }
    function _endpage() { if($this->angle!=0) { $this->angle=0; $this->_out('Q'); } parent::_endpage(); }
    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);
    }
    private 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)); }
}