<?php   
	session_start();

    $id=isset($_REQUEST['id'])?$_REQUEST['id']:0;
    include ("coneccionfe.php");
    require ('mem_image.php');   
	include("phpqrcode/qrlib.php");

    header("Content-type: text/html; charset=ISO-8859-1");
    $link = pg_connect("host=$dbhost port=$dbport user=$dbuser password=$dbpwd dbname=$dbname")or die(pg_last_error($link));

	#INICIO DEL ARMADO DEL PDF con la libreria FPDF
    $pdf = new FPDF('P','mm',array(210,297));
    $pdf= new PDF_MemImage('P','mm',array(210,277));
	
	function header_documento($obj_pdf, $doc, $link)
	{
		$obj_pdf->AddPage();
		$obj_pdf->Image("../img/logofe20563192802.png",9,15,70,21,"png");
		

		$obj_pdf->SetFont('Arial','B',10);
		$obj_pdf->SetTextColor(60);
		$obj_pdf->ln(5);
		$obj_pdf->Cell(124,5,"",0);
		$obj_pdf->Cell(75,5,"",0);
		$obj_pdf->ln();
		
		
		pg_query($link, "begin");
		$solotboleta = "";
		$tipodoc = "";
		$visible_lb_guia = true;
		$refnumdocafectado = "";
		$labelguiamotivo = "Guías";
		$creferencia_guias = $doc["creferencia_guias"];
		$nlon= strpos($creferencia_guias,"/");
		
		if ($doc['tipodoc']=='01')
		{
			$tipodoc = "FACTURA ELECTRÓNICA";
			$doccliente = "R.U.C.";
			$visible_lb_guia = true;
			$refnumdocafectado =  $doc["vreferencia"];
			
		}
		elseif ($doc['tipodoc']=='03')
		{
			$solotboleta = "BOLETA DE VENTA";
			$tipodoc = "ELECTRÓNICA";
			$doccliente = "D.N.I.";
			$visible_lb_guia = false;
			$refnumdocafectado =  $doc["vreferencia"];
		}
		elseif ($doc['tipodoc']=='07')
		{
			$solotboleta = "NOTA DE CREDITO";
			$tipodoc = "ELECTRÓNICA";
			$doccliente = "R.U.C.";
			$visible_lb_guia = false;
			$refnumdocafectado = $doc["numdocafectado"];
			$labelguiamotivo = "Motivo";
			$creferencia_guias =  $doc["dscmotivo"];
		}
		elseif ($doc['tipodoc']=='08')
		{
			$solotboleta = "NOTA DE DEBITO";
			$tipodoc = "ELECTRÓNICA";
			$doccliente = "R.U.C.";
			$visible_lb_guia = false;
			$refnumdocafectado = $doc["numdocafectado"];
			$labelguiamotivo = "Motivo";
			$creferencia_guias =  $doc["dscmotivo"];
		}
		
		$DOCUMENTO = "R.U.C.";
		
		$Cliente     = strtoupper($doc[7]);	
		$DireccMinus  =  ucwords(strtolower($doc["dirreceptor"]));
		//$FechaFrmEuro = date("d-m-Y",strtotime($doc[5]));
		$FechaFrmEuro = date("d-m-Y",strtotime($doc["fechemision"]));
		$Fechvcto = date("d-m-Y",strtotime($doc["fechvcto"]));
		
		$numdocafectado = $doc["rucreceptor"];
		$fpago = $doc["fpago"];
		$fpago = $doc["fpago"]." ". $doc["dvcto"] ." ". utf8_decode(" DÍAS") ;
		
		
		$rzonscialemi = $doc["rznsocemisor"];
				
		$obj_pdf->Rect(130,15,70,27);
		#ENCABEZADO DEL RUC. DOC. SERIE
		$ruc = $doc["rucemisor"];
		$obj_pdf->Cell(125,5,"",0);
		$obj_pdf->Cell(65,5,"$DOCUMENTO $ruc",0,0,"C");
		$obj_pdf->ln();
		$obj_pdf->Cell(125,5,"",0);
		$obj_pdf->Cell(68,5,"$solotboleta",0,0,'C');
		$obj_pdf->ln();
		$obj_pdf->Cell(125,5,"",0);
		$obj_pdf->Cell(65,1,utf8_decode("$tipodoc"),0,0,"C");
		$obj_pdf->ln();
		$cdocumentoSN = $doc["serie"]."-".$doc["correlativo"];
		$obj_pdf->SetFont('Arial','B',12);
		$obj_pdf->ln();		
		$obj_pdf->Cell(330,10,"$cdocumentoSN",0,0,"C");
		
		$obj_pdf->ln();
		
		$obj_pdf->SetFont('Arial','B',10);
		//$obj_pdf->Cell(1,5,"",0);
		$obj_pdf->Cell(120,-3,"GROUP CORPORATION MED S.R.L.",0);
		
		$obj_pdf->Cell(70,4,"",0);
		$obj_pdf->ln();
		$obj_pdf->SetFont('Arial','',8);
		//$direccion1 = "Jr. Los Mirtos Nº 590 Int. 1406, Urb. San Eugenio - Lince Lima Lima Perú";
		$direccion1 = "Dirección Fiscal:";
		$direccion2 = "Telefeno: 765-4270 / Celular: 917873122 ";
		
		
		//$direccion4 = "Callao.Prov.Const. del Callao.";
		$direccion3 = "E-mail: grupomedsrl@gmail.com";
		$direccion5 = "";
		$direccion6 = "";
		$direccion7 = "";
		
		$telefono = "";
		
		$direccion1 = "Pj. Los Pinos mza A Lt 9 Av. Los Pinos de Ñaña (Alt de urbanización Alamenda de Ñana) Lima-Lima-Lurigancho";
		$creferencia_guias = $doc["creferencia_guias"];
		$nlon= strpos($creferencia_guias,"/");
		if ($nlon >0)
		{
			//$creferencia_guias = "";
		}
		$obj_pdf->Ln(4);
		$obj_pdf->SetFont('Arial','',8);
		$y = $obj_pdf->GetY();
		$obj_pdf->MultiCell(150,-4,utf8_decode("$direccion1"),0);
		$obj_pdf->SetXY(140,$y);
		$obj_pdf->Ln(1);
		 
		$obj_pdf->Cell(120,4,utf8_decode("$direccion2"),0);
		$obj_pdf->Ln(4);
	
				
		$obj_pdf->SetFont('Arial','',8);
		$obj_pdf->Cell(120,4,utf8_decode("$direccion3"),0);
		$obj_pdf->ln(1);
		
		
		//$obj_pdf->Cell(120,4,utf8_decode(".$direccion4."),0);
		//$obj_pdf->ln();
		$obj_pdf->Cell(120,4,utf8_decode("$direccion5"),0);
		$obj_pdf->ln();
		$obj_pdf->Cell(120,4,utf8_decode("$direccion6"),0);
	 
		$obj_pdf->ln(2);
		
		$y = $obj_pdf->GetY();
		$x = $obj_pdf->GetX();
		//$obj_pdf->SetXY(9,$y);
		
		
		$obj_pdf->Rect(10,63,191,34);
		//1 = IZQUIERDA, 2 = ARRIBA, 3= DERECHA, 4 = ALTO
		$obj_pdf->Cell(131,5,"",0);
		$obj_pdf->SetFont('Arial','B',8);	 
		$obj_pdf->SetFont('Arial','',8);
		$obj_pdf->Cell(20,5,"",0);
		$obj_pdf->Ln(1);
		$obj_pdf->SetFont('Arial','B',7);
		#$obj_pdf->Cell(2);
		$obj_pdf->Cell(18,5,utf8_decode("SEÑOR(ES)"),0);
		$obj_pdf->SetFont('Arial','',7);
		$obj_pdf->Cell(130,5,utf8_decode(": $Cliente"),0);
		$obj_pdf->SetFont('Arial','B',7);
		 if ($visible_lb_guia)
		{
			//$obj_pdf->Cell(22,5,utf8_decode("N° de Guía: $creferencia_guias"),0);
		}
		else
		{
			//$obj_pdf->Cell(22,5,"",0);
		}
		
		$TipoMoneda = " ";
		$Simbolo = "";
		if ($doc["tipomoneda"]=="USD") {
		$TipoMoneda = "Dólares";
		$Simbolo = "US$";
		} else {
			$TipoMoneda = "Soles";
			$Simbolo = "S/";
		}
	   
		$obj_pdf->SetFont('Arial','',7);
		$obj_pdf->Cell(20,5,"",0);
		$obj_pdf->Ln(4);
	
		$tipoventa = "FORMA DE PAGO";
		if (trim($doc['cexp'])=="02")
			{
				
				$tipoventa = "TIPO DE VENTA";
			}
		$vendedor = $doc["cdsc_vend"];
		
		$obj_pdf->SetFont('Arial','B',7);
		$obj_pdf->Cell(18,5,"$doccliente",0);
		$obj_pdf->SetFont('Arial','',7);
		$obj_pdf->Cell(108,5,": $doc[6]",0);
		$obj_pdf->SetFont('Arial','B',7);
		   $obj_pdf->Cell(28,5,utf8_decode($tipoventa),0);
	   // $obj_pdf->Cell(30,5,utf8_decode("Fecha de emisión"),0);
		$obj_pdf->SetFont('Arial','',7);
		 $obj_pdf->Cell(20,5,": $fpago",0);
	  //  $obj_pdf->Cell(20,5,": $FechaFrmEuro",0);
		$obj_pdf->Ln(4);
		#$obj_pdf->Cell(2);
		$obj_pdf->SetFont('Arial','B',7);
		$obj_pdf->Cell(18,5,utf8_decode("DIRECCIÓN "),0);
		
		$obj_pdf->SetFont('Arial','',7);
		$obj_pdf->Cell(2,5,":",0);
		$y = $obj_pdf->GetY();
		$obj_pdf->MultiCell(90,5,utf8_decode("$DireccMinus"),0);
		$obj_pdf->SetXY(136,$y);
		$obj_pdf->SetFont('Arial','B',7);
		$obj_pdf->Cell(28,5,"VENDEDOR",0);
		$obj_pdf->SetFont('Arial','',7);
		$obj_pdf->Cell(20,5,": $vendedor",0);
		$obj_pdf->SetFont('Arial','B',7);
		$obj_pdf->Ln(4);
		$y = $obj_pdf->GetY();
		$obj_pdf->SetXY(136,$y);
		$obj_pdf->Cell(28,5,"TIPO DE MONEDA",0);
		$obj_pdf->SetFont('Arial','',7);
		$obj_pdf->Cell(20,5,utf8_decode(": $TipoMoneda"),0);
		$obj_pdf->Ln(5);
		#REFERENCIA
		$obj_pdf->SetFont('Arial','B',7);
		$obj_pdf->Cell(18,5,utf8_decode("REFERENCIA"),0);
		$obj_pdf->SetFont('Arial','',7);
		$obj_pdf->Cell(108,5,utf8_decode(": $refnumdocafectado"),0);
		$obj_pdf->SetFont('Arial','B',7);
		$obj_pdf->Cell(28,5,utf8_decode("FECHA DE EMISIÓN"),0);
		$obj_pdf->SetFont('Arial','',7);
		$obj_pdf->Cell(20,5,": $FechaFrmEuro",0);
		$obj_pdf->Ln(5);
		
		$fvcto1 = "FECHA DE VCTO";
		$fvcto2 = $Fechvcto;
		if (trim($doc['cexp'])=="02")
			{
				$fvcto1 = " ";
				$fvcto2 = " ";
			}
			
		$y = $obj_pdf->GetY();
			$obj_pdf->SetXY(136,$y);
			$obj_pdf->SetFont('Arial','B',7);
			$obj_pdf->Cell(28,3,$fvcto1,0);
			$obj_pdf->SetFont('Arial','',7);
			$obj_pdf->Cell(20,3,": $fvcto2",0);
		if ($visible_lb_guia)
		{
			$obj_pdf->Ln(4);
			$obj_pdf->SetFont('Arial','B',7);
			$obj_pdf->Cell(18,5,utf8_decode("GUIAS"),0);
			$obj_pdf->SetFont('Arial','',7);
			$obj_pdf->MultiCell(168,5,utf8_decode(": $creferencia_guias"),0);
			
			
		}
		else
		{
			//$obj_pdf->Cell(22,5,"",0);
			
		}
	
	   $obj_pdf->SetFont('Arial','B',7);
	   $obj_pdf->Ln(4);
	   $obj_pdf->Cell(15,5,utf8_decode("CÓDIGO"),1,0,'C');
	   $obj_pdf->Cell(112,5,utf8_decode("DESCRIPCIÓN DEL PRODUCTO"),1,0,'C');
	   $obj_pdf->Cell(10,5,"UM",1,0,'C');
	   $obj_pdf->Cell(18,5,"CANTIDAD",1,0,'C');
	   $obj_pdf->Cell(18,5,"PRECIO UNIT.",1,0,'C');
	   $obj_pdf->Cell(18,5,"VALOR VENTA",1,0,'C');
	   $obj_pdf->Ln(6);
	}
	
	
		
	$sqlca = "SELECT b.id_febinario_tc, 
	a.rucemisor, 
	a.tipodoc, 
	a.serie, 
	a.correlativo,
	a.fechemision, 
	a.rucreceptor, 
	a.rznsocreceptor,
    a.".chr(34)."datoadicional002".chr(34).",
	a.tipomoneda, 
	a.montodescuentos, 
	a.montogravadas, 
	a.montoinafectos,
    a.montoexonerado, 
	a.montoigv,
	a.montoisc, 
	a.".chr(34)."datoadicional009".chr(34)." as cnumeroletra,
	a.nombre_txt, 
	a.stat_anulado,
    a.rucreceptor,
	".chr(34)."datoadicional001".chr(34)." as fpago,	
	a.montototal, a.rznsocemisor,
	".chr(34)."datoadicional004".chr(34)." as detra, a.numdocafectado,
	a.datoadicional003 as creferencia_guias, a.dirreceptor, a.tasaimpuesto, a.dscmotivo, a.fechvcto  as fechvcto, a.referencia as vreferencia,
	a.".chr(34)."datoadicional015".chr(34)." as cexp, a.".chr(34)."datoadicional007".chr(34)." as cdsc_vend,  a.".chr(34)."datoadicional005".chr(34)." as dvcto
	FROM ".chr(34)."$schema".chr(34).".fa_faele_tc a
   	inner join fa_febinario_tc b on a.tipodoc = b.tipodoc and a.serie = b.serie and a.correlativo = b.correlativo
    where b.id_febinario_tc = $id";
		
	//echo $sqlca;
// datoAdicional_001
	
	
	$content = pg_query($link,"set search_path to 'SHFE';SELECT a.rucemisor || '|' || a.tipodoc || '|' || a.serie || '|' || a.correlativo || '|' || a.montoigv || '|' || 
	a.montototal || '|' || a.fechemision || '|' || a.tipodocreceptor || '|' || a.rucreceptor || '|' as qr, a.rucemisor || '-' ||a.tipodoc || '-' || a.serie || '-' || a.correlativo as nombre FROM fa_faele_tc a
	inner join fa_febinario_tc b on a.serie = b.serie and a.correlativo = b.correlativo where id_febinario_tc = $id;");
	
	$objAd = pg_fetch_object($content);
 
	QRcode::png($objAd->qr,"$objAd->nombre.png",QR_ECLEVEL_L,3,1.2);
	
	$qr = "<img src='$objAd->nombre.png'/>";
	
	
    $result=pg_query($link, $sqlca);

    while($row=pg_fetch_array($result)){
        $doc = $row;
    }

    
	$TipoMoneda = " ";
	$Simbolo = "";
	if ($doc[9]=="USD") {
		$TipoMoneda = "Dólares";
		$Simbolo = "US$";
	} else {
		$TipoMoneda = "Soles";
		$Simbolo = "S/";
	}
	$detra = $doc["detra"];
	
    $nomarchivo = str_replace('txt', 'pdf', $doc['nombre_txt']);

    
    
    #CABECERA
	header_documento($pdf, $doc, $link);
	
	

    $pdf->SetFont('Arial','B',9);
	// fin de encabezado
	
    #DETALLE
	/*
    $sqldet = "select codproducto,desitem,ctdunidaditem,mtovalorunitario,mtoprecioventaitem,
	codunidadmedida from ".chr(34)."$schema".chr(34).".fa_faelectronica_td where ccod_ruc='$doc[1]' 
	and ccod_doc='$doc[2]' and cdoc_serie='$doc[3]' and cdoc_nro = '$doc[4]'";
	*/
	 $sqldet = " select a.codigoitem, a.nombreitem, a.qtyitem,a.montoprecio,a.montoventa,a.unmditem from 
    ".chr(34)."$schema".chr(34).".fa_faele_td a inner join 
    ".chr(34)."$schema".chr(34).".fa_faele_tc b on a.tipodoc = b.tipodoc and a.serie = b.serie 
	and a.correlativo = b.correlativo where b.rucemisor='$doc[1]' 
	and a.tipodoc='$doc[2]' and a.serie='$doc[3]' and a.correlativo = '$doc[4]'";
	
	
    $result=pg_query($link, $sqldet);
    $numregs=pg_num_rows($result);

   
   
   $pdf->SetFont('Arial','',8);
    $i=0;
    $count =0;
	$filaspaginas = 0;
	$ifillRecord = 0;
	
    while($i<$numregs){
		if ($ifillRecord==27)
		{
			//$pdf->AddPage();
			header_documento($pdf, $doc, $link);
			$pdf->Ln(1);
			$filaspaginas = $filaspaginas+ 100;
			$ifillRecord = 0;
		}
		
         $codigo=pg_result($result,$i,'codigoitem');
         $descri=pg_result($result,$i,'nombreitem');
         $unimet=pg_result($result,$i,'unmditem');
         $cantid=pg_result($result,$i,'qtyitem');
         $valoru=pg_result($result,$i,'montoprecio');
         $preven=pg_result($result,$i,'montoventa');
         $pdf->SetFont('Arial','',7);
		 $y = $pdf->GetY();  
		  $abe= strlen($descri);
		// $pdf->MultiCell(100,3,"We declare " ,1,'L',false); 		 
         $pdf->Cell(15,5,$codigo,0,0,'L');
         $pdf->SetFont('Arial','',7);
		 $pdf->MultiCell(125,5,$descri,0,'L',false);
		 $pdf->SetXY(138,$y);
         $pdf->Cell(10,5,$unimet,0,0);
		 $pdf->SetXY(145,$y);
         $pdf->Cell(18,5,number_format($cantid,2),0,0,'R');
		 $pdf->SetXY(165,$y);
         $pdf->Cell(18,5,number_format($valoru,5),0,0,'R');
         $pdf->Cell(18,5,number_format($preven,2),0,0,'R');
		 
        if ($abe > 200){
			 $pdf->Ln(25);
			 $count = $count + 25;	 
		}elseif ($abe > 120){
			 $pdf->Ln(20);
			 $count = $count + 20;
		}elseif ($abe > 80){
			 $pdf->Ln(15);
			 $count = $count + 15;
		}elseif ($abe > 40){
			 $pdf->Ln(10);
			 $count = $count + 10;
		}else{
			 $pdf->Ln(5);
			 $count = $count + 5;
		}
		
         $i++;
		 $ifillRecord++;
    }
	
  //  $pdf->Cell(18,5,"Observacion:",0);
//	$pdf->multiCell(120,5,".$datoadicional_001",0);

	//$espacio = 95 - $count;
	
    //$espacio = (105+$filaspaginas)- $count;
	//$espacio = (105+100)- $count;
	$espacio = 2;
    $pdf->Ln($espacio);
    
		
    
	$pdf->SetFont('Arial','B',7);
	 
     $pdf->ln(5);
	
	$pdf->Cell(190,5,"SON ".$doc["cnumeroletra"],1,0,'L');
    $pdf->Cell(190,5,"",0,0,'C');
	//$obj_pdf->Cell(18,5,"VALOR VENTA",1,0,'C');
	$pdf->ln(8);
	$vp2 = "$objAd->nombre.png";
	$pdf->Image($vp2);
	
	    $pdf->SetFont('Arial','',8.5);
		$y = $pdf->GetY();
		$pdf->SetXY(135,$y);
		
		$pdf->Cell(45,-50,"SUB TOTAL  ".$Simbolo,0);
		$pdf->Cell(20,-50,number_format($doc["montogravadas"],2),0,0,'R');
	
	     
		$pdf->ln(5);
		
		
		$y = $pdf->GetY();
		$pdf->SetXY(135,$y);
		$pdf->Cell(45,-50,"I.G.V. ".$doc["tasaimpuesto"] . " %"."   ".$Simbolo,0); 
		$pdf->Cell(20,-50,number_format($doc["montoigv"],2),0,0,'R');
		$pdf->ln(5);
		
		$y = $pdf->GetY();
		$pdf->SetXY(135,$y);
		$pdf->Cell(45,-50,"TOTAL ".$Simbolo,0);
		$pdf->Cell(20,-50,number_format($doc["montototal"],2),0,0,'R');
		
	
	$spot= "../imagenes/spotd20524829097.png";
	$rb= "../imagenes/rb20601547687.png";
	
	
	if ($detra=="DETRA")
	{
		//$pdf->Image($spot,70,218.2,-200);
		//$pdf->Image($spot,70,200.2,-200);
	}
	
	$pdf->ln(1);
	
	
	
	$y = $pdf->GetY();
	$x = $pdf->GetX();
	$pdf->SetXY(9,$y);
    //$pdf->Image($rb,$x,$y,95,35,"png");
	//$obj_pdf->Image("../cperun/img/logofe20601547687.png",9,15,18,22,"png");
	$pdf->ln(1); 
	
	 $pdf->SetFont('Arial','B',6);
	 $pdf->Cell(40,5,"SIRVASE ABONAR EN :",1,0,'C');
	 $pdf->ln(5); 
	 $pdf->Cell(40,5,utf8_decode("BCP M.N. 191-2304221-0-59"),1,0,'C');
	 $pdf->ln(5); 
	 $pdf->Cell(40,5,utf8_decode("CCI. 00219100230422105953"),1,0,'C');
	 $pdf->SetFont('Arial','',7);
	 
	$pdf->Output('D',$nomarchivo,true);
	unlink($vp2);
	
?>
