<?php
include_once('../../../php/sessionStart.php');
include_once('../../../php/db/dbExec.php');
include_once('../../../php/functions.php');
include_once('../../../php/timezone.php');
include_once('../../../php/privileges.php');
include_once('../../../php/maxExecTime.php');
include_once('../ws/COFIDI/wsExec.php');
include_once('../ws/COFIDI/wsFormatsXML.php');

$bitForm = "fel1090";
$bitMod = "fel";
$empCod = $_SESSION['empCod'];
$empConso = $_SESSION['empConso'];
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);

switch ($_POST['action']) {
	case 'consultar':
		echo consultar();
		break;

	case 'consultarCta':
		echo consultarCta();
		break;

	case 'consultarCliencc':
		echo consultarCliencc();
		break;

	case 'consultarCiemes':
		echo consultarCiemes();
		break;

	case 'generarPartida':
		echo generarPartida();
		break;

	case 'guardar':
		echo guardar();
		break;

	case 'imprimir':
		echo imprimir();
		break;
}

function consultar() {
	global $empCod, $usuNom;

	$tipoPol='010';

	$priv = new privileges();
	if (!$priv->consult($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorConsult());
	}

	$func = new functions();

	$selTipoCod=$_POST['selTipoCod'];
	$txtSerie=$_POST['txtSerie'];
	$numNum=$_POST['numNum'];

	# QUERYS
	$sIva_ven = "SELECT
					i.*,
					c.ciem_stat 
				  FROM iva_ven i 
				  LEFT JOIN ciemes c ON c.ciem_mes=MONTH(i.ivav_fec) AND c.ciem_ano=YEAR(i.ivav_fec) AND c.ciem_emp='$empCod'
				  WHERE ivav_emp='$empCod' AND ivav_serie='$txtSerie' AND ivav_num='$numNum'";

	$sPoli_det = "SELECT * FROM poli_det WHERE pold_emp='$empCod' AND pold_tipo='$tipoPol' AND pold_tipoi='$txtSerie' AND pold_num='$numNum'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sIva_ven, "iva_ven");
	$resp["poli_det"] = $db->sFetchAll($sPoli_det);
	$db->close();

	$func = new functions();
	return $func->jsonEncodeArrayEach($resp, array("iva_ven", "poli_det"));
}

function consultarCta() {
	global $empCod;

	$priv = new privileges();
	if (!$priv->consult($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorConsult());
	}

	$txtCod=utf8_decode($_POST['txtCod']);

	# QUERYS
	$sCuentas = "SELECT c.*, TRIM(cta) AS cta, TRIM(cta_nom) AS cta_nom
				FROM cuentas c WHERE cta='$txtCod' AND cta_emp='$empCod'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sCuentas, "cuentas");
	$db->close();

	$func = new functions();
	return $func->jsonEncodeArray($resp, "cuentas");
}

function consultarCliencc() {
	global $empCod;

	$priv = new privileges();
	if (!$priv->consult($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorConsult());
	}

	# QUERYS
	$sClien = "SELECT *, TRIM(cli_cod) AS cli_cod, TRIM(cli_nomfac) AS cli_nomfac FROM cliencc WHERE cli_emp='$empCod' AND cli_stat='A' ORDER BY cli_cod ASC";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp["cliencc"] = $db->sFetchAll($sClien);
	$db->close();

	$func = new functions();
	return $func->jsonEncodeArray($resp, "cliencc");
}

function consultarCiemes() {
	global $empCod;

	$priv = new privileges();
	if (!$priv->consult($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorConsult());
	}

	$func = new functions();
	$numAno=$_POST["numAno"];
	$selMesCod=$_POST["selMesCod"];

	# QUERYS
	$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$numAno AND ciem_mes=$selMesCod";

	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sCiemes, "ciemes");
	$db->close();

	return json_encode($resp);
}

function generarPartida() {
	global $empCod;

	$priv = new privileges();
	if (!$priv->consult($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorConsult());
	}

	$numIva=$_POST['numIva'];
	$deduTot=$_POST['deduTot'];
	$numRet=$_POST['numRet'];
	$numReti=$_POST['numReti'];
	$numVen=$_POST['numVen'];
	$numServ=$_POST['numServ'];
	$numExport=$_POST['numExport'];

	# QUERYS
	function sCuentas($cta) {
		global $empCod;
		return "SELECT TRIM(cta) AS cta, TRIM(cta_nom) AS cta_nom
				FROM cuentas c WHERE cta='$cta' AND cta_emp='$empCod'";
	}
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp["ctaIva"] = ($numIva==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtaiv"]));
	$resp["ctaComb"] = ($deduTot==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtacomb"]));
	$resp["ctaRet"] = ($numRet==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtarisr"]));
	$resp["ctaReti"] = ($numReti==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtariva"]));
	$resp["ctaVen"] = ($numVen==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtaven"]));
	$resp["ctaServ"] = ($numServ==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtaserv"]));
	$resp["ctaExport"] = ($numExport==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtaexport"]));
	$resp["ctaCaj"] = $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtacaj"]));
	$db->close();

	$func = new functions();
	return $func->jsonEncodeArrayEach($resp, array('ctaIva', 'ctaComb', 'ctaRet', 'ctaReti', 'ctaCaj', 'ctaVen', 'ctaServ', 'ctaExport'));
}

function guardar() {
	global $empCod, $usuNom, $empConso, $bitMod, $bitForm, $numTcam, $dtFec, $selTipoCod, $tipoPol, $db;

	$priv = new privileges();
	if (!$priv->modify($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorModify());
	}

	$func = new functions();

	$numAno = $_POST["numAno"];
	$selMesCod = $_POST["selMesCod"];
	$numTcam = $_POST['numTcam'];
	$dtFec = $_POST['dtFec'];
	$selTipoCod = $_POST['selTipoCod'];

	$jsonFac=json_decode($_POST['tblFac']);
	$tipoPol='010';

	$_SESSION['tempFacturas'] = array();
	$arrayError = array();

	# QUERYS PARA UN REGISTRO
	$sFacturas = "SELECT MAX(fact_idinterno)+1 AS IDInterno FROM facturas";

	function sCliencc($cod){
		global $empCod;
		return "SELECT 
					*,
					TRIM(cli_nit) AS cli_nit,
					TRIM(cli_dir) AS cli_dir,
					TRIM(cli_tel) AS cli_tel,
					TRIM(cli_ven) AS cli_ven,
					TRIM(cli_serv) AS cli_serv,
					TRIM(cli_piedefac) AS cli_piedefac,
					TRIM(cli_codpos) AS cli_codpos,
					TRIM(cli_muni) AS cli_muni,
					TRIM(cli_depto) AS cli_depto
				FROM cliencc WHERE cli_emp='$empCod' AND cli_cod='$cod'";
	}

	function iFacturas($Batch, $Serial, $DocumentGUID, $transac, $tot, $codp, $nit, $nom, $dir, $tel, $dcre, $tcam, $fpag, $obs, $retsn, $retisn, $stat, $vencod, $lugare, $envio, $pedido, $orden, $bodsal, $pcomi, $contrato){
		global $empCod, $usuNom, $dtFec, $selTipoCod;
		return "INSERT INTO facturas(fact_documentguid,fact_emp,fact_tipo,fact_num,fact_transac,fact_fec,fact_tot,fact_codp,fact_nit,fact_nom,fact_dir,fact_tel,fact_dcre,fact_tcam,fact_fpag,fact_obs,fact_retsn,fact_retisn,fact_stat,fact_vend,fact_ulcam,fact_lugare,fact_envio,fact_pedido,fact_orden,fact_bodsal,fact_pcomi,fact_contrato,fact_fel) VALUES ('$DocumentGUID','$empCod','$Batch',$Serial,$transac,'$dtFec','$tot','$codp','$nit','$nom','$dir','$tel',$dcre,'$tcam','$fpag','$obs','$retsn','$retisn','$stat','$vencod','$usuNom','$lugare','$envio','$pedido','$orden','$bodsal','$pcomi','$contrato','$selTipoCod')";
	}

	function iFact_det($IDInterno, $transac, $Batch, $num, $codcorr, $cod, $desc, $desci, $med, $unimed, $cant, $preu, $cosu, $sub, $descu, $descuv, $tot, $autoriza, $codp, $nit, $vend, $bodsal, $exensn){
		global $empCod, $dtFec;
		return "INSERT INTO fact_det(factd_idinterno,factd_emp,factd_transac,factd_tipo,factd_num,factd_fec,factd_codcorr,factd_cod,factd_desc,factd_desci,factd_med,factd_unimed,factd_cant,factd_preu,factd_cosu,factd_sub,factd_descu,factd_descuv,factd_tot,factd_autoriza,factd_codp,factd_nit,factd_vend,factd_bodsal,factd_exensn) VALUES ('$IDInterno','$empCod','$transac','$Batch','$num','$dtFec','$codcorr','$cod','$desc','$desc','$med','$unimed','$cant','$preu','$cosu','$sub','$descu','$descuv','$tot','$autoriza','$codp','$nit','$vend','$bodsal','$exensn')";
	}

	/*function sMeses($mes) {
		return "SELECT mes_nom FROM meses WHERE mes_cod=$mes";
	}*/

	function sPaises($pais) {
		return "SELECT pa_alfa2 FROM paises WHERE id=$pais";
	}

	function iIva_ven($num, $Batch, $nit, $tot, $sub, $iva, $nom, $tcam, $cod) {
		global $empCod, $usuNom, $dtFec;
		return "INSERT INTO iva_ven(ivav_emp,ivav_fec,ivav_num,ivav_tipo,ivav_nit,ivav_bien,ivav_serv,ivav_exp,ivav_tot,ivav_sub,ivav_exen,ivav_subb,ivav_subs,ivav_sube,ivav_iva,ivav_medi,ivav_vehi,ivav_noafe,ivav_subme,ivav_subve,ivav_subna,ivav_conso,ivav_comb,ivav_tfaco,ivav_subco,ivav_expre,ivav_suber,ivav_con,ivav_afe,ivav_vehia,ivav_ivave,ivav_ulcam,ivav_galos,ivav_galor,ivav_galod,ivav_vgals,ivav_vgalr,ivav_vgald,ivav_ret,ivav_reti,ivav_retsn,ivav_retisn,ivav_dedu,ivav_clin,ivav_stat,ivav_galon,ivav_srd,ivav_vgalo,ivav_tvehi,ivav_prens,ivav_facus,ivav_tcam,ivav_gtq,ivav_proco) 
		VALUES ('$empCod','$dtFec',$num,'$Batch','$nit',0,'$tot',0,'$tot','$sub',0,0,'$sub',0,'$iva',0,0,0,0,0,0,'$empCod',0,0,0,0,0,'','S',0,0,'$usuNom',0,0,0,0,0,0,0,0,'N','N',0,'$nom','',0,0,0,0,0,0,'$tcam',0,'$cod')";
	}

	function iDoctoscc($num, $Batch, $nit, $nom, $tot, $sub, $iva, $cod, $tcam, $dcre) {
		global $empCod, $usuNom, $dtFec;
		return "INSERT INTO doctoscc(dc_emp,dc_fec,dc_num,dc_tipo,dc_nit,dc_clien,dc_bien,dc_serv,dc_peque,dc_exp,dc_tot,dc_sub,dc_subb,dc_subs,dc_sube,dc_subp,dc_iva,dc_stat,dc_afe,dc_con,dc_noafe,dc_conso,dc_ulcam,dc_abo,dc_codp,dc_tcam,dc_totdif,dc_dc,dc_contab,dc_retsn,dc_retisn,dc_sal,dc_abot) VALUES ('$empCod','$dtFec',$num,'$Batch','$nit','$nom',0,'$tot',0,0,'$tot','$sub',0,'$sub',0,0,'$iva','','S','',0,'$empCod','$usuNom',0,'$cod','$tcam',0,$dcre,'','N','N','$tot',0)";
	}

	function iPolizas($num, $serie, $con, $nit) {
		global $empCod, $tipoPol, $usuNom, $dtFec;
		return "INSERT INTO polizas(pol_emp, pol_fec, pol_ban, pol_tipo, pol_num, pol_con, pol_stat, pol_tipoi, pol_nit, pol_ulcam) VALUES('$empCod','$dtFec',0,'$tipoPol',$num,'$con','','$serie','$nit','$usuNom')";
	}

	function sCuentas($cta) { 
		global $empCod;
		return "SELECT TRIM(cta_nom) AS cta_nom FROM cuentas WHERE cta_emp='$empCod' AND cta='$cta'";
	}

	function iTipov($cod, $nom) {
		return "INSERT INTO tipov(tv_cod, tv_nom, tv_impues, tv_pone, tv_abrev, tv_corr, tv_librosn, tv_fel) VALUES('$cod','$nom','N','P','',1,'S','')";
	}

	# QUERYS PARA VARIOS REGISTROS
	function iPoli_det($num, $serie, $nit, $jsonPol) {
		global $empCod, $dtFec, $tipoPol;
		$func = new functions();
		$r = "INSERT INTO poli_det (pold_emp, pold_fec, pold_ban, pold_tipo, pold_num, pold_tipoi, pold_nit, pold_cta, pold_ctan, pold_debe, pold_haber, pold_stat) VALUES ";
		foreach ($jsonPol as $obj) {
			$obj->cta = utf8_decode($obj->cta);
			$obj->ctaNom = utf8_decode($obj->ctaNom);
			$r = $r."('$empCod','$dtFec',0,'$tipoPol','$num','$serie','$nit','$obj->cta','$obj->ctaNom','$obj->debe','$obj->haber','')".$func->addValues($obj, $jsonPol);
		}
		return $r;
	}

	function dPoli_det($num, $serie) {
		global $empCod, $tipoPol;
		return "DELETE FROM poli_det WHERE pold_emp='$empCod' AND pold_tipo='$tipoPol' AND pold_num='$num' AND pold_tipoi='$serie'";
	}

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	foreach ($jsonFac as $obj) {
		$tot=$obj->totQ+$obj->totD;
		$obj->nom = utf8_decode($obj->nom);

		$sub = round(($tot/(($_SESSION['pIva']/100)+1)), 2);
		$iva = round((($tot/(($_SESSION['pIva']/100)+1))*($_SESSION['pIva']/100)), 2);
		/*$sub=round(($tot/(($_SESSION['pIva']/100)+1)),2);
		$iva=round(($tot-$sub),2);*/

		$haber = ($sub+$iva);
		if ($tot != $haber) {
			$sub += ($tot < $haber) ? ($tot-$haber) : ($haber-$tot);
		}

		if ($obj->tipo=="Q") {
			$totIva=$tot;
			$subIva=$sub;
			$ivaIva=$iva;
		} else {
			/*$totIva=round(($tot*$numTcam),2);
			$subIva=round(($totIva/(($_SESSION['pIva']/100)+1)),2);
			$ivaIva=round(($totIva-$subIva),2);*/

			$totIva=round($tot*$numTcam, 2);
			$subIva=round(($totIva/(($_SESSION['pIva']/100)+1)), 2);
			$ivaIva=round((($totIva/(($_SESSION['pIva']/100)+1))*($_SESSION['pIva']/100)), 2);


			$haberIva = ($subIva+$ivaIva);
			if ($totIva != $haberIva) {
				$subIva += ($totIva < $haberIva) ? ($totIva-$haberIva) : ($haberIva-$totIva);
			}
		}

		$faCliencc = $db->sFetchAssoc(sCliencc($obj->cod));

		$mesvencido=$faCliencc["cli_mesvencido"];
		$fins=$faCliencc["cli_fins"];
		$periodo=periodo($numAno, $selMesCod, $mesvencido, $fins);

		/*$fecini=date($numAno."-".$selMesCod."-01");
        $fecfin=date("d-m-Y", strtotime($fecini."- 1 days"));
        $diafin=date("d", strtotime($fecfin));
        $mesfin=date("n", strtotime($fecfin));
        $anofin=date("Y", strtotime($fecfin));
        $nmesfin=$db->sFetchAssoc(sMeses($mesfin))["mes_nom"];
		$periodo="Periodo Del 01 al ".$diafin." de ".$nmesfin." de ".$anofin;

		$faCliencc = $db->sFetchAssoc(sCliencc($obj->cod));

		$mesvencido=$faCliencc["cli_mesvencido"];
		$fins=$faCliencc["cli_fins"];
		$diafins=date("d", strtotime($fins));
		$mesfins=date("n", strtotime($fins));
		$anofins=date("Y", strtotime($fins));

		if ($mesvencido==0 && $mesfin==$mesfins && $anofin==$anofins) {
			if ($selMesCod==12) {
				$mesfin1=1;
				$anofin1=$numAno+1;
			} else {
				$mesfin1=$selMesCod+1;
				$anofin1=$numAno;
			}

			$fecini1=date($anofin1."-".$mesfin1."-01");
			$fecfin1=date("d-m-Y", strtotime($fecini1."- 1 days"));
			$diafin=date("d", strtotime($fecfin1));
			$nmesfin=$db->sFetchAssoc(sMeses($selMesCod))["mes_nom"];
			$anofina=$numAno;
			$diaini=$diafins;
			$nmesini=$db->sFetchAssoc(sMeses($mesfins))["mes_nom"];
			$anoini=$anofins;
			if ($anoini!=$anofina) {
				$periodo="Periodo Del ".$diaini." de ".$nmesini." de ".$anoini." al ".$diafin." de ".$nmesfin." de ".$anofina;
			} else {
				$periodo="Periodo Del ".$diaini." de ".$nmesini." al ".$diafin." de ".$nmesfin." de ".$anofina;
			}
		}
		if ($mesvencido==1 && $mesfin==$mesfins && $anofin==$anofins) {
			$diaini=$diafins;
			$fecini=date($numAno."-".$selMesCod."-01");
			$fecfin=date("d-m-Y", strtotime($fecini."- 1 days"));
			$diafin=date("d", strtotime($fecfin));
			$mesfin=date("n", strtotime($fecfin));
			$anofin=date("Y", strtotime($fecfin));

			$nmesfin=$db->sFetchAssoc(sMeses($mesfin))["mes_nom"];
			$periodo="Periodo Del ".$diaini." al ".$diafin." de ".$nmesfin." de ".$anofin;
		}
		if ($mesvencido==0 && ($mesfin!=$mesfins || $anofin!=$anofins)) {
			if ($selMesCod=12) {
				$mesfin1=1;
				$anofin1=$numAno+1;
			} else {
				$mesfin1=$selMesCod+1;
				$anofin1=$numAno;
			}
			$fecini1=date($anofin1."-".$mesfin1."-01");
			$fecfin1=date("d-m-Y", strtotime($fecini1."- 1 days"));
			$diafin=date("d", strtotime($fecfin1));
			$nmesfin=$db->sFetchAssoc(sMeses($selMesCod))["mes_nom"];
			$anofin=$numAno;
			$periodo="Periodo Del 01 al ".$diafin." de ".$nmesfin." de ".$anofin;
		}
		if ($mesvencido==1 && ($mesfin!=$mesfins || $anofin!=$anofins)) {
			$diaini=$diafins;
			$fecini=date($numAno."-".$selMesCod."-01");
			$fecfin=date("d-m-Y", strtotime($fecini."- 1 days"));
			$diafin=date("d", strtotime($fecfin));
			$mesfin=date("n", strtotime($fecfin));
			$anofin=date("Y", strtotime($fecfin));
			$nmesfin=$db->sFetchAssoc(sMeses($mesfin))["mes_nom"];
			$periodo="Periodo Del ".$diaini." al ".$diafin." de ".$nmesfin." de ".$anofin;
		}*/

		$pais = $db->sFetchAssoc(sPaises($faCliencc['cli_pais']))['pa_alfa2'];
		$dcre = $faCliencc["cli_dcre"];

		$wsFormatsXML = new wsFormatsXML();
		// Datos Generales
		$Tipo=$selTipoCod;
		$FechaHoraEmision = $dtFec.'T'.date("H:i:s", STRTOTIME(date('h:i:sa'))).'-06:00';
		$CodigoMoneda = ($obj->tipo=='Q') ? 'GTQ' : 'USD';

		// Frases
		$arrayFrases = array(
			array('TipoFrase'=>1, 'CodigoEscenario'=>1)
		);

		// Items
		$arrayItems = array(
			array('NumeroLinea'=>1, 'BienOServicio'=>'S', 'Cantidad'=>1, 'UnidadMedida'=>'UND', 'Descripcion'=>$faCliencc["cli_serv"], 'PrecioUnitario'=>$tot, 'Precio'=>$tot, 'Descuento'=>0, 'NombreCorto'=>'IVA', 'CodigoUnidadGravable'=>1, 'MontoGravable'=>$sub, 'MontoImpuesto'=>$iva, 'Total'=>$tot),
			array('NumeroLinea'=>2, 'BienOServicio'=>'S', 'Cantidad'=>0, 'UnidadMedida'=>'UND', 'Descripcion'=>$periodo, 'PrecioUnitario'=>0, 'Precio'=>0, 'Descuento'=>0, 'NombreCorto'=>'IVA', 'CodigoUnidadGravable'=>1, 'MontoGravable'=>0, 'MontoImpuesto'=>0, 'Total'=>0)
		);
		if (!empty($faCliencc["cli_piedefac"])) {
			// Para quitar el 0D00 (Hexadecimal) porque nos da error y no deja guardar en WS
			$pieSAT = str_replace("\r", "", $faCliencc["cli_piedefac"]);

			$pieSATArray = explode("\n", $pieSAT);

			$NumeroLinea = 3;
			foreach ($pieSATArray as $linea) {
				array_push($arrayItems, array('NumeroLinea'=>$NumeroLinea, 'BienOServicio'=>'S', 'Cantidad'=>0, 'UnidadMedida'=>'UND', 'Descripcion'=>$linea, 'PrecioUnitario'=>0, 'Precio'=>0, 'Descuento'=>0, 'NombreCorto'=>'IVA', 'CodigoUnidadGravable'=>1, 'MontoGravable'=>0, 'MontoImpuesto'=>0, 'Total'=>0));
				$NumeroLinea++;
			}
		}

		// Totales
		$arrayImpuestos = array(
			array('NombreCorto'=>'IVA', 'TotalMontoImpuesto'=>$iva)
		);

		// Complementos
		$arrayComplementos = array();
		if ($Tipo == "FCAM") {
			array_push($arrayComplementos, array('IDComplemento'=>$Tipo, 'NumeroAbono'=>1, 'FechaVencimiento'=>date("Y-m-d",strtotime($dtFec."+ $dcre days")), 'MontoAbono'=>$tot));
		}

		// Para quitar comillas porque nos da error y no deja guardar en WS
		$nomWS = str_replace('"', '', utf8_decode($obj->nom));
		$DatosGenerales = $wsFormatsXML->DatosGenerales($Tipo, $FechaHoraEmision, $CodigoMoneda);
		$Receptor = $wsFormatsXML->Receptor($faCliencc['cli_nit'], $nomWS, '', $faCliencc['cli_codpos'], $faCliencc['cli_muni'], $faCliencc['cli_depto'], $pais);

		$FEL = $wsFormatsXML->GTDocumentoIni()
			.$DatosGenerales
			.$wsFormatsXML->Emisor()
			.$Receptor
			.$wsFormatsXML->Frases($arrayFrases)
			.$wsFormatsXML->Items($arrayItems)
			.$wsFormatsXML->Totales($tot, $arrayImpuestos)
			.$wsFormatsXML->Complementos($arrayComplementos)
			.$wsFormatsXML->GTDocumentoFin();
		$base64FEL = base64_encode($FEL);
		//echo $FEL." ------ base64 ---- ".$base64FEL;

		$wsCOFIDI = new wsCOFIDIExec();
		$IDInterno = $db->sFetchAssoc($sFacturas)['IDInterno'];
		foreach ($wsCOFIDI->iEx($base64FEL, $IDInterno) as $Body) {
			// Si se guardó en la factura en la SAT (Result = TRUE o FALSE) entonces guardar en nuestra DB
			$result = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Result;
			if ($func->stringToBool((string)$result)) {
				$Batch = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Identifier->Batch;
				$Serial = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Identifier->Serial;
				$DocumentGUID = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Identifier->DocumentGUID;

				$resp = $db->iEx(iFacturas($Batch, $Serial, $DocumentGUID, $IDInterno, $tot, $obj->cod, $faCliencc["cli_nit"], $obj->nom, $faCliencc["cli_dir"], $faCliencc["cli_tel"], $faCliencc["cli_dcre"], (($obj->tipo=="Q") ? 1 : $numTcam), (($faCliencc["cli_dcre"]=="0") ? 1 : 2), "", "N", "N", "", $faCliencc["cli_ven"], "", "", "", "", "", "0.00", 0));
				$db->iEx(iFact_det($IDInterno, $IDInterno, $Batch, $Serial, 0, $obj->cod, $faCliencc["cli_serv"], $faCliencc["cli_serv"], "", "", 1, $tot, 0, $tot, 0, 0, $tot, 0, $obj->cod, $faCliencc["cli_nit"], $faCliencc["cli_ven"], "", "N"));
				$db->iEx(iFact_det($IDInterno, $IDInterno, $Batch, $Serial, 0, "", $periodo, $periodo, "", "", 0, 0, 0, 0, 0, 0, 0, 0, $obj->cod, $faCliencc["cli_nit"], $faCliencc["cli_ven"], "", "N"));
				if (!empty($faCliencc["cli_piedefac"])) {
					$db->iEx(iFact_det($IDInterno, $IDInterno, $Batch, $Serial, 0, "", $faCliencc["cli_piedefac"], $faCliencc["cli_piedefac"], "", "", 0, 0, 0, 0, 0, 0, 0, 0, $obj->cod, $faCliencc["cli_nit"], $faCliencc["cli_ven"], "", "N"));
				}
				$db->iEx(iIva_ven($Serial, $Batch, $faCliencc["cli_nit"], $totIva, $subIva, $ivaIva, $obj->nom, 1, $obj->cod));
				$db->iEx(iDoctoscc($Serial, $Batch, $faCliencc["cli_nit"], $obj->nom, $tot, $sub, $iva, $obj->cod, ($obj->tipo=="Q") ? 1 : $numTcam, $faCliencc["cli_dcre"]));
				$db->iEx(iPolizas($Serial, $Batch, "Facturacion Cliente: ".$obj->nom." Codigo ".$obj->cod." ".$periodo, $faCliencc["cli_nit"]));
				// Meter las cuentas a un JSON para insertar en un solo query
				$ctaCli = $faCliencc["cli_cta"];
				$ctaIva = (string)$_SESSION["empCtaiv"];
				$ctaServ = "41102001";
				$ctaNomCli = $db->sFetchAssoc(sCuentas($ctaCli))["cta_nom"];
				$ctaNomIva = $db->sFetchAssoc(sCuentas($ctaIva))["cta_nom"];
				$ctaNomServ = $db->sFetchAssoc(sCuentas($ctaServ))["cta_nom"];
				$jsonPol=json_decode('[{"cta":"'.$ctaCli.'","ctaNom":"'.$ctaNomCli.'","debe":"'.$totIva.'","haber":"0.00"},
					{"cta":"'.$ctaIva.'","ctaNom":"'.$ctaNomIva.'","debe":"0.00","haber":"'.$ivaIva.'"},
					{"cta":"'.$ctaServ.'","ctaNom":"'.$ctaNomServ.'","debe":"0.00","haber":"'.$subIva.'"}]');
				$db->iEx(iPoli_det($Serial, $Batch, $faCliencc["cli_nit"], $jsonPol));

				$db->iEx(iTipov($Batch, $Batch));

				array_push($_SESSION['tempFacturas'], array('serie'=>''.$Batch, 'num'=>''.$Serial, 'nom'=>$obj->nom, 'tot'=>$tot, 'tipo'=>$obj->tipo));
				
				/*$resp["insert"] = iTipov($Batch, $Batch);
				$resp["tipo"]=$obj->tipo;
				$resp["tcam"]=($obj->tipo=="Q") ? 1 : $numTcam;*/

				$IDInterno = $db->sFetchAssoc($sFacturas)['IDInterno'];
			} else {
				$Code = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Code;
				$Description = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Description;

				array_push($arrayError, array("Code"=>''.$Code, "cod"=>$obj->cod, "Description"=>''.$Description));
				//$resp = $db->rErrorPublic($Code." - ".$obj->cod, $Description);
				/*$resp["error"] = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Code;
				$resp["errorDesc"] = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Description;*/
			}
		}
	}

	// Por si no se pudo guardar la factura de algún cliente
	$sizeError = sizeof($arrayError);
	$title = "";
	$text = "";
	if ($sizeError != 0) {
		if ($sizeError == 1) {
			$title = $arrayError[0]["Code"]." - ".$arrayError[0]["cod"];
			$text = $arrayError[0]["Description"];
		} else {
			$title = 'en Varios Registros';
			$text .='<table style="margin: 0 auto"><tr><td width="70">Error</td><td width="70">Código</td><td class="d-none">Description</td></tr>';
			foreach($arrayError as $row) {
				$text .="<tr><td class='text-center'>{$row['Code']}</td><td class='text-center'>{$row['cod']}</td><td class='d-none'>{$row['Description']}</td></tr>";
			}
			$text .='</table>';
		}
		$resp = $db->rErrorPublic($title, $text);
	}

	$resp["print"] = (sizeof($_SESSION['tempFacturas']) != 0) ? true : false;

	$db->close();

	return json_encode($resp);
}


function imprimir() {
	global $empCod, $db;

	$priv = new privileges();
	if (!$priv->consult($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorConsult());
	}

	$numAno = $_POST["numAno"];
	$selMesCod = $_POST["selMesCod"];
	$jsonFac=json_decode($_POST['tblFac']);
	
	# QUERYS
	$sTipov = "SELECT TRIM(tv_nom) AS tv_nom FROM tipov WHERE tv_cod='{$_POST["selTipoCod"]}'";

	function sCliencc($cod){
		global $empCod;
		return "SELECT 
					*,
					TRIM(cli_nit) AS cli_nit,
					TRIM(cli_dir) AS cli_dir,
					TRIM(cli_tel) AS cli_tel,
					TRIM(cli_ven) AS cli_ven,
					TRIM(cli_serv) AS cli_serv,
					TRIM(cli_piedefac) AS cli_piedefac,
					TRIM(cli_codpos) AS cli_codpos,
					TRIM(cli_muni) AS cli_muni,
					TRIM(cli_depto) AS cli_depto
				FROM cliencc WHERE cli_emp='$empCod' AND cli_cod='$cod'";
	}
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$fa["tipov"] = $db->sFetchAssoc($sTipov);

	$_SESSION["printFacturas"] = array();
	foreach ($jsonFac as $obj) {
		$tot=$obj->totQ+$obj->totD;

		$fa["cliencc"] = $db->sFetchAssoc(sCliencc($obj->cod));

		$mesvencido=$fa["cliencc"]["cli_mesvencido"];
		$fins=$fa["cliencc"]["cli_fins"];
		$periodo=periodo($numAno, $selMesCod, $mesvencido, $fins);

		$arrayItems = array(
						array('cod'=>$obj->cod, 'descrip'=>$fa["cliencc"]["cli_serv"], 'cant'=>'1.00', 'preu'=>$tot, 'sub'=>$tot),
						array('cod'=>'', 'descrip'=>periodo($numAno, $selMesCod, $mesvencido, $fins), 'cant'=>0, 'preu'=>0, 'sub'=>0),
						array('cod'=>'', 'descrip'=>$fa["cliencc"]["cli_piedefac"], 'cant'=>0, 'preu'=>0, 'sub'=>0)
					  );

		array_push($_SESSION["printFacturas"], array(
			'tipoNomFEL'=>$fa["tipov"]["tv_nom"],
			'tipoFEL'	=>$_POST["selTipoCod"],
			'nom'		=>$obj->nom,
			'nit'		=>$fa["cliencc"]["cli_nit"],
			'dir'		=>$fa["cliencc"]["cli_dir"],
			'fec'		=>$_POST["dtFec"],
			'tcam'		=>$obj->tipo,
			'tot'		=>$tot,
			'totLetras'	=>$obj->totLetras,
			'det' 		=>$arrayItems
		));
	}
	$db->close();
	return "";
}

function sMeses($mes) {
	return "SELECT mes_nom FROM meses WHERE mes_cod=$mes";
}

function periodo($numAno, $selMesCod, $mesvencido, $fins) {
	global $db;

	$fecini=date($numAno."-".$selMesCod."-01");
    $fecfin=date("d-m-Y", strtotime($fecini."- 1 days"));
    $diafin=date("d", strtotime($fecfin));
    $mesfin=date("n", strtotime($fecfin));
    $anofin=date("Y", strtotime($fecfin));
    $nmesfin=$db->sFetchAssoc(sMeses($mesfin))["mes_nom"];
	$periodo="Periodo Del 01 al ".$diafin." de ".$nmesfin." de ".$anofin;

	$diafins=date("d", strtotime($fins));
	$mesfins=date("n", strtotime($fins));
	$anofins=date("Y", strtotime($fins));

	if ($mesvencido==0 && $mesfin==$mesfins && $anofin==$anofins) {
		if ($selMesCod==12) {
			$mesfin1=1;
			$anofin1=$numAno+1;
		} else {
			$mesfin1=$selMesCod+1;
			$anofin1=$numAno;
		}

		$fecini1=date($anofin1."-".$mesfin1."-01");
		$fecfin1=date("d-m-Y", strtotime($fecini1."- 1 days"));
		$diafin=date("d", strtotime($fecfin1));
		$nmesfin=$db->sFetchAssoc(sMeses($selMesCod))["mes_nom"];
		$anofina=$numAno;
		$diaini=$diafins;
		$nmesini=$db->sFetchAssoc(sMeses($mesfins))["mes_nom"];
		$anoini=$anofins;
		if ($anoini!=$anofina) {
			$periodo="Periodo Del ".$diaini." de ".$nmesini." de ".$anoini." al ".$diafin." de ".$nmesfin." de ".$anofina;
		} else {
			$periodo="Periodo Del ".$diaini." de ".$nmesini." al ".$diafin." de ".$nmesfin." de ".$anofina;
		}
	}
	if ($mesvencido==1 && $mesfin==$mesfins && $anofin==$anofins) {
		$diaini=$diafins;
		$fecini=date($numAno."-".$selMesCod."-01");
		$fecfin=date("d-m-Y", strtotime($fecini."- 1 days"));
		$diafin=date("d", strtotime($fecfin));
		$mesfin=date("n", strtotime($fecfin));
		$anofin=date("Y", strtotime($fecfin));

		$nmesfin=$db->sFetchAssoc(sMeses($mesfin))["mes_nom"];
		$periodo="Periodo Del ".$diaini." al ".$diafin." de ".$nmesfin." de ".$anofin;
	}
	if ($mesvencido==0 && ($mesfin!=$mesfins || $anofin!=$anofins)) {
		if ($selMesCod==12) {
			$mesfin1=1;
			$anofin1=$numAno+1;
		} else {
			$mesfin1=$selMesCod+1;
			$anofin1=$numAno;
		}
		$fecini1=date($anofin1."-".$mesfin1."-01");
		$fecfin1=date("d-m-Y", strtotime($fecini1."- 1 days"));
		$diafin=date("d", strtotime($fecfin1));
		$nmesfin=$db->sFetchAssoc(sMeses($selMesCod))["mes_nom"];
		$anofin=$numAno;
		$periodo="Periodo Del 01 al ".$diafin." de ".$nmesfin." de ".$anofin;
	}
	if ($mesvencido==1 && ($mesfin!=$mesfins || $anofin!=$anofins)) {
		$diaini=$diafins;
		$fecini=date($numAno."-".$selMesCod."-01");
		$fecfin=date("d-m-Y", strtotime($fecini."- 1 days"));
		$diafin=date("d", strtotime($fecfin));
		$mesfin=date("n", strtotime($fecfin));
		$anofin=date("Y", strtotime($fecfin));
		$nmesfin=$db->sFetchAssoc(sMeses($mesfin))["mes_nom"];
		$periodo="Periodo Del ".$diaini." al ".$diafin." de ".$nmesfin." de ".$anofin;
	}
	return $periodo;
}
?>