<?php 
 ob_start();
    header('Content-Type: text/html; charset=UTF-8');
    //require("fpdf/fpdf.php");
    require("fpdf/pdf_js.php");
    require("phpqrcode/qrlib.php");
    require_once("PDF417/vendor/autoload.php");
    use BigFish\PDF417\PDF417;
    use BigFish\PDF417\Renderers\ImageRenderer;

    include ("config.php");

    /******************************************************************************************/
    /* consultas SQL
    /******************************************************************************************/

    $id = $_GET['id_guia'];


    $mysqli = new mysqli($db_host,$db_user,$db_pass,$db_name);

    //Para obtener los datos de la venta

    $query0 = "SELECT id_venta  FROM guia_remision WHERE id_guia_remision = '".$id."' ";
    $result0= $mysqli->query($query0);
    $row0 = $result0->fetch_assoc();

    if (!is_null($row0['id_venta'])) {
        $query1 = "SELECT c.nombre as nombre_cliente, c.numero_documento as ruc_dni , g.* , tcv.nombre as tipo, tc.*, v.nombre_comprobante, l.direccion as direc, l.telefono as telef FROM guia_remision g INNER JOIN ventas v ON g.id_venta = v.id_venta INNER JOIN clientes c ON c.id_cliente = v.id_cliente INNER JOIN tipo_comprobante tcv ON tcv.id_tipo_comprobante = v.id_tipo_comprobante INNER JOIN tipo_comprobante tc ON tc.id_tipo_comprobante = g.id_tipo_comprobante INNER JOIN local l ON l.id_local = g.id_local WHERE g.id_guia_remision = '".$id."' ";
        $result1 = $mysqli->query($query1);
        $row1 = $result1->fetch_assoc();
    }
    else {
        $query1 = "SELECT c.nombre as nombre_cliente, c.numero_documento as ruc_dni , g.* , tc.*, l.direccion as direc, l.telefono as telef FROM guia_remision g INNER JOIN clientes c ON c.id_cliente = g.id_cliente INNER JOIN tipo_comprobante tc ON tc.id_tipo_comprobante = g.id_tipo_comprobante INNER JOIN local l ON l.id_local = g.id_local WHERE g.id_guia_remision = '".$id."' ";
        $result1 = $mysqli->query($query1);
        $row1 = $result1->fetch_assoc();
    }

    //Para obtener los detalles de la venta
    $query2 = "SELECT p.nombre as producto,  p.descripcion, d.cantidad as cantidad , u.nombre as unidad FROM detalle_venta d INNER JOIN productos p ON d.id_producto = p.id_producto INNER JOIN unidad_medida u ON u.id_unidad_medida = p.id_unidad_medida WHERE d.id_venta = '".$row1['id_venta']."' ";
    $result2 = $mysqli->query($query2);


    //Para obtener los detalles de la guia
    $query4 = "SELECT p.nombre as producto,  p.descripcion, d.cantidad as cantidad , u.nombre as unidad FROM detalle_guia_remision d INNER JOIN productos p ON d.id_producto = p.id_producto INNER JOIN unidad_medida u ON u.id_unidad_medida = p.id_unidad_medida WHERE d.id_guia_remision = '".$id."' ";
    $result4 = $mysqli->query($query4);


     


    //Para obtener los datos de la empresa
    $query3 = "SELECT * FROM empresa WHERE id_empresa = '1' ";
    $result3 = $mysqli->query($query3);
    $row3 = $result3->fetch_assoc();


    //Para obtener los datos deL DESTINATARIO
    $id_destinatario  = $row1['id_destinatario'];  
    

    $query6 = "SELECT nombre, numero_documento FROM clientes WHERE id_cliente = '".$id_destinatario."' ";
    $result6 = $mysqli->query($query6);
    $row6 = mysqli_fetch_assoc($result6);


    // Variables correspondientes a la factura.
    $RUC        = $row1['ruc_dni'];    // RUC.
    $NomRazSoc  = $row1['nombre_cliente'];              // Nombre o Razón social.
    $FecEmi     = $row1['fecha_traslado']; 
    $CodHash    = "";  
    $partida  = $row1['punto_partida'];
    $llegada  = $row1['punto_llegada']; 
    $Domicilio  = $row1['punto_partida']; 
    $Domicilio  = $row1['punto_partida'];      

    $TotMonto   = 0;                            // Total importe. 
    $autoriza   = $row3['autorizacion'];
    $pagina     = $row3['pagina_web'];
    $empresa    = $row3['razon_social'];
    
    $xml = @file_get_contents('../sunat/xml/guias/'.$row3['ruc'].'-'.$row1['codigo'].'-'.$row1['nombre_guia'].'.xml');
        
    if ($xml) {
        // Obteniendo datos del archivo .XML 
        $DOM = new DOMDocument('1.0', 'ISO-8859-1');
        $DOM->preserveWhiteSpace = FALSE;
        $DOM->loadXML($xml);

       // Obteniendo Codigo Hash
        $DocXML = $DOM->getElementsByTagName('DigestValue');
        $i=0;
        foreach($DocXML as $Nodo){
            if ($i==0){
                $CodHash = $Nodo->nodeValue; 
            }
            $i++;
        } 
    }    
   
     // PARA GENERAR IMAGEN QR
    $server_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
    $qr_url=$server_url."/imprimeGuiaTransportista.php?id_guia=".$id;
    $qr_ruta="image/image_qr.png";
    $qr_tamano=10;
    $qr_level="Q";
    $qr_frame=3;
    QRcode::png($qr_url, $qr_ruta, $qr_level, $qr_tamano,$qr_frame); 


    // TOTALES DE LA FACTURA 
    
    $sub_total = 0;
    $total = 0;
    $igv = 0;
    $desc = 0;
    $ii=0;


    if (!is_null($row1['id_venta'])) {
        while($row2 = $result2->fetch_assoc())
        {
            $array['detalle'][$ii]['descripcion'] = $row2['producto']." ".$row2['descripcion']; 
            $array['detalle'][$ii]['cantidad'] = number_format($row2['cantidad'] , 2, ".", ""); 
            $array['detalle'][$ii]['unidad'] = $row2['unidad']; 
            $ii++;
        }
    }
    else{
        while($row4 = $result4->fetch_assoc())
        {
            $array['detalle'][$ii]['descripcion'] = $row4['producto']." ".$row4['descripcion']; 
            $array['detalle'][$ii]['cantidad'] = number_format($row4['cantidad'] , 2, ".", ""); 
            $array['detalle'][$ii]['unidad'] = $row4['unidad']; 
            $ii++;
        }
    }


 

    /******************************************************************************************/
    /* creamos documento PDF
    /******************************************************************************************/

    $pdf=new PDF('P','cm','Letter');
    $pdf->AliasNbPages();
    $pdf->AddPage();
    $pdf->AddFont('IDAutomationHC39M','','IDAutomationHC39M.php');
    $pdf->AddFont('verdana','','verdana.php');
    $pdf->SetAutoPageBreak(true);
    $pdf->SetMargins(0, 0, 0);
    $pdf->SetLineWidth(0.02);
    $pdf->SetFillColor(0,0,0);
    $pdf->Footer(true);

    function cargarEncabezado($pdf, $row1, $row3, $Domicilio, $autoriza, $pagina, $CodHash, $row6) {

        /******************************************************************************************/
        /* ENCABEZADO
        /******************************************************************************************/

        $pdf->image("../public/img/logo_empresa.jpg", 1.2, 1.2 , 4, 1.7); // x , y, ancho, alto
        $pdf->RoundedRect(1, 1, 10, 2.5, 0.2, ''); 

        $pdf->SetTextColor(0,0,150);
        $pdf->SetFont('arial','B',10);
        $pdf->SetXY(5.5,1.3);
        $pdf->MultiCell(5.5, 0.4, utf8_decode($row3['razon_social']), 0, "C", 0);

        
        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','',7);
        $pdf->SetXY(1,2.9);
        $pdf->MultiCell(10, 0.3, utf8_decode($row1['direc']), 0,'C', 0);

        $pdf->SetXY(1,3.2);
        $pdf->MultiCell(10, 0.3, ""."Telf: ".$row1['telef'], 0,'C', 0);


        $pdf->RoundedRect(12, 1, 8, 2.5, 0.2, ''); 

        $pdf->SetTextColor(170,0,0);
        $pdf->SetFont('arial','',12);
        $pdf->SetXY(12,1.2);
        $pdf->Cell(8, 0.25, "RUC: ".$row3['ruc']."", 0, 1,'C', 0);

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','B',12);
        $pdf->SetXY(12,1.8);
        $pdf->Cell(8, 0.25, utf8_decode("GUÍA DE REMISIÓN ELECTRÓNICA"), 0, 1,'C', 0); 

        $pdf->SetXY(12,2.4);
        $pdf->Cell(8, 0.25, utf8_decode("TRANSPORTISTA"), 0, 1,'C', 0); 

        $pdf->SetTextColor(0,0,150);
        $pdf->SetFont('arial','',16);
        $pdf->SetXY(12,3.0);
        $pdf->Cell(8, 0.25, utf8_decode("N°").' '.$row1['nombre_guia'], 0, 1,'C', 0); 

        /******************************************************************************************/
        /* DATOS DEL CLIENTE
        /******************************************************************************************/

        $h_titu = $pdf->GetMultiCellHeight(14, 0.15, utf8_decode($row1['nombre_cliente']) , $border=null, $align='L'); 

        $pdf->RoundedRect(1, 3.8, 19, 1.9+$h_titu, 0.2, ''); 

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','B',9);

        $pdf->SetXY(1.1,4.2);
        $pdf->Cell(1, 0.35, utf8_decode("Fecha de Inicio de Traslado"), 0, 1,'L', 0);

        $pdf->SetXY(1.1,4.8);
        $pdf->Cell(1, 0.35, utf8_decode("Remitente "), 0, 1,'L', 0);

        $pdf->SetXY(12.5,4.2);
        $pdf->Cell(1, 0.35, utf8_decode("DNI / RUC Remitente"), 0, 1,'L', 0);

        $pdf->SetXY(1.1,5.4);
        $pdf->Cell(1, 0.35, utf8_decode("Punto de Partida    "), 0, 1,'L', 0);

        /*$pdf->SetXY(12.5,4.8);
        $pdf->Cell(1, 0.35, utf8_decode("Motivo Traslado"), 0, 1,'L', 0);*/

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','',9);

        $pdf->SetXY(6, 4.2);
        $pdf->Cell(1, 0.35, ":  ".date_format(date_create($row1['fecha_traslado']), 'd-m-Y'), 0, 1,'L', 0);

        $pdf->SetXY(6,4.8);
        $pdf->MultiCell(14, 0.35, ": ".utf8_decode($row1['nombre_cliente']), 0, 'L', 0);

        $pdf->SetXY(16.5, 4.2);
        $pdf->Cell(1, 0.35, ":  ".utf8_decode($row1['ruc_dni']), 0, 1,'L', 0);

        $pdf->SetXY(6,5.4);
        $pdf->MultiCell(14, 0.35, ": ".utf8_decode($row1['punto_partida']), 0, 'L', 0);

        /*$pdf->SetXY(16.5, 4.8);
        $pdf->Cell(1, 0.35, ":  ".utf8_decode($row1['motivo']), 0, 1,'L', 0);*/

        /******************************************************************************************/
        /* DATOS DEL TRASLADO
        /******************************************************************************************/

        $h_parti = $pdf->GetMultiCellHeight(16, 0.15, utf8_decode($row1['punto_partida']) , $border=null, $align='L'); 
        $h_llega = $pdf->GetMultiCellHeight(16, 0.15, utf8_decode($row1['punto_llegada']) , $border=null, $align='L');  

        $pdf->RoundedRect(1, 5.8 +$h_titu, 19, 1.6+$h_parti+$h_llega, 0.2, ''); 

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','B',9);

        $pdf->SetXY(1.1,6.1+$h_titu);
        $pdf->Cell(1, 0.35, utf8_decode("Destinatario"), 0, 1,'L', 0);

        $pdf->SetXY(1.1, 6.6+$h_titu+$h_llega);
        $pdf->Cell(1, 0.35, utf8_decode("DNI / RUC Destinatario"), 0, 1,'L', 0);

        $pdf->SetXY(1.1, 7.2+$h_titu+$h_llega);
        $pdf->Cell(1, 0.35, utf8_decode("Punto de llegada"), 0, 1,'L', 0);

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','',9);

        $pdf->SetXY(5.1,6.1+$h_titu);
        $pdf->MultiCell(16, 0.35, ":  ".utf8_decode($row6['nombre']), 0, 'L', 0);

        $pdf->SetXY(5.1, 6.6+$h_titu+$h_llega);
        $pdf->MultiCell(16, 0.35, ":  ".utf8_decode($row6['numero_documento']), 0, 'L', 0);

        $pdf->SetXY(5.1, 7.2+$h_titu+$h_llega);
        $pdf->MultiCell(16, 0.35, ":  ".utf8_decode($row1['punto_llegada']), 0, 'L', 0);

        $h1 = $h_titu+$h_parti+$h_llega;

        /******************************************************************************************/
        /* DATOS DEL TRANSPORTISTA
        /******************************************************************************************/

        $h_transpor = $pdf->GetMultiCellHeight(14, 0.15, utf8_decode($row1['nombre_transportista']) , $border=null, $align='L'); 

        $pdf->RoundedRect(1, 7.8+$h1, 19, 2+$h_transpor , 0.2, ''); 

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','B',9);

        $pdf->SetXY(1.1,8+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("Empresa de Transporte        :"), 0, 1,'L', 0);

        

        $pdf->SetXY(1.1, 8.6+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("RUC Empresa Transporte    :"), 0, 1,'L', 0);

        $pdf->SetXY(11, 8.6+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("Nombre de Conductor:"), 0, 1,'L', 0);

        $pdf->SetXY(1.1,9.2+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("DNI de Conductor                 :"), 0, 1,'L', 0);

        $pdf->SetXY(11,9.2+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("Placa del Vehiculo:"), 0, 1,'L', 0);

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','',9);

        $pdf->SetXY(6.5,8+$h1);
        $pdf->MultiCell(14, 0.35, utf8_decode($row1['nombre_transportista']), 0, 'L', 0);

        $pdf->SetXY(6.5, 8.6+$h_transpor+$h1); 
        $pdf->Cell(1, 0.35, $row1['documento_transportista'], 0, 1,'L', 0);

       

        $pdf->SetXY(14.5, 8.6+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, ( $row1['nombre_chofer'] ." ".$row1['apellido_chofer'] ), 0, 1,'L', 0);

        $pdf->SetXY(6.5, 9.2+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, $row1['dni_chofer'], 0, 1,'L', 0);

        $pdf->SetXY(14.5, 9.2+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode($row1['marca_placa']), 0, 1,'L', 0);

        /******************************************************************************************/
        /* DATOS DEL VENTA
        /******************************************************************************************/

        $pdf->RoundedRect(1, 10.3+$h1, 19, 1.5+$h_transpor , 0.2, ''); 

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','B',9);

        $pdf->SetXY(1.1, 10.4+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("Documento que Sustenta Traslado   :"), 0, 1,'L', 0);

        $pdf->SetXY(14.1, 10.4+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("Peso (KG)   :"), 0, 1,'L', 0);

        $pdf->SetXY(1.1, 10.9+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("Indicador de Transporte Subcontratado:  "), 0, 1,'L', 0);

        $pdf->SetXY(1.1, 11.4+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode("Observacion :"), 0, 1,'L', 0);

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','',9);
        
        $pdf->SetXY(7.4, 10.4+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, ( $row1['sustento']  ) , 0, 1,'L', 0);


         $pdf->SetXY(16.4, 10.4+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, ( $row1['peso']  ) , 0, 1,'L', 0);


        $pdf->SetXY(7.4, 10.9+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode($row1['motivo']), 0, 1,'L', 0);

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','I',7);

        $pdf->SetXY(3.4, 11.4+$h_transpor+$h1);
        $pdf->Cell(1, 0.35, utf8_decode($row1['observacion']), 0, 1,'L', 0);

        
        /******************************************************************************************/
        /* ENCABEZADO DE PRODUCTOS
        /******************************************************************************************/

        $Y = 4.1 + $h1 + $h_transpor;

        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','B',10);

        $pdf->SetXY(1,$Y+8);
        $pdf->Cell(12.6, 0.5, utf8_decode("Descripción"), 1, 1,'C', 0);

        $pdf->SetXY(13.6,$Y+8);
        $pdf->Cell(2.5, 0.5, utf8_decode("Cantidad"), 1, 1,'C', 0);

        $pdf->SetXY(16.1,$Y+8);
        $pdf->Cell(3.9, 0.5, utf8_decode("Unidad de Medida"), 1, 1,'C', 0);

        /******************************************************************************************/
        /* PIE DE PAGINA
        /******************************************************************************************/
        
         $pdf->image('image/image_qr.png',1, 25.3, 2.3, 2.3);  // x , y, ancho, alto
         
        $pdf->line(1, 25.3, 20.5, 25.3);
        $pdf->SetTextColor(0,0,0);
        $pdf->SetFont('arial','I',9);
        $pdf->SetXY(1,25.5);
        $pdf->MultiCell(19.5, 0.35, utf8_decode("Representación Impresa de la Guia de Remision Electrónica \n Código Hash: $CodHash
        Autorizado para ser Emisor Electrónico por la $autoriza \n $pagina \n GRACIAS POR SU PREFERENCIA !!"), 0, 'C');

        return $Y;

    }

    $Y2 = cargarEncabezado($pdf, $row1, $row3, $Domicilio, $autoriza, $pagina, $CodHash, $row6);

    /******************************************************************************************/
    /* LISTA  DE PRODUCTOS
    /******************************************************************************************/

    $Y = $Y2 + 8.5;
    $Y1 = 0;

    for ($i=0; $i < sizeof($array['detalle']) ; $i++) { 

        $pdf->SetFont('arial','',9);
        
        $h_descrip = $pdf->GetMultiCellHeight(12.6, 0.5, utf8_decode($array['detalle'][$i]['descripcion']), $border=null, $align='L'); 
        
        $pdf->SetXY(1,$Y+$Y1);
        $pdf->MultiCell(12.6, 0.5, utf8_decode($array['detalle'][$i]['descripcion']) , 1, "L", 0);

        $pdf->SetXY(13.6,$Y+$Y1);
        $pdf->Cell(2.5, $h_descrip, utf8_decode($array['detalle'][$i]['cantidad']), 1, 1,'C', 0);
        
        $pdf->SetXY(16.1,$Y+$Y1);
        $pdf->Cell(3.9, $h_descrip, $array['detalle'][$i]['unidad'], 1, 1,'C', 0);


        $Y1 = $Y1 + $h_descrip;

        if ($Y1>8.5) {
            $pdf->AddPage();
            $pdf->Footer(true);
            $Y2 = cargarEncabezado($pdf, $row1, $row3, $Domicilio, $autoriza, $pagina, $CodHash, $row6 );
            $Y = $Y2 + 8.5;
            $Y1 = 0;
        }
         
    }   

    $pdf->SetFont('arial','',9);

    $pdf->line(2, $Y1+15, 8, $Y1+15);
    $pdf->SetXY(1,$Y1+15);
    $pdf->MultiCell(8, 0.5, $row3['razon_social'], 0, "C", 0);

    $pdf->line(13, $Y1+15, 19, $Y1+15);
    $pdf->SetXY(12,$Y1+15);
    $pdf->Cell(7.6, 0.7, utf8_decode("CONFORMIDAD DEL CLIENTE"), 0, 1,'C', 0);


    //==============================================================================

    $pdf->AutoPrint(true);
    $pdf->Output();    

ob_end_flush(); 