<?php

require_once('pdf/pdf_js.php');
session_cache_limiter('private');
session_start();
$com = "I";
include("DMMYSQLG.php");
require_once("DF80000.php");
include("DMMYSQLG.php");
//include("DSA3000.php");
class PDF extends PDF_JavaScript{
	function AutoPrint($dialog=false){
		//Open the print dialog or start printing immediately on the standard printer
		$param=($dialog ? 'true' : 'false');
		$script="print($param);";
		$this->IncludeJS($script);
	}
	
	function AutoPrintToPrinter($server, $printer, $dialog=false){
		//Print on a shared printer (requires at least Acrobat 6)
		$script =  "var pp = getPrintParams();";
		if($dialog)
			$script .= "pp.interactive = pp.constants.interactionLevel.full;";
		else
			$script .= "pp.interactive = pp.constants.interactionLevel.automatic;";
		$script .= "pp.printerName = '\\\\\\\\".$server."\\\\".$printer."';";
		$script .= "print(pp);";
		$script .= "print(pp);";
		$script .= "print(pp);";
		$this->IncludeJS($script);
	}
	function SendToDefaultPrinter($dialog=false,$printer="",$arrOpt=NULL){
		//$script ='trustedPrint = app.trustedFunction(function(){';
		//$script .= '	app.beginPriv();';
		$script .= "	var pp = getPrintParams();";
		$script .= "	fv = pp.constants.flagValues;";
		$script .= "	pp.flags |=(fv.suppressCenter|fv.suppressRotate);";
		$script .= "	pp.pageHandling=pp.constants.handling.none;";		
		($dialog)?($script .= "	pp.interactive = pp.constants.interactionLevel.full;"):($script .= "pp.interactive = pp.constants.interactionLevel.automatic;");
		//$script .= "this.print(pp);";
		$script .= "	this.print(pp);";
		$script .= "	this.print(pp);";
		$script .= "	this.print(pp);";
		//$script .= "	app.endPriv();";
		//$script .= '}';
		//$script .='trustedPrint();';
				
		$this->IncludeJS($script);				
	}
}

$dt_parame =mysqli_fetch_array(mysqli_query($con ,"select * from dgparame"));

$arrHoja=array(180,215);
$pdf=new PDF('P','mm','Letter');

$pdf->SetMargins(6,0,5);
$pdf->SetAutoPageBreak(true,5);
(isset($_REQUEST['noleyref']))?($leyRefFac=false):($leyRefFac=true);
//$pdf->AddFont('ARIAL');
$pdf->AddPage();
if(!isset($_REQUEST['bot']) || $_REQUEST['bot']==""){
	$pdf->SetFont('ARIAL','B',20);
	$pdf->SetY(50);
	$pdf->SetTextColor(100,30,0);	
	$pdf->Cell(198,15,"A T E N C I O N !",0,1,'C');
	$pdf->SetTextColor(0);			
	for($i=0;$i<5;$i++){
		$pdf->Cell(198,10,"NO ES UN FORMATO VALIDO DE IMPRESION!",0,1,'C');	
	}
	$pdf->Output("NOFACTURA.pdf",'I');
	exit();
}
$dt_factur=mysqli_fetch_array(mysqli_query($con ,"SELECT * FROM dgfactur WHERE fol_fac = '".$_REQUEST['bot']."'"));
$dt_catcli=mysqli_fetch_array(mysqli_query($con ,"SELECT * FROM dgcatcli WHERE cod_cli = '".$dt_factur['cod_cli']."'"));
$dt_catven=mysqli_fetch_array(mysqli_query($con ,"SELECT * FROM dgcatven WHERE cod_ven = '".$dt_factur['cod_ven']."'"));
$dt_tipven=mysqli_fetch_array(mysqli_query($con ,"SELECT * FROM dgtipven WHERE tip_ven = '".$dt_factur['tip_ven']."'"));

@$dt_bascps=mysqli_fetch_array(mysqli_query($con ,"select * from dxbascps where codigo = '".$dt_catcli['codigo']."'"));
@$dt_coloni=mysqli_fetch_array(mysqli_query($con ,"select * from geoyos_jc.dxcoloni where cve_col = '".$dt_bascps['des_colonia']."'"));
@$dt_delmun=mysqli_fetch_array(mysqli_query($con ,"select * from geoyos_jc.dxdelmun where cve_delmun = '".$dt_bascps['cve_delmun']."'"));
@$dt_estado=mysqli_fetch_array(mysqli_query($con ,"select * from geoyos_jc.dxestado where cve_estado = '".$dt_bascps['cve_estado']."'"));
@$dt_paises=mysqli_fetch_array(mysqli_query($con ,"select * from geoyos_jc.dxpaises where cve_pais = '".$dt_bascps['cve_pais']."'"));
@$dt_bascpt=mysqli_fetch_array(mysqli_query($con ,"select * from dxbascpt where codigo = '".$dt_catcli['codigo']."'"));
mysqli_query($con ,"SET group_concat_max_len =5020");
$dt_pememaSum=mysqli_fetch_array(mysqli_query($con ,"SELECT SUM(sub_ven) as subFac,SUM(iva_ven) as ivaFac,SUM(tot_ven) as totFac, GROUP_CONCAT(dgpemema.con_ven ORDER BY dgpemema.con_ven ASC SEPARATOR ', ') as folSel,CONCAT(dgpemema.apa_cli_alt,' ',dgpemema.ama_cli_alt,' ',dgpemema.nom_cli_alt) as nomCliAlt,dgpemema.fac_ant as facAnt,dgpemema.fec_ven as fecVen FROM dgpemema WHERE tip_ven='".$dt_tipven['tip_ven']."' AND num_fac='".$dt_factur['num_fac']."' group by num_fac order by dgpemema.con_ven"));
$dt_facturFacAnt=mysqli_fetch_array(mysqli_query($con ,"SELECT con_cre as conCre, num_fac as numFac,es_glo as esGlo,tip_fac as tipFac,fec_fac as fecFac FROM dgfactur where num_fac='".$dt_pememaSum['facAnt']."' AND tip_fac='".$dt_tipven['tip_fac']."'"));

$auxArrFolFac=explode(",",$dt_pememaSum['folSel']);
if($dt_factur['iva_des']=='1') $bIVA=true;
else $bIVA=false;
$pdf->SetFont('ARIAL','',8);
$pdf->Ln(20);
$auxFecFac=explode("/",chfecha($dt_factur['fec_fac'],'Y-m-d','d/M/Y'));
/*****************FECHA FACTURA********************/
$adjX=-2;
$adjY=0;
$posFecY=42;

$pdf->SetXY(100+$adjX,$posFecY+$adjY); $pdf->Cell(15,3,$auxFecFac[0],0,0,'C');
$pdf->SetXY(120+$adjX,$posFecY+$adjY); $pdf->Cell(40,3,$auxFecFac[1],0,0,'C');
$pdf->SetXY(170+$adjX,$posFecY+$adjY); $pdf->Cell(20,3,$auxFecFac[2],0,0,'C');

/************************************************/

/***********NUMERO FACTURA SISTEMA*****************/
$posNumFacX=160;
$posNumFacY=47;

$pdf->SetXY($posNumFacX+$adjX,$posNumFacY+$adjY); 
$pdf->Cell(30,3,$dt_tipven['tip_fac'].$dt_factur['num_fac'],0,0,'L');
/************************************************/

/***********REF FACTURA SISTEMA*****************/
if($dt_factur['con_cre']=='W' && $leyRefFac){
	$posNumRefFacX=190;
	$posNumRefFacY=47;
	
	$pdf->SetXY($posNumRefFacX+$adjX,$posNumRefFacY+$adjY); 
	$pdf->Cell(20,3,"REF",0,0,'L');
}
/************************************************/

/***********CLAVE CLIENTE SISTEMA*****************/
$posCodCliX=35;
$posCodCliY=47;

$pdf->SetXY($posCodCliX+$adjX,$posCodCliY+$adjY); 
$pdf->Cell(35,3,$dt_catcli['cod_cli'],0,0,'L');
/************************************************/

/***************NOMBRE CLIENTE*******************/
$posNomCliX=35;
$posNomCliY=51;

$pdf->SetXY($posNomCliX+$adjX,$posNomCliY+$adjY); 
$pdf->Cell(118,3,trim($dt_catcli['ap_pat_cli'].' '.$dt_catcli['ap_mat_cli'].' '.$dt_catcli['nom_cli']),0,0,'L');
/************************************************/

/************DIRECCION CLIENTE*******************/
$posDirCliX=35;
$posDirCliY=57;
$leyDir="";
if(trim($dt_bascps['entre_calle'])!="" || trim($dt_bascps['y_calle'])!=""){
	$leyDir=trim("ENTRE ".$dt_bascps['entre_calle']." Y ".$dt_bascps['y_calle'].", ");

}
$pdf->SetXY($posDirCliX+$adjX,$posDirCliY+$adjY);
$direcCli=trim($dt_bascps['calle'].' '.$dt_bascps['no_ext'].' '.$dt_bascps['no_int'].' COL. '.$dt_coloni['des_colonia']);
(strlen($direcCli)<=68)?($jump="\n"):($jump=""); 
$pdf->MultiCell(118,3,"$direcCli $jump".trim($leyDir)."C.P. ".$dt_bascps['cod_pos']." ".$dt_delmun['des_delmun']." ".$dt_paises['des_pais'].", ".$dt_estado['des_estado'],0,'L');
/************************************************/

/***************R.F.C. CLIENTE*******************/
$posRfcCliX=35;
$posRfcCliY=67;

$pdf->SetXY($posRfcCliX+$adjX,$posRfcCliY+$adjY); 
$pdf->Cell(118,3,trim($dt_catcli['rfc_cli']),0,0,'L');
/************************************************/

/*******************PACIENTE*********************/
$posNomPacX=35;
$posNomPacY=71;

$pdf->SetXY($posNomPacX+$adjX,$posNomPacY+$adjY); 
if(!$dt_factur['es_glo'] && count($auxArrFolFac)<=1)
	$nomPac=$dt_pememaSum['nomCliAlt'];
else
	$nomPac="V A R I O S";
$pdf->Cell(118,3,trim($nomPac),0,0,'L');
/************************************************/

/******************CONDICIONES*******************/
$posConFacX=160;
$posConFacY=75;

$pdf->SetXY($posConFacX+$adjX,$posConFacY+$adjY); 
if(trim($dt_factur['con_cre'])=="R") $condiciones="CREDITO ".$dt_bascpt['dia_cred']." DIAS";
elseif(trim($dt_factur['con_cre'])=="C") $condiciones="CONTADO";
elseif(trim($dt_factur['con_cre'])=="W"){
	$condiciones="REFACTURACION";
	($dt_facturFacAnt['conCre']=="C")?($condiciones="CONTADO"):($condiciones="CREDITO ".$dt_bascpt['dia_cred']." DIAS");
}
$pdf->Cell(40,3,$condiciones,0,0,'L');
/************************************************/

/**********************************D E T A L L E***********************************/
if(!$dt_factur['es_glo']){
	@$sq_factud=mysqli_query($con ,"select SUM(dgfactud.subtotal) as subtotal,SUM(dgfactud.total_cd) as total_cd,SUM(dgfactud.can_ref) as can_ref,SUM(des) as impDes, dgfactud.nparte1, IF('".$dt_factur['imp_aux_des']."'='1',dgfactud.aux_des,dginvent.np_desc1) as np_desc1 from dgfactud LEFT JOIN dginvent ON(dginvent.nparte1=dgfactud.nparte1) where dgfactud.cons_fac = '".$dt_factur['fol_fac']."' and total_cd>0 group by dgfactud.nparte1");
}else{
	$arrFolFac=explode(",",$dt_pememaSum['folSel']);
	/*for($i=0;$i<count($arrFolFac);$i++){
		$arrFolFac[$i]."<br>";
	}*/
	$leyDet="NOTAS DE VENTA CORRESPONDIENTE AL \n".whatDay($dt_factur['fec_fac']).", ".chfecha($dt_factur['fec_fac'],'Y-m-d','d de M de Y')."\nSEGUN FOLIOS DEL ".$arrFolFac[0]." AL ".$arrFolFac[(count($arrFolFac)-1)]."\nESTUDIOS VARIOS DE LABORATORIO Y GABINETE";
	@$sq_factud=mysqli_query($con ,"select ROUND(SUM(dgfactud.subtotal),2) as subtotal,ROUND(SUM(dgfactud.total_cd),2) as total_cd,'1' as can_ref,SUM(des) as impDes, dgfactud.nparte1, '$leyDet' as np_desc1 from dgfactud LEFT JOIN dginvent ON(dginvent.nparte1=dgfactud.nparte1) where dgfactud.cons_fac = '".$dt_factur['fol_fac']."' and total_cd>0 group by dgfactud.cons_fac");
}
$pdf->SetXY(9+$adjX,93+$adjY);
$pdf->SetWidths(array(15,2,125,3,26,2,24));
$pdf->SetDrawColor(255,255,255);
$pdf->SetAligns(array('R','C','L','C','R','C','R'));
$impTotFac=0; $totDes=0;
if($bIVA){
	if(dateCmp($dt_pememaSum['fecVen'],'2010-01-01')<0   && $dt_factur['con_cre']=='W')
		$dt_tasiva=mysqli_fetch_array(mysqli_query($con ,"SELECT * FROM dxtasiva WHERE cve_iva='3'"));	
	elseif 
		$dt_tasiva=mysqli_fetch_array(mysqli_query($con ,"SELECT * FROM dxtasiva WHERE cve_iva='1'"));
}else{      
	$dt_tasiva['porc_iva']=0;
}
while(@$dt_factud=mysqli_fetch_array($sq_factud)){
	$pdf->SetX(9+$adjX);
	(!$dt_factur['es_glo'])?($impDes=round($dt_factud['impDes']/(1+$dt_tasiva['porc_iva']/100),2)):($impDes=0);
	$impDetFac=round(($dt_factud['total_cd']/(1+$dt_tasiva['porc_iva']/100))+$impDes,2);
	/*if($bIVA) $impDetFac=($dt_factud['total_cd']/(1+$dt_tasiva['porc_iva']))+$impDes;
	else      $impDetFac=$dt_factud['total_cd']+$impDes;*/
	$preUni=round($impDetFac/$dt_factud['can_ref'],2);	
	$pdf->row(array($dt_factud['can_ref'],
				'',
				$dt_factud['np_desc1'],
				'',
				number_format($preUni,2, '.', ','),
				'',
				number_format($impDetFac, 2, '.', ',')
		));
	$numRowDet += 1;
	$impTotFac +=round($impDetFac,2);
	$totDes +=round($impDes,2);
}
/**********************************************************************************/

/*******************************LEYENDA SI REFACTURACION***************************/
if($dt_factur['con_cre']=="W"  && $leyRefFac){
	if($dt_facturFacAnt['esGlo']=='1') $laGlo="GLOBAL"; else $laGlo="";
	$leyRefFac="INCLUIDO EN LA FACTURA $laGlo $dt_facturFacAnt['tipFac']$dt_facturFacAnt['numFac'] DEL ".chfecha($dt_facturFacAnt['fecFac'],'Y-m-d','d de M de Y');
}else{
	$leyRefFac="";
}
/**********************************************************************************/

/**********************************FOLIOS DE FACTURA*******************************/
if(!$dt_factur['es_glo']){
	if($totDes>0){
		$posDesFacX=9; $posDesFacY=190; 
		$pdf->SetXY($posDesFacX+$adjX,$posDesFacY+$adjY);
		$pdf->Cell(25,3,"Descuento de:",0,0,'L');
		$pdf->Cell(20,3,number_format($totDes,2,'.',',')."-",0,0,'L');
	}
	$posLeyFolFacX=9; $posLeyFolFacY=195; 
	$pdf->SetXY($posLeyFolFacX+$adjX,$posLeyFolFacY+$adjY);$pdf->Cell(16,3,"Folio(s):",0,0,'L');
		
	$posFolFacX=25; $posFolFacY=195; 
	$pdf->SetXY($posFolFacX+$adjX,$posFolFacY+$adjY); $pdf->MultiCell(180,3,$dt_pememaSum['folSel']."\n".strtoupper($leyRefFac),0,'L');
}
/**********************************************************************************/

$subTot=round($impTotFac-$totDes,2);

$pdf->SetXY(175+$adjX,220+$adjY); $pdf->Cell(31,5,number_format($subTot, 2, '.', ','),0,1,'R');
$pdf->SetXY(175+$adjX,230+$adjY); 
$pdf->Cell(5,4,number_format($dt_tasiva['porc_iva'],0,'','')."%",0,0,'L');
$pdf->Cell(26,4,number_format(($dt_factur['tot_ven']-$subTot), 2, '.', ','),0,1,'R');
$pdf->SetXY(175+$adjX,240+$adjY); $pdf->Cell(31,4,number_format($dt_factur['tot_ven'], 2, '.', ','),0,1,'R');

include("DF10000.php");
$can=number_format($dt_factur['tot_ven'],2,'.','');
$parTot=explode(".","$can");
$pre_let=num2letras(number_format($parTot[0], 2, '.', ''));
$pdf->SetXY(40+$adjX,228+$adjY);
$pdf->Cell(110,5,"PAGADO EN UNA SOLA EXHIBICION",0,0,'L');

/***************************IMPORTE CON LETRA********************************/
$pdf->SetXY(40+$adjX,240+$adjY);
$pdf->Cell(110,5,"Importe Con Letra:",0,0,'L');

$pdf->SetXY(40+$adjX,245+$adjY);
$pdf->MultiCell(110,5,"(".$pre_let.' PESOS '."$parTot[1]".'/100 M.N.'.")",0,'C');
$pdf->SetX(40+$adjX);
$pdf->Cell(110,5,"\"EFECTOS FISCALES AL PAGO\"",0,0,'C');
/****************************************************************************/
//if(!$_POST['imp_fac_cop']){
	//$pdf->AutoPrint(true);
	$pdf-> SendToDefaultPrinter(false);
	//$pdf->AutoPrint(true);
	//$pdf->AutoPrint(true);		
//}
/**********************ACTUALIZA DVREDOCL Y DGFACTUR************************/
mysqli_query($con ,"UPDATE dgfactur SET iva_ven='".number_format($dt_factur['tot_ven']-$subTot,2,'.','')."',sub_ven='".number_format($subTot, 2, '.', '')."',tot_ven='".number_format($dt_factur['tot_ven'],2,'.','')."' WHERE fol_fac='".$_REQUEST['bot']."'");
mysqli_query($con ,"UPDATE dvredocl SET iva_tot='".number_format($dt_factur['tot_ven']-$subTot,2,'.','')."',sub_tot='".number_format($subTot, 2, '.', '')."',tot_ven='".number_format($dt_factur['tot_ven'],2,'.','')."' WHERE tip_mov='C' AND codigo='".$dt_bascps['coldigo']."' AND num_doc='".$dt_factur['num_fac']."'");
mysqli_query($con ,"UPDATE dvredocd SET sub_tot='".number_format($subTot, 2, '.', '')."' WHERE tip_mov='C' AND codigo='".$dt_bascps['coldigo']."' AND num_doc='".$dt_factur['num_fac']."'");

/***************************************************************************/	
$pdf->Output("FACTURA $dt_factur['tip_fac']$dt_factur['num_fac'].pdf",'I');
?>