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

    /******************************************************************************************/
    /* Funciones 
    /******************************************************************************************/

    function floattostr( $val )
    {
        preg_match( "#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($val), $o );
        return $o[1].sprintf('%d',$o[2]).($o[3]!='.'?$o[3]:'');
    }

    /******************************************************************************************/
    /* consultas SQL
    /******************************************************************************************/
    
    $id = $_GET['id_proforma'];

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

    //Para obtener los datos de la venta
    $query1 = "SELECT p.*, p.created_at as hora, u.username, l.direccion as direc, l.telefono as telef FROM proformas  p INNER JOIN local l ON p.id_local = l.id_local INNER JOIN usuarios u ON p.id_usuario = u.id_usuario WHERE id_proforma = '".$id."' ";
    $result1 = $mysqli->query($query1);
    $row1 = $result1->fetch_assoc();

    //Para obtener los detalles de la venta
    $query2 = "SELECT * , d.precio as precio_unit FROM detalle_proforma d INNER JOIN productos p ON d.id_producto = p.id_producto WHERE id_proforma = '".$id."' AND d.estado = 1" ;
    $result2 = $mysqli->query($query2);

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

    $query4 = "SELECT sum(monto) as pagos FROM detalle_credito WHERE id_proforma = '".$id."' AND estado = 1";
    $result4 = $mysqli->query($query4);
    $row4 = $result4->fetch_assoc();


    // Variables correspondientes a la factura.
    $RUC        = $row1['numero_documento'];    // RUC.
    $NomRazSoc  = $row1['nombre'];              // Nombre o Razón social.
    $FecEmi     = $row1['fecha_emision'];         // Fecha de emisión.
    $Domicilio  = $row1['direccion'];           // Domicilio.
    //$CodHash    = "";                           // Código Hash.
    //$TipoDoc    = $row1['id_tipo_comprobante']; // Tipo de documento.
    $TotGrav    = 0;                            // Total gravado.
    $TotIGV     = 0;                            // Total IGV.
    $TotMonto   = 0;                            // Total importe. 
    $Saldo      = $row1['saldo'];                               
    $Adelanto   = $row1['adelanto'];  
    $autoriza   = $row3['autorizacion'];
    $pagina     = $row3['pagina_web'];
    $empresa    = $row3['razon_social'];
    $Pagos      = $row4['pagos'] == null ? '0.00' : number_format($row4['pagos'], 2);  
   
    // TOTALES DE LA FACTURA 
    
    $sub_total = 0;
    $total = 0;
    $igv = 0;
    $desc = 0;
    $ii=0;
    while($row2 = $result2->fetch_assoc()){

        
        $array['detalle'][$ii]['descripcion'] = $row2['nombre']." ".$row2['descripcion']; 
        $array['detalle'][$ii]['cantidad'] = number_format($row2['cantidad'] , 4, ".", ""); 
        $array['detalle'][$ii]['precio'] = number_format($row2['precio_unit'], 4, ".", ""); 
        $array['detalle'][$ii]['descuento'] = number_format($row2['descuento'] , 2, ".", ""); 
        $array['detalle'][$ii]['subtotal'] = number_format($row2['subtotal'] , 2, ".", ""); 
        $ii++;
    }

    $TotMonto = number_format($row1['total'], 2, '.', '');       

    /******************************************************************************************/
    /* creamos documento PDF
    /******************************************************************************************/
    
    $pdf = new PDF('P','cm', array(8,500));
    //$pdf=new PDF('P','cm','Letter');
    $pdf->AliasNbPages();
    $pdf->AddPage();
    $pdf->AddFont('IDAutomationHC39M','','IDAutomationHC39M.php');
    $pdf->AddFont('helvetica','','helvetica.php');
    $pdf->SetAutoPageBreak(true);
    $pdf->SetMargins(0, 0, 0);
    $pdf->SetLineWidth(0.02);
    $pdf->SetFillColor(0,0,0);
    
    $pdf->image("../public/img/logo_empresa.jpg",1.6, 0.2 , 4.2, 1.5); // x , y, ancho, alto

    $pdf->SetFont('helvetica','B',8);
    $h_empresa = $pdf->GetMultiCellHeight(7, 0.31, utf8_decode($empresa) , $border=null, $align='L'); 
    $pdf->SetXY(0, 1.8);
    $pdf->MultiCell(7.6, 0.3, utf8_decode($empresa), 0, "C", 0);


    $pdf->SetFont('helvetica','',7);
    $pdf->SetXY(0,1.85+ $h_empresa);
    $pdf->Cell(7.6, 0.25, "RUC: ".$row3['ruc']."   Telf: ".$row1['telef']."", 0, 1,'C', 0);

    
    $pdf->SetXY(0, 2.15+ $h_empresa);
    $pdf->MultiCell(7.6, 0.25, utf8_decode($row1['direc']), 0, 'C', 0);
    $h_direcc = $pdf->GetMultiCellHeight(7, 0.31, utf8_decode($row1['direc']) , $border=null, $align='L'); 

    $pdf->SetFont('helvetica','B',10);
    $pdf->SetXY(0,2.55+ $h_empresa + $h_direcc);
    $pdf->Cell(7.6, 0.25, $row1['tipo'].utf8_decode(" N° ").$row1['id_proforma'], 0, 1,'C', 0);

    //DATOS DE FACTURA
    
    $pdf->SetFont('helvetica','B',7);
    $h_titu = $pdf->GetMultiCellHeight(5.1, 0.31, utf8_decode($NomRazSoc) , $border=null, $align='L'); 
    $h_domi = $pdf->GetMultiCellHeight(5.1, 0.31, utf8_decode($Domicilio) , $border=null, $align='L'); 

    $pdf->SetXY(0.2,2.8+$h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, utf8_decode("================================================="), 0, 1,'L', 0);

    $pdf->SetXY(0.25,3.2+ $h_empresa + $h_direcc);
    $pdf->Cell(1.2, 0.35, utf8_decode("Cliente               : "), 0, 1,'L', 0);

    $pdf->SetXY(0.2,3.2+$h_titu+$h_domi+ $h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, utf8_decode("DNI / RUC"), 0, 1,'L', 0);
    
    $pdf->SetXY(0.22,3.2+$h_titu+ $h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, utf8_decode("Domicilio           : "), 0, 1,'L', 0);

    $pdf->SetXY(0.2,3.55+$h_titu+$h_domi+ $h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, utf8_decode("Fecha Emision"), 0, 1,'L', 0);

    $pdf->SetXY(0.2,3.91+$h_titu+$h_domi+ $h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, utf8_decode("Tipo Moneda"), 0, 1,'L', 0);


    $pdf->SetFont('helvetica','',7);

    $pdf->SetXY(2.4,3.2+ $h_empresa + $h_direcc);
    $pdf->MultiCell(5.1, 0.3, utf8_decode($NomRazSoc), 0, "L", 0);

    $pdf->SetXY(2.4,3.2+$h_titu+ $h_empresa + $h_direcc);
    $pdf->MultiCell(5.1, 0.3,utf8_decode($Domicilio) , 0, "L", 0);

    $pdf->SetXY(2.1,3.2+$h_titu+$h_domi+ $h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, ":   ".utf8_decode($RUC), 0, 1,'L', 0);

    $pdf->SetXY(2.1,3.55+$h_titu+$h_domi+ $h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, ":   ".date_format(date_create($FecEmi), 'd-m-Y')."     Hora : ".date("H:i:s", strtotime($row1['hora'])), 0, 1,'L', 0);

    $pdf->SetXY(2.1,3.91+$h_titu+$h_domi+ $h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, ":   ".utf8_decode("SOLES"), 0, 1,'L', 0);

    //DATOS DETALLE FACTURA
    
    $pdf->SetXY(0.2,4.2+$h_titu+$h_domi+$h_empresa + $h_direcc);
    $pdf->Cell(1, 0.35, utf8_decode("================================================="), 0, 1,'L', 0);

    $Y = $h_titu+$h_domi+ $h_empresa + $h_direcc;

    $pdf->SetTextColor(0,0,0);
    $pdf->SetFont('helvetica','B',7);

    $pdf->SetXY(0.2,$Y+4.4);
    $pdf->Cell(0.8, 0.5, utf8_decode("Cant."), 0, 1,'C', 0);

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

    $pdf->SetXY(4,$Y+4.4);
    $pdf->Cell(1.2, 0.5, utf8_decode("Precio"), 0, 1,'R', 0);

    $pdf->SetXY(5,$Y+4.4);
    $pdf->Cell(1.2, 0.5, utf8_decode("Dscto"), 0, 1,'R', 0);

    $pdf->SetXY(6.2,$Y+4.4);
    $pdf->Cell(1.2, 0.5, utf8_decode("Importe"), 0, 1,'R', 0);

    $pdf->SetXY(0.2,$Y+4.75);
    $pdf->Cell(1, 0.35, utf8_decode("================================================="), 0, 1,'L', 0);

    $pdf->SetFont('helvetica','',7);
    $Y=$Y+5.2;
    $Y1 = 0;

    for ($i=0; $i < sizeof($array['detalle']) ; $i++) { 
        
        $h_descrip = $pdf->GetMultiCellHeight(3, 0.35, utf8_decode($array['detalle'][$i]['descripcion']), $border=null, $align='L'); 

        $pdf->SetXY(0.2,$Y+$Y1);
        $pdf->Cell(0.8, 0.35, floattostr($array['detalle'][$i]['cantidad']), 0, 1,'C', 0);

        $pdf->SetXY(1.0,$Y+$Y1);
        $pdf->MultiCell(3, 0.35, utf8_decode($array['detalle'][$i]['descripcion']) , 0, "L", 0);

        $pdf->SetXY(3.9,$Y+$Y1);
        $pdf->Cell(1.2, 0.35, floattostr($array['detalle'][$i]['precio']), 0, 1,'R', 0);

        $pdf->SetXY(5.3,$Y+$Y1);
        $pdf->Cell(0.8, 0.35, ($array['detalle'][$i]['descuento']==0 ? number_format($array['detalle'][$i]['descuento'],2) : '-'.number_format($array['detalle'][$i]['descuento'],2) ), 0, 1,'R', 0);

        $pdf->SetXY(6,$Y+$Y1);
        $pdf->Cell(1.4, 0.35, $array['detalle'][$i]['subtotal'], 0, 1,'R', 0);

        $Y1 = $Y1 + $h_descrip;
    } 

    //TOTALES FACTURA
    
    $pdf->SetFont('helvetica','',7);

    $Y2 = $Y1 + $h_titu+$h_domi+ $h_empresa + $h_direcc + 5.2 ;

    $pdf->line(0.25, $Y2+0.3, 7.35, $Y2+0.3);


    if (!is_null($Adelanto) && !is_null($Saldo)) {

        $pdf->SetXY(0.2, $Y2+0.5);
        $pdf->Cell(6, 0.35, utf8_decode("A Cuenta         S/ "), 0, 1,'R', 0);

        $pdf->SetXY(0.2, $Y2+1);
        $pdf->Cell(6, 0.35, utf8_decode("Pago de Letras          S/ "), 0, 1,'R', 0);

        $pdf->SetXY(0.2, $Y2+1.5);
        $pdf->Cell(6, 0.35, utf8_decode("Saldo          S/ "), 0, 1,'R', 0);

        $pdf->SetXY(6.2, $Y2+0.5);
        $pdf->Cell(1.2, 0.35, number_format($Adelanto,2), 0, 1,'R', 0);

        $pdf->SetXY(6.2, $Y2+1);
        $pdf->Cell(1.2, 0.35, $Pagos, 0, 1,'R', 0);

        $pdf->SetXY(6.2, $Y2+1.5);
        $pdf->Cell(1.2, 0.35, number_format($Saldo,2), 0, 1,'R', 0);

        $pdf->line(0.25, $Y2+2, 7.35, $Y2+2);

        $Y2 = $Y2 + 1.9;
    }


    $pdf->SetFont('helvetica','B',9);
    $pdf->SetXY(0.2,$Y2+0.5);
    $pdf->Cell(5.8, 0.35, utf8_decode("Importe Total         "), 0, 1,'R', 0);

    $pdf->SetXY(6.2,$Y2+0.5);
    $pdf->Cell(1.2, 0.35, "S/ ".number_format($TotMonto,2), 0, 1,'R', 0);

    $pdf->line(0.25, $Y2+1, 7.35, $Y2+1);

    //Monto en LETRAS
    $letras = NumeroALetras::convertir($TotMonto, 'soles', 'centimos');
    $pdf->SetFont('helvetica','BI',6.5);
    $pdf->SetXY(0.15,$Y2+1.3);
    $pdf->MultiCell(7, 0.35,"SON : ".$letras ."  SOLES" , 0, 'L');


    //Observacion
    $h_obser = 0; 
    if (!is_null($row1['observacion'])) {
        $h_obser = $pdf->GetMultiCellHeight(7, 0.35, utf8_decode($row1['observacion']), $border=null, $align='L'); 
        $pdf->SetFont('helvetica','I',6.5);
        $pdf->SetXY(0.15,$Y2+2);
        $pdf->MultiCell(7, 0.35,"OBSERVACION : ".utf8_decode($row1['observacion']), 0, 'L');
    }

    // nombre de usuario
    $pdf->SetFont('helvetica','BI',6.5);
    $pdf->SetXY(0.1,$Y2+2.3+$h_obser);
    $pdf->MultiCell(5, 0.4,"USUARIO : ".$row1['username'] , 0, 'L');
 
  
    //PIE DE PAGINA

    $pdf->SetTextColor(0,0,0);
    $pdf->SetFont('helvetica','BI',6.5);
    $pdf->SetXY(0.1,$Y2+3+$h_obser);
    $pdf->MultiCell(7.5, 0.35, utf8_decode("Comprobante NO VALIDO, reclame su BOLETA o FACTURA \n $pagina \n GRACIAS POR SU PREFERENCIA !!"), 0, 'C'); 

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

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