<?php
// ImprimirOS.php - Versión "Cero Errores": Estructura Unificada, Sincronizada y QR Encriptado

class PDF_OS extends FPDF {
    public $idu;
    private $urlValidacion = "http://167.172.224.160/a/l.php"; // Dirección base

    // --- 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); // Control total del espacio
        if ($ancho > 100) {
            $this->disenoEstacionario($datos, $conf);
        } else {
            $this->disenoTicket($datos, $conf, $ancho);
        }
    }

    // --- PROCESAMIENTO DE IMAGEN (Logo Proporcional) ---
    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);
        $ruta = dirname(__FILE__) . DIRECTORY_SEPARATOR . "temp_os_{$this->idu}.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);
                return $h;
            }
        }
        return 0;
    }

    // --- DISEÑO A4 / A5 (Estacionario) ---
    public function disenoEstacionario($d, $c) {
        $w = $this->GetPageWidth(); $h = $this->GetPageHeight(); $m = 12;
        $esHorizontal = ($w > $h);
        $anchoTalon = 45;
        $utilW = $esHorizontal ? ($w - $m*2 - $anchoTalon - 5) : ($w - $m*2);

        // Generar Link con Token
        $token = $this->generarTokenSeguro($d['folio']);
        $urlFinal = $this->urlValidacion . "?token=" . $token;

        // Header
        $this->insertarLogo($m, $m, 45, 22, $c['Logo_Base64']);
        $xF = $esHorizontal ? ($utilW + $m - 40) : ($w - $m - 45);
        $this->Rect($xF, $m, 45, 22);
        $this->SetXY($xF, $m+2); $this->SetFont('Arial','B',8); $this->Cell(45,4,"ORDEN DE SERVICIO",0,1,'C');
        $this->SetXY($xF, $m+7); $this->SetFont('Arial','B',14); $this->SetTextColor(180,0,0);
        $this->Cell(45,10, $d['folio'], 0,1,'C'); $this->SetTextColor(0);
        $this->SetXY($xF, $m+17); $this->SetFont('Arial','',7); $this->Cell(45,4, $d['fecha']." | ".$d['hora'], 0,0,'C');

        // Info Cabecera (Cargado a la izquierda)
        $xT = $m + 46;
        $this->SetXY($xT, $m);
        $lines = explode("\n", $c['Cabecera_Texto'] ?? '');
        foreach($lines as $i=>$l){
            $this->SetX($xT); $this->SetFont('Arial', $i==0?'B':'', $i==0?11:7.5);
            $this->Cell($xF-$xT-2, $i==0?6:3.5, utf8_decode($l),0,1,'L');
        }

        // Datos Cliente/Equipo
        $y = 40; $this->SetFillColor(248); $this->SetLineWidth(0.2);
        $this->Rect($m, $y, ($utilW/2)-1, 20, 'DF');
        $this->SetXY($m+3, $y+2); $this->SetFont('Arial','B',7); $this->Cell(0,4,"CLIENTE: ".utf8_decode($d['cliente']),0,1);
        $this->SetX($m+3); $this->SetFont('Arial','',8); $this->Cell(0,5,"TEL: ".$d['tel'],0,1);

        $this->Rect($m+($utilW/2)+1, $y, ($utilW/2)-1, 20, 'DF');
        $this->SetXY($m+($utilW/2)+4, $y+2); $this->SetFont('Arial','B',7); $this->Cell(0,4,"EQUIPO: ".utf8_decode($d['equipo']),0,1);
        $this->SetX($m+($utilW/2)+4); $this->SetFont('Arial','',8); $this->Cell(0,5,"S/N: ".$d['serie']." | PASS: ".$d['pass'],0,1);

        // Falla dinámica
        $y += 22; $this->SetXY($m, $y);
        $this->SetFont('Arial','B',8); $this->Cell($utilW, 5, "FALLA REPORTADA:", 'B', 1);
        $this->SetFont('Arial','',9); $this->MultiCell($utilW, 5, utf8_decode($d['falla']), 0, 'L');
        $yFinalFalla = $this->GetY() + 5;

        // Costos y Firma
        $yC = ($yFinalFalla > $h - 75) ? ($h - 75) : $yFinalFalla;
        $this->Rect($m, $yC, $utilW, 25);
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=".urlencode($urlFinal), $m+2, $yC+2, 21, 21, 'PNG');
        $this->SetXY($m+25, $yC+2); $this->SetFont('Arial','B',9);
        $this->Cell(30,6,"TOTAL: $".number_format($d['costo'],2),0,1,'L');
        $this->SetX($m+25); $this->Cell(30,6,"RESTA: $".number_format($d['resta'],2),0,1,'L');
        
        $this->SetXY($m+$utilW-60, $yC+18); $this->Cell(55,0.1,"",'T',1,'C');
        $this->SetX($m+$utilW-60); $this->SetFont('Arial','B',7); $this->Cell(55,4,"FIRMA DE CONFORMIDAD",0,0,'C');

        // Pie de Página (Justificado Izquierda)
        $yPie = $esHorizontal ? ($h - 22) : ($h - 52);
        $this->SetY($yPie); $this->SetFont('Arial','I',7); $this->SetTextColor(100);
        $this->MultiCell($utilW, 3.5, utf8_decode($c['Pie_Pagina_Texto'] ?? ''), 0, 'L');

        // Talón
        if($esHorizontal) { $this->dibujarTalonV($w-$m-$anchoTalon, $m, $anchoTalon, $h-($m*2), $d); }
        else { $this->dibujarTalonH($m, $h-35, $utilW, $d); }
    }

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

        $this->SetMargins(4, 2, 4); $this->SetY(4);
        $hL = $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(0); $this->SetTextColor(255);
        $this->Cell(0,7,"OS: ".$d['folio'],0,1,'C',true);
        $this->SetTextColor(0); $this->Ln(2);

        $this->SetFont('Arial','B',7); $this->Cell(0,4,"CLIENTE: ".utf8_decode($d['cliente']),0,1);
        $this->SetFont('Arial','',7); $this->Cell(0,4,"EQUIPO: ".utf8_decode($d['equipo']),0,1);
        $this->Cell(0,4,"SERIE: ".$d['serie'],0,1);

        $this->Ln(2); $this->SetFont('Arial','B',7); $this->Cell(0,4,"FALLA:",0,1);
        $this->SetFont('Arial','',7); $this->MultiCell(0,3.5,utf8_decode($d['falla']),0,'L');

        $this->Ln(2); $this->SetFont('Arial','B',8);
        $this->Cell(0,5,"TOTAL: $".number_format($d['costo'],2),0,1,'R');
        $this->Cell(0,5,"RESTA: $".number_format($d['resta'],2),0,1,'R');

        $this->Ln(5); $this->Cell(0,0.1,"",'T',1,'C');
        $this->SetFont('Arial','',6); $this->Cell(0,4,"FIRMA CLIENTE",0,1,'C');

        // QR Cliente y Pie de Página en Ticket
        $this->Ln(3); $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=".urlencode($urlFinal), ($ancho/2)-10, $this->GetY(), 20, 20, 'PNG');
        $this->SetY($this->GetY()+22);
        $this->SetFont('Arial','I',6); $this->SetTextColor(100);
        $this->MultiCell(0, 3, utf8_decode($c['Pie_Pagina_Texto'] ?? ''), 0, 'L');

        // Talón Ticket
        $this->Ln(4); $this->SetDash(1,1); $this->Cell(0,0.1,"",'T',1,'C'); $this->SetDash();
        $this->Ln(2); $yT = $this->GetY();
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=".urlencode($urlFinal), $ancho-20, $yT, 16, 16, 'PNG');
        $this->SetFont('Arial','B',8); $this->Cell(0,4,"TALON: ".$d['folio'],0,1);
        $this->SetFont('Arial','',7); $this->Cell(0,4,utf8_decode(substr($d['equipo'],0,25)),0,1);
        
        return $this->GetY() + 10;
    }

    // Talones
    private function dibujarTalonH($x, $y, $w, $d) {
        $token = $this->generarTokenSeguro($d['folio']);
        $urlFinal = $this->urlValidacion . "?token=" . $token;

        $this->SetDash(1,1); $this->Line($x, $y-2, $x+$w, $y-2); $this->SetDash();
        $this->SetFillColor(252); $this->Rect($x, $y, $w, 22, 'DF');
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=".urlencode($urlFinal), $x+2, $y+2, 18, 18, 'PNG');
        $this->SetXY($x+22, $y+3); $this->SetFont('Arial','B',10); $this->Cell(0,5,"ID: ".$d['folio'],0,1);
        $this->SetX($x+22); $this->SetFont('Arial','',8); $this->Cell(0,4,"CLI: ".utf8_decode($d['cliente']),0,1);
        $this->SetX($x+22); $this->Cell(0,4,"EQ: ".utf8_decode($d['equipo'])." | CLAVE: ".$d['pass'],0,1);
    }

    private function dibujarTalonV($x, $y, $w, $h, $d) {
        $token = $this->generarTokenSeguro($d['folio']);
        $urlFinal = $this->urlValidacion . "?token=" . $token;

        $this->SetDash(1,1); $this->Line($x-2, $y, $x-2, $y+$h); $this->SetDash();
        $this->SetFillColor(252); $this->Rect($x, $y, $w, $h, 'DF');
        $this->Image("https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=".urlencode($urlFinal), $x+($w/2)-10, $y+5, 20, 20, 'PNG');
        $this->SetXY($x, $y+28); $this->SetFont('Arial','B',10); $this->Cell($w,5,$d['folio'],0,1,'C');
        $this->SetFont('Arial','',7); $this->SetX($x+2); $this->MultiCell($w-4, 4, "EQ: ".utf8_decode($d['equipo'])."\nCLI: ".utf8_decode($d['cliente']), 0, 'L');
    }

    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);
    }
}