<?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 = "fel1010";
$bitMod = "fel";
$empCod = $_SESSION['empCod'];
$empConso = $_SESSION['empConso'];
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);

$tipoPol='010';

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

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

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

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

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

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

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

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

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

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

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

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

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

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

function consultar() {
	global $empCod, $pCaja, $usuCod;

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

	$func = new functions();

	# QUERYS
	$sCaja = "SELECT c.*, 
				TRIM(c.caj_nomt) AS caj_nomt, 
				TRIM(c.caj_dirt) AS caj_dirt,
				TRIM(c.caj_telt) AS caj_telt,
				TRIM(c.caj_mailt) AS caj_mailt,
				TRIM(c.caj_leyen1) AS caj_leyen1,
				TRIM(c.caj_leyen2) AS caj_leyen2
				FROM caja c
				WHERE caj_emp='$empCod' AND caj_cod='$pCaja'";

	$sUsu = "SELECT TRIM(u.usu_vend) AS usu_vend
				FROM usuarios u
				WHERE usu_cod='$usuCod'";

	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sCaja, "caja");
	//$resp = $db->sEx($sUsu, "usuarios");
	$resp["usuarios"] = $db->sFetchAssoc($sUsu);

	$db->close();

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


function consultarArtic() {
	global $empCod;

	$func = new functions();

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

	# QUERYS
	$sArtic = "SELECT a.*, 
				TRIM(a.art_cod) AS art_cod, 
				TRIM(a.art_desc) AS art_desc, 
				TRIM(a.art_desd) AS art_desd,
				TRIM(ctaCos.cta_nom) AS art_ctaCosnom,
				TRIM(ctaInv.cta_nom) AS art_ctaInvnom,
				TRIM(ctaVen.cta_nom) AS art_ctaVennom,
				TRIM(p.pro_nom) AS art_provnom,
				TRIM(um.um_nom) AS um_nom
				FROM artic a
				LEFT JOIN cuentas ctaCos ON a.art_emp = ctaCos.cta_emp AND a.art_ctaCos=ctaCos.cta
				LEFT JOIN cuentas ctaInv ON a.art_emp = ctaInv.cta_emp AND a.art_ctaInv=ctaInv.cta
				LEFT JOIN cuentas ctaVen ON a.art_emp = ctaVen.cta_emp AND a.art_ctaven=ctaVen.cta
				LEFT JOIN provcp p ON a.art_emp = p.pro_emp AND a.art_prov=p.pro_cod
				LEFT JOIN unimed um ON a.art_medi=um.um_cod
				WHERE a.art_emp='$empCod' AND a.art_cod='$txtCodd'";

	$sArticbarr = "SELECT a.*, 
				TRIM(a.art_cod) AS art_cod, 
				TRIM(a.art_desc) AS art_desc, 
				TRIM(a.art_desd) AS art_desd,
				TRIM(ctaCos.cta_nom) AS art_ctaCosnom,
				TRIM(ctaInv.cta_nom) AS art_ctaInvnom,
				TRIM(ctaVen.cta_nom) AS art_ctaVennom,
				TRIM(p.pro_nom) AS art_provnom,
				TRIM(um.um_nom) AS um_nom,
				TRIM(cb.cb_cod) AS cb_cod,
				TRIM(cb.cb_barr) AS cb_barr 
				FROM artic a
				LEFT JOIN cuentas ctaCos ON a.art_emp = ctaCos.cta_emp AND a.art_ctaCos=ctaCos.cta
				LEFT JOIN cuentas ctaInv ON a.art_emp = ctaInv.cta_emp AND a.art_ctaInv=ctaInv.cta
				LEFT JOIN cuentas ctaVen ON a.art_emp = ctaVen.cta_emp AND a.art_ctaven=ctaVen.cta
				LEFT JOIN provcp p ON a.art_emp = p.pro_emp AND a.art_prov=p.pro_cod
				LEFT JOIN unimed um ON a.art_medi=um.um_cod
				LEFT JOIN cod_barr cb ON a.art_emp=cb.cb_emp AND a.art_cod=cb.cb_cod 
				WHERE a.art_emp='$empCod' AND cb.cb_barr='$txtCodd'";


	function sExiart($codigo) { 
		global $empCod;
		return "SELECT e.*, TRIM(b.bod_nom) AS bod_nom
				FROM exiart e 
				LEFT JOIN bodegas b ON e.ea_emp=b.bod_emp AND e.ea_bod=b.bod_cod
				WHERE e.ea_emp='$empCod' AND e.ea_cod='$codigo'";
	}

	//$sCod_barr = "SELECT * FROM cod_barr WHERE cb_emp='$empCod' AND cb_cod='$txtCodd'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$codigo=$txtCodd;
	$resp = $db->sEx($sArtic, "artic");
	$select["artic"] = $db->query($sArtic);
	if ($db->numRows($select["artic"]) == 0) {
		$resp = $db->sEx($sArticbarr, "artic");
		$codigo=$resp["artic"]["art_cod"];
	}
	$resp["exiart"] = $db->sFetchAll(sExiart($codigo));
	$resp["imgArtic"] = "imgArticulos/$empCod"."_".$func->imgCharacters($codigo).".jpeg?".rand(1,9999);
	$db->close();

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

function consultarDepo() {
	global $empCod;

	$func = new functions();

	$selBanDepo=utf8_decode($_POST['selBanDepo']);
	$numNdepo=utf8_decode($_POST['numNdepo']);

	# QUERYS
	$sFacturas = "SELECT fact_emp, fact_fec, 
				TRIM(fac.fact_serie) AS fact_serie, 
				TRIM(fac.fact_num) AS fact_num,
				TRIM(fac.fact_nom) AS fact_nom, 
				TRIM(fac.fact_alumno) AS fact_alumno
				FROM facturas fac
				WHERE fact_emp='$empCod' AND fact_depoban='$selBanDepo' AND fact_deponum='$numNdepo' AND fact_tot>0";

	//$sCod_barr = "SELECT * FROM cod_barr WHERE cb_emp='$empCod' AND cb_cod='$txtCodd'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sFacturas, "facturas");
	$select["facturas"] = $db->query($sFacturas);
	$db->close();

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

function consultarExist() {
	global $empCod;

	$func = new functions();

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

	# QUERYS
	$sExiart = "SELECT ea_exist, ea_exicon FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$txtCod' AND ea_bod='$selBod'";
	
	function uExiart($cod, $bod, $existact) {
		global $empCod;
		return "UPDATE exiart SET ea_exist=$existact WHERE ea_emp='$empCod' AND ea_cod='$cod' AND ea_bod='$bod'";
	}
	# PARA REVISION DE EXISTENCIAS
	function sMoviie0($codd, $bodega) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_entra) AS mov_sentra
	            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$bodega' GROUP BY '$empCod','$bodega','$codd'";
	}

	function sMoviis0($codd, $bodega) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_sale) AS mov_ssale
	            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$bodega' GROUP BY '$empCod','$bodega','$codd'";
	}

	# EJECUCION DE QUERYS
	$db = new dbExec();
    # Aqui se recalculan existencias
    # Para revisar las existencias normales
	$select["moviie0"] = $db->query(sMoviie0($txtCod,$selBod));
	$fetchAssoc["moviie0"] = $db->fetchAssoc($select["moviie0"]);
	if ($db->numRows($select["moviie0"]) == 0) {
	   $sumentro=0;
    } else {
      $sumentro=$fetchAssoc["moviie0"]["mov_sentra"];
    }
	$select["moviis0"] = $db->query(sMoviis0($txtCod,$selBod));
	$fetchAssoc["moviis0"] = $db->fetchAssoc($select["moviis0"]);
	if ($db->numRows($select["moviis0"]) == 0) {
	   $sumsalio=0;
    } else {
       $sumsalio=$fetchAssoc["moviis0"]["mov_ssale"];
	}	               
    $exisactu=$sumentro-$sumsalio;
	$db->uEx(uExiart($txtCod,$selBod,$exisactu));

	$resp = $db->sEx($sExiart, "exiart");
	$db->close();

	return json_encode($resp);
}


function consultarCorrtipov() {
	global $empCod;

	$func = new functions();

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

	# QUERYS
	$sCorrtipov = "SELECT ctv_num FROM corrtipov WHERE ctv_emp='$empCod' AND ctv_tipo='$selTipoCod'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();

	$select["corrtipov"] = $db->query($sCorrtipov);
	if ($db->numRows($select["corrtipov"])>0) {
		$numFac = ($db->fetchAssoc($select["corrtipov"])["ctv_num"]);
	} else {
		$numFac = 1;
		$r["corrtipov"] = $db->query("INSERT INTO corrtipov (ctv_emp, ctv_tipo, ctv_num) VALUES('$empCod', '$selTipoCod', $numFac);");
	}

	$resp["corrtipov"]["ctv_num"] = $numFac;
	$db->close();

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

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());
	}

	$txtCliCod = $_POST["txtCliCod"];

	# QUERYS
	$sCliencc = "SELECT *, 
					TRIM(cli_cod) AS cli_cod, 
					TRIM(cli_nom) AS cli_nom,
					TRIM(cli_nomfac) AS cli_nomfac,
					TRIM(cli_nit) AS cli_nit,
					TRIM(cli_dir) AS cli_dir,
					TRIM(cli_ven) AS cli_ven,
					TRIM(cli_cta) AS cli_cta,
					TRIM(cli_tel) AS cli_tel
				FROM cliencc WHERE cli_emp='$empCod' AND cli_cod='$txtCliCod'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp["cliencc"] = $db->sFetchAssoc($sCliencc);
	$db->close();

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

function consultarClienIva() {
	global $empCod;
	$txtNit=utf8_decode($_POST['txtNit']);

	# QUERYS
	$sClien = "SELECT *, TRIM(cli_nom) AS cli_nom, TRIM(cli_dir) AS cli_dir, TRIM(cli_tel) AS cli_tel FROM clien WHERE cli_nit='$txtNit'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sClien, "clien");
	$db->close();

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

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 consultarAuto() {
	global $empCod, $usuNom;
	$txtPassdescu=$_POST['txtPassdescu'];
	$dtHoy = date("Y-m-d");
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));
	$Descrip = "  Autorizacion utilizada por: ".$usuNom." ".$dtGrabado;

	# QUERYS
	$sPassauto = "SELECT * FROM autoriza WHERE aut_num='$txtPassdescu' and aut_stat!='B'";

	$uPassauto = "UPDATE autoriza SET aut_stat='B',aut_fecutil='$dtHoy',aut_desc=CONCAT(aut_desc, '$Descrip') WHERE aut_num='$txtPassdescu'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sPassauto, "autoriza");

	$select["autoriza1"] = $db->query($sPassauto);
	if ($db->numRows($select["autoriza1"]) > 0) {
		$db->uEx($uPassauto);
	}	
	$db->close();

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

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

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

	$func = new functions();

	$selGrupo=$_POST['selGrupo'];

	# QUERYS
	$sBolsas = "SELECT bol.*, TRIM(art.art_medi) AS art_medi, art.art_pre1 AS art_pre1, TRIM(um.um_nom) AS um_nom, TRIM(bol_desc) AS bol_desc, ea_exist
		FROM bolsas bol 
		LEFT JOIN artic art ON art.art_emp=bol.bol_emp AND art.art_cod=bol.bol_cod
		LEFT JOIN unimed um ON um.um_cod=art.art_medi
		LEFT JOIN exiart ea ON ea.ea_emp=bol.bol_emp AND ea.ea_cod=bol.bol_cod AND ea_bod='0010'
		WHERE bol_emp='$empCod' AND bol_gru='$selGrupo'";


	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sBolsas, "bolsas");
	$resp["bolsas"] = $db->sFetchAll($sBolsas);
	$db->close();

	$func = new functions();
	//return $func->jsonEncodeArray($resp, array('abonos', 'poli_det', 'abo_det'));
	return $func->jsonEncodeArray($resp, 'bolsas');
}

function generarPartida() {
	global $empCod, $totales;

	$numTcam = $_POST["numTcam"];
	$crFpag = $_POST["crFpag"];
	$crExp = $_POST["crExp"];
	$crRet = $_POST["crRet"];
	$crReti = $_POST["crReti"];
	$selTipoImpues = $_POST["selTipoImpues"];
	$tot=$_POST["tot"];
	$cliCta="1120101";
	$tarjCta="1120208";
	$depoCta="1110202";
	//$_POST['cliCta'];
	$jsonDet=json_decode($_POST['tblDet'], true);

	$func = new functions();
	# 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'";
	}

	function sArtic($cod) {
		global $empCod;
		return "SELECT
					art_cosp,
					TRIM(art_ctacos) AS art_ctacos, 
					TRIM(art_ctainv) AS art_ctainv, 
					TRIM(art_ctaven) AS art_ctaven
				FROM artic WHERE art_cod='$cod' AND art_emp='$empCod'";
	}

	// !!!!! IMPORTANTE !!!!!
	// SE COPIA LA FUNCION iDetalle() QUE ESTA EN LA FUNCION guardar() Y SE QUITA LO QUE NO SE NECESITA, 
	// ESTO SE HACE PARA QUE LOS CALCULOS DE LA PARTIDA SEAN IGUALES A LOS QUE SE GUARDAN
	function iDetalle($tot, $expsn, $jsonDet) {
		global $totales;
		// VARIABLES PARA SEPARAR BIENES, SERVICIOS Y EXPORTACION
		$hayBienes=false;
		$totales["bienes"]["exentoS"]=0;
		$totales["bienes"]["exentoN"]=0;
		$totales["servicios"]["exentoS"]=0;
		$totales["servicios"]["exentoN"]=0;
		$totales["exportacion"]=0;

		foreach ($jsonDet as $obj) {
			// OPERACIONES PARA SERPARAR EL TOTAL DE BIENES Y SERVICIOS
			if ($obj->bienserd=='S') {
				$hayServicios = true;
				($obj->exensnd=='N') ? $totales["servicios"]["exentoN"]+=$obj->totd : $totales["servicios"]["exentoS"]+=$obj->totd;
			} else {
				$hayBienes = true;
				($obj->exensnd=='N') ? $totales["bienes"]["exentoN"]+=$obj->totd : $totales["bienes"]["exentoS"]+=$obj->totd;
			}
		}

		// SI ES EXPORTACIÓN, ENTONCES PONER CERO EN BIENES Y SERVICIOS - PONER EL TOTAL EN EXPORTACION PARA LOS CALCULOS
		if ($expsn=='S') {
			$totales["bienes"]["exentoS"]=0;
			$totales["bienes"]["exentoN"]=0;
			$totales["servicios"]["exentoS"]=0;
			$totales["servicios"]["exentoN"]=0;
			$totales["exportacion"]=$tot;
		}
	}
	
	// PARA HACER LOS CALCULOS
	iDetalle($tot, $crExp, json_decode($_POST['tblDet']));
	$val = calculos($tot, $crRet, $crReti, $crExp, $selTipoImpues, $numTcam, 1);

	$resp["tot"] = round($val["tot"],2);
	$resp["ret"] = round($val["ret"],2);
	$resp["reti"] = round($val["reti"],2);
	$resp["iva"] = round($val["iva"],2);
	$resp["sub"] = round($val["sub"],2);
	
	# EJECUCION DE QUERYS
	$db = new dbExec();

	$resp["ctaInv"]=array();
	$resp["ctaCos"]=array();
	$resp["ctaVen"]=array();
	$j=0;
	foreach ($jsonDet as $rec) {
		// COSTO Y CUENTAS DEL ARTICULO
		$fa["artic"] = $db->sFetchAssoc(sArtic($rec["codd"]));
		$totCosp = ($fa["artic"]["art_cosp"]*$rec["cantd"])*$numTcam;
		$ctaInv = $fa["artic"]["art_ctainv"];
		$ctaCos = $fa["artic"]["art_ctacos"];
		$ctaVen = $fa["artic"]["art_ctaven"];

		// PARA ACUMULAR LAS CUENTAS DE INVENTARIO
		$i = $func->multiSearch($resp["ctaInv"], array('cta' => (string)$ctaInv));
		if ($i >= 0) {
			$resp["ctaInv"][$i]["cta_valor"] += $totCosp;
		} else {
			$fa["ctaInv"] = $db->sFetchAssoc(sCuentas((string)$ctaInv));
			array_push($resp["ctaInv"], array("cta"=>$ctaInv,"cta_nom"=>$fa["ctaInv"]["cta_nom"],"cta_valor"=>$totCosp));
		}

		// PARA ACUMULAR LAS CUENTAS DE COSTOS
		$i = $func->multiSearch($resp["ctaCos"], array('cta' => (string)$ctaCos));
		if ($i >= 0) {
			$resp["ctaCos"][$i]["cta_valor"] += $totCosp;
		} else {
			$fa["ctaCos"] = $db->sFetchAssoc(sCuentas((string)$ctaCos));
		    array_push($resp["ctaCos"], array("cta"=>$ctaCos,"cta_nom"=>$fa["ctaCos"]["cta_nom"],"cta_valor"=>$totCosp));
		}

		// VENTAS=SUBTOTAL <O> VENTAS=TOTAL, DEPENDIENTO SI ES EXPORTACION O EXENTO
		$rec["totd"] = round($rec["totd"]*$numTcam, 2);
		if ($rec["exensnd"]=='N' && $crExp=='N') {
			$rec["totd"] /= (($_SESSION['pIva']/100)+1);
		}
		// PARA ACUMULAR LAS CUENTAS DE VENTAS
		$i = $func->multiSearch($resp["ctaVen"], array('cta' => (string)$ctaVen));
		if ($i >= 0) {
			$resp["ctaVen"][$i]["cta_valor"] += $rec["totd"];
		} else {
			$fa["ctaVen"] = $db->sFetchAssoc(sCuentas((string)$ctaVen));
		    array_push($resp["ctaVen"], array("cta"=>$ctaVen,"cta_nom"=>$fa["ctaVen"]["cta_nom"],"cta_valor"=>$rec["totd"], "cta_exensn"=>$rec["exensnd"]));
		}
		unset($jsonDet[$j]);
		$j++;
	}
    $ctaven=$_SESSION['empCtaven'];
    $ctacontado="1110101";
	$resp["ctaRet"] = ($resp["ret"]==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtarisr"]));
	$resp["ctaReti"] = ($resp["reti"]==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtariva"]));
	$resp["ctaIva"] = ($resp["iva"]==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$_SESSION["empCtaiv"]));
	$resp["ctaCaja"] = $db->sFetchAssoc(sCuentas((string)$ctacontado));
	$resp["ctaCli"] = $db->sFetchAssoc(sCuentas((string)$cliCta));
	$resp["ctaTarj"] = $db->sFetchAssoc(sCuentas((string)$tarjCta));
	$resp["ctaDepo"] = $db->sFetchAssoc(sCuentas((string)$depoCta));
	$resp["ctaVen"] = ($resp["sub"]==0) ? 0 : $db->sFetchAssoc(sCuentas((string)$ctaven));

	$db->close();

	return $func->jsonEncodeArray($resp, "ctaInv");
}

function guardar() {
	global $empCod, $usuNom, $empConso, $bitMod, $bitForm, $numTcam, $dtFec, $selTipoCod, $selTipoAbrev, $selCodasiste, $tipoPol, $tipoInv, $db, $func, $totales, $dtGrabado, $numInv, $numTotfp, $numEfec, $numDepo, $numTarj, $numCred, $txtNit,$numdoc,$seriedoc, $txtAlumno, $selBanDepo, $numNdepo, $crNitCui;

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

	$func = new functions();

	if ($empCod=="4") {
		$_SESSION["empEstablecimiento"] = "1";
	}

	$tipoPol="010";
	$DocumentGUID = '';
	$selTipoCod = $_POST["selTipoCod"];
	$selTipoAbrev = $_POST["selTipoAbrev"];
	$selTipoLibrosn = $_POST["selTipoLibrosn"];
	$selTipoImpues = $_POST["selTipoImpues"];
	$selCodasiste = $_POST["selCodasiste"];
	$dtFec = $_POST["dtFec"];
	$numAno=date("Y", strtotime($dtFec));
	$numMes=date("n", strtotime($dtFec));

	$selBodSalCod = $_POST["selBodSalCod"];
	$numTcam = $_POST["numTcam"];
	$txtCliCod = utf8_decode($_POST["txtCliCod"]);
	$txtNomFac = utf8_decode($_POST["txtNomFac"]);
	$txtNit = utf8_decode($_POST["txtNit"]);
	$txtDir = utf8_decode($_POST["txtDir"]);
	$txtTel = utf8_decode($_POST["txtTel"]);
	$txtAlumno = utf8_decode($_POST["txtAlumno"]);
	$numDcre = $_POST["numDcre"];
	$selVendCod = $_POST["selVendCod"];
	$crFpag = $_POST["crFpag"];
	$crExp = 'N';
	//$_POST["crExp"];
	$crRet = $_POST["crRet"];
	$crReti = $_POST["crReti"];
	$crNitCui = $_POST["crNitCui"];
	$tot=$_POST["tot"];
	$numTotfp=(empty($_POST['numTotfp'])) ? 0 : $_POST['numTotfp'];
	$numEfec=(empty($_POST['numEfec'])) ? 0 : $_POST['numEfec'];
	$numDepo=(empty($_POST['numDepo'])) ? 0 : $_POST['numDepo'];
	$numTarj=(empty($_POST['numTarj'])) ? 0 : $_POST['numTarj'];
	$numCred=(empty($_POST['numCred'])) ? 0 : $_POST['numCred'];
	$selBanDepo = $_POST["selBanDepo"];
	$numNdepo=(empty($_POST['numNdepo'])) ? 0 : $_POST['numNdepo'];
	$valq=(empty($_POST['valq'])) ? 0 : $_POST['valq'];
	$txtObs = "";
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));

	$jsonDet=json_decode($_POST['tblDet']);
	$jsonPol=json_decode($_POST['tblPol']);
	$crTcam="L";

	$tipoInv=$_POST["selTipoRelatd"];


	$arrayError = array();


	$sCorrTipov = "SELECT ctv_num FROM corrtipov WHERE ctv_emp='$empCod' AND ctv_tipo='$selTipoCod'";

	$sCliIva = "SELECT * FROM clien WHERE cli_nit='$txtNit'";

	$uCliIva = "UPDATE clien SET cli_nom='$txtNomFac', cli_dir='$txtDir', cli_tel='$txtTel' WHERE cli_nit='$txtNit'";

	$iCliIva = "INSERT INTO clien (cli_nit, cli_nom, cli_dir, cli_tel) VALUES('$txtNit','$txtNomFac','$txtDir','$txtTel')";

	$sTABLES = "SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_NAME='facturas' AND TABLE_SCHEMA='{$_SESSION['nombredb']}'";

/*	$sFacturas = "SELECT f.fact_idinterno, d.ds_num, f.fact_fec FROM facturas f
				  LEFT JOIN doctoss d ON d.ds_emp=f.fact_emp AND d.ds_ftipo=f.fact_tipo AND d.ds_fserie=f.fact_serie AND d.ds_fnum=f.fact_num
				  WHERE fact_emp='$empCod' AND fact_tipo='$selTipoCod' AND fact_serie='$selTipoAbrev' AND fact_num=$numNum";  */

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

	function iuFacturas($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, $expsn, $FechaHoraEmision){
		global $empCod, $usuNom, $dtFec, $selTipoCod, $numTotfp, $numEfec, $numDepo, $numTarj, $numCred, $dtGrabado, $func, $txtAlumno, $selBanDepo, $numNdepo, $crNitCui;
//		if ($func->stringToBool($_POST['nuevo'])) {
			return "INSERT INTO facturas(fact_documentguid,fact_emp,fact_tipo,fact_serie,fact_num,fact_transac,fact_fec,fact_tot,fact_codp,fact_nit,fact_nom,fact_dir,fact_tel,fact_alumno,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,fact_expsn,fact_efec,fact_depo,fact_tarj,fact_cred,fact_guardado,fact_tipoform,fact_depoban,fact_deponum,fact_tipodocid) VALUES ('$DocumentGUID','$empCod','$selTipoCod','$Batch',$Serial,$transac,'$dtFec','$tot','$codp','$nit','$nom','$dir','$tel','$txtAlumno',$dcre,'$tcam','$fpag','$obs','$retsn','$retisn','$stat','$vencod','$usuNom','$lugare','$envio','$pedido','$orden','$bodsal','$pcomi','$contrato','','$expsn','$numEfec','$numDepo','$numTarj','$numCred','$FechaHoraEmision','B','$selBanDepo','$numNdepo','$crNitCui')";
/*		} else {
			return "UPDATE facturas SET fact_fec='$dtFec',fact_tot='$tot',fact_codp='$codp',fact_nit='$nit',fact_nom='$nom',fact_dir='$dir',fact_tel='$tel',fact_dcre=$dcre,fact_tcam='$tcam',fact_fpag='$fpag',fact_obs='$obs',fact_retsn='$retsn',fact_retisn='$retisn',fact_stat='$stat',fact_vend='$vencod',fact_ulcam='$usuNom',fact_lugare='$lugare',fact_envio='$envio',fact_pedido='$pedido',fact_orden='$orden',fact_bodsal='$bodsal',fact_pcomi='$pcomi',fact_contrato='$contrato',fact_expsn='$expsn' WHERE fact_documentguid='$DocumentGUID' AND fact_emp='$empCod' AND fact_tipo='$selTipoCod' AND fact_serie='$Batch' AND fact_num=$Serial";
		}   */
	}

	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 iuIva_ven($num, $Batch, $nit, $nom, $retsn, $retisn, $bien, $serv, $exen, $exp, $obs, $subb, $subs, $sube, $ret, $reti, $sub, $iva, $tot, $tcam) {
		global $empCod, $usuNom, $dtFec, $selTipoCod, $empConso, $bitMod, $func;
//		if ($func->stringToBool($_POST['nuevo'])) {
			return "INSERT INTO iva_ven (ivav_emp, ivav_serie, ivav_num, ivav_nit, ivav_tipo, ivav_clin, ivav_fec, ivav_retsn, ivav_retisn, ivav_afe, ivav_bien, ivav_serv, ivav_exen, ivav_exp, ivav_expre, ivav_medi, ivav_noafe, ivav_vehi, ivav_vehia, ivav_tvehi, ivav_tfaco, ivav_galos, ivav_galor, ivav_galod, ivav_comb, ivav_con, ivav_subb, ivav_subs, ivav_subco, ivav_subve, ivav_sube, ivav_suber, ivav_subna, ivav_subme, ivav_ret, ivav_reti, ivav_sub, ivav_iva, ivav_tot, ivav_dedu, ivav_ulcam, ivav_conso, ivav_mod) VALUES ('$empCod', '$Batch', '$num', '$nit', '$selTipoCod', '$nom', '$dtFec', '$retsn', '$retisn', 'S', '$bien', '$serv', '$exen', '$exp', 0, 0, 0, 0, 0, '', 0, 0, 0, 0, 0, '$obs', '$subb', '$subs', 0, 0, '$sube', 0, 0, 0, $ret, $reti, '$sub', '$iva', '$tot', 0,'$usuNom', '$empConso', '$bitMod')";
/*		} else {
			return "UPDATE iva_ven SET ivav_nit='$nit', ivav_clin='$nom', ivav_fec='$dtFec', ivav_retsn='$retsn', ivav_retisn='$retisn', ivav_bien='$bien', ivav_serv='$serv', ivav_exen='$exen', ivav_exp='$exp', ivav_con='$obs', ivav_subb='$subb', ivav_subs='$subs', ivav_sube='$sube', ivav_ret='$ret', ivav_reti='$reti', ivav_sub='$sub', ivav_iva='$iva', ivav_tot='$tot', ivav_ulcam='$usuNom', ivav_conso='$empConso', ivav_mod='$bitMod' WHERE ivav_emp='$empCod' AND ivav_serie='$Batch' AND ivav_num=$num AND ivav_tipo='$selTipoCod'";
		}   */
	}

	function sDoctoscc($num, $Batch) {
		global $empCod, $selTipoCod;
		return "SELECT dc_num FROM doctoscc WHERE dc_emp='$empCod' AND dc_serie='$Batch' AND dc_num=$num AND dc_tipo='$selTipoCod'";
	}

	function iuDoctoscc($num, $Batch, $nit, $nom, $retsn, $retisn, $bien, $serv, $exen, $exp, $obs, $subb, $subs, $sube, $ret, $reti, $sub, $iva, $tot, $tcam, $cod) {
		global $empCod, $usuNom, $dtFec, $selTipoCod, $empConso, $bitMod, $func, $db;
		if ($db->numRows($db->query(sDoctoscc($num, $Batch)))==0) {
			return "INSERT INTO doctoscc (dc_emp, dc_serie, dc_num, dc_codp, dc_nit, dc_tipo, dc_clien, dc_fec, dc_fecp, dc_retsn, dc_retisn, dc_afe, dc_bien, dc_serv, dc_exen, dc_exp, dc_expre, dc_medi, dc_noafe, dc_tfaco, dc_galos, dc_galor, dc_galod, dc_comb, dc_con, dc_subb, dc_subs, dc_subco, dc_sube, dc_suber, dc_subna, dc_subme, dc_ret, dc_reti, dc_sub, dc_iva, dc_tot, dc_dedu, dc_tcam, dc_ulcam, dc_conso, dc_mod) VALUES ('$empCod', '$Batch', '$num','$cod', '$nit', '$selTipoCod', '$nom', '$dtFec', '$dtFec', '$retsn', '$retisn', 'S', '$bien', '$serv', '$exen', '$exp', 0, 0, 0, 0, 0, 0, 0, 0, '$obs', '$subb', '$subs', 0, '$sube', 0, 0, 0, $ret, $reti, '$sub', '$iva', '$tot', 0, '$tcam', '$usuNom', '$empConso','$bitMod')";
		} else {
			return "UPDATE doctoscc SET dc_codp='$cod', dc_nit='$nit', dc_clien='$nom', dc_fec='$dtFec', dc_fecp='$dtFec', dc_retsn='$retsn', dc_retisn='$retisn', dc_bien='$bien', dc_serv='$serv', dc_exen='$exen', dc_exp='$exp', dc_con='$obs', dc_subb='$subb', dc_subs='$subs', dc_sube='$sube', dc_ret='$ret', dc_reti='$reti', dc_sub='$sub', dc_iva='$iva', dc_tot='$tot', dc_tcam='$tcam', dc_ulcam='$usuNom', dc_conso='$empConso', dc_mod='$bitMod' WHERE dc_emp='$empCod' AND dc_serie='$Batch' AND dc_num=$num AND dc_tipo='$selTipoCod'";
		}
	}

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

	function sCierres($cta, $numAnio, $numMes) { 
		global $empCod;
		return "SELECT * FROM cierres WHERE cie_emp='$empCod' AND cie_ano=$numAnio AND cie_mes=$numMes AND cie_cta='$cta'";
	}

	function uCierres($cta, $numAnio, $numMes, $mdebe, $mhaber) { 
		global $empCod, $usuNom;
		return "UPDATE cierres SET cie_mdebe=$mdebe, cie_mhaber=$mhaber, cie_ulcam='$usuNom' WHERE cie_emp='$empCod' AND cie_ano=$numAnio AND cie_mes=$numMes AND cie_cta='$cta'";
	}

	function iCierres($cta, $numAnio, $numMes, $mdebe, $mhaber) { 
		global $empCod, $usuNom;
		return "INSERT INTO cierres(cie_emp, cie_ano, cie_mes, cie_cta, cie_mdebe, cie_mhaber, cie_ulcam) VALUES('$empCod',$numAnio,$numMes,'$cta',$mdebe,$mhaber,'$usuNom')";	    
	}

	function sExiart($cod, $bod) {
		global $empCod;
		return "SELECT ea_exist FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$cod' AND ea_bod='$bod'";
	}

	function uExiart($cod, $bod, $existact) {
		global $empCod;
		return "UPDATE exiart SET ea_exist=$existact WHERE ea_emp='$empCod' AND ea_cod='$cod' AND ea_bod='$bod'";
	}

	function iExiart($cod, $bod) {
		global $empCod;
		return "INSERT INTO exiart(ea_emp,ea_cod,ea_bod,ea_exist) VALUES('$empCod','$cod','$bod',0)";
	}

	function iuDoctoss($num, $bodsal, $tcam, $obs, $tot, $codp, $nit, $nom, $dir, $vend, $Batch, $Serial, $hora) { 
		global $empCod, $tipoInv, $dtFec, $usuNom, $selTipoCod, $func;
//		if ($func->stringToBool($_POST['nuevo'])) {
			return "INSERT INTO doctoss(ds_emp,ds_tipo,ds_num,ds_fec,ds_fecapli,ds_bodsal,ds_tcam,ds_clicod,ds_clinit,ds_clinom,ds_clidir,ds_vencod,ds_ftipo,ds_fserie,ds_fnum,ds_hora,ds_obs,ds_total,ds_ulcam) VALUES ('$empCod','$tipoInv','$num','$dtFec','$dtFec','$bodsal','$tcam','$codp','$nit','$nom','$dir','$vend','$selTipoCod','$Batch',$Serial,'$hora','$obs','$tot','$usuNom')";
/*		} else {
			return "UPDATE doctoss SET ds_fec='$dtFec',ds_fecapli='$dtFec',ds_bodsal='$bodsal',ds_tcam='$tcam',ds_clicod='$codp',ds_clinit='$nit',ds_clinom='$nom',ds_clidir='$dir',ds_vencod='$vend',ds_ftipo='$selTipoCod',ds_fserie='$Batch',ds_fnum=$Serial,ds_hora='$hora',ds_obs='$obs',ds_total='$tot',ds_ulcam='$usuNom' WHERE ds_emp='$empCod' AND ds_tipo='$tipoInv' AND ds_num='$num'";
		}   */
	}

	function iFact_det($IDInterno,$transac,$Batch,$Serial,$autoriza,$codp,$nit,$vend,$bodsal,$tcam,$obs,$nom,$dir,$expsn,$tot,$cosp,$codd,$descd,$medid,$unimed,$cantd,$preud,$subd,$descud,$descuvd,$totd,$exensnd,$bienserd) { 
		global $empCod, $tipoInv, $dtFec, $usuNom, $selTipoCod, $func, $totales, $numInv;
			return "INSERT INTO fact_det(factd_idinterno,factd_emp,factd_transac,factd_tipo,factd_serie,factd_num,factd_fec,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,factd_bienser) VALUES ('$IDInterno','$empCod','$transac','$selTipoCod','$Batch','$Serial','$dtFec','$codd','$descd','$descd','$medid','$unimed','$cantd','$preud','$cosp','$subd','$descud','$descuvd','$totd',0,'$codp','$nit','$vend','$bodsal','$exensnd','$bienserd')";
	}

	function iDocs_det($IDInterno, $transac, $Batch, $Serial, $autoriza, $codp, $nit, $vend, $bodsal, $tcam, $obs, $nom, $dir, $expsn, $tot, $existant, $existact,$cosp,$i,$codd,$descd,$medid,$unimed,$cantd,$preud,$subd,$descud,$descuvd,$totd,$exensnd,$bienserd) { 
		global $empCod, $tipoInv, $dtFec, $usuNom, $selTipoCod, $func, $totales, $numInv;
			return "INSERT INTO docs_det(dsd_emp,dsd_tipo,dsd_num,dsd_fec,dsd_fecapli,dsd_linea,dsd_cod,dsd_cant,dsd_cantcon,dsd_desc,dsd_descfac,dsd_med,dsd_unimed,dsd_unit,dsd_descu,dsd_descuv,dsd_monto,dsd_cosu,dsd_exiant,dsd_exipos,dsd_consig,dsd_autoriza,dsd_exensn) VALUES ('$empCod','$tipoInv','$Serial','$dtFec','$dtFec',$i,'$codd','$cantd',0,'$descd','$descd','$medid','$unimed','$preud','$descud','$descuvd','$totd','$cosp',$existant,$existact,'',0,'$exensnd')";
	}

	function iMovii($IDInterno, $transac, $Batch, $Serial, $autoriza, $codp, $nit, $vend, $bodsal, $tcam, $obs, $nom, $dir, $expsn, $tot, $cosp, $i, $codd, $descd, $medid, $unimed, $cantd, $preud, $subd, $descud, $descuvd, $totd, $exensnd, $bienserd) { 
		global $empCod, $tipoInv, $dtFec, $usuNom, $selTipoCod, $func, $totales, $numInv;
			return "INSERT INTO movii(mov_emp,mov_tipo,mov_num,mov_ftipo,mov_fserie,mov_fnum,mov_fec,mov_fecapli,mov_linea,mov_cod,mov_bodent,mov_bodsal,mov_entra,mov_sale,mov_entracon,mov_salecon,mov_cosu,mov_preu) VALUES ('$empCod','$tipoInv','$Serial','$selTipoCod','$Batch','$Serial','$dtFec','$dtFec',$i,'$codd','','$bodsal',0,'$cantd',0,0,'$cosp','$preud')";
	}

	function sArtic($cod) {
		global $empCod;
		return "SELECT art_cosp FROM artic WHERE art_cod='$cod' AND art_emp='$empCod'";
	}

	function sPolizas($num, $serie) {
		global $empCod, $tipoPol;
		return "SELECT pol_num FROM polizas WHERE pol_emp='$empCod' AND pol_tipo='$tipoPol' AND pol_num='$num' AND pol_tipoi='$serie'";
	}

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

	function uPolizas($num, $serie, $con, $nit) {
		global $empCod, $tipoPol, $usuNom, $dtFec, $dtGrabado;
		return "UPDATE polizas SET pol_con='$con', pol_fec='$dtFec', pol_nit='$nit', pol_ulcam='$usuNom', pol_grabado='$dtGrabado' WHERE pol_emp='$empCod' AND pol_tipo='$tipoPol' AND pol_num='$num' AND pol_tipoi='$serie'";
	}

	# 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'";
	}

	# PARA REVISION DE EXISTENCIAS
	function sMoviie0($codd, $bodega) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_entra) AS mov_sentra
	            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$bodega' GROUP BY '$empCod','$bodega','$codd'";
	}

	function sMoviis0($codd, $bodega) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_sale) AS mov_ssale
	            FROM movii WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$bodega' GROUP BY '$empCod','$bodega','$codd'";
	}

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$faCliencc = $db->sFetchAssoc(sCliencc($txtCliCod));

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

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

	if ($crTcam=="L") {
		$totIva=$tot;
		$subIva=$sub;
		$ivaIva=$iva;
	} else {
		$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);
		}
	}                         */

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

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

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

	$sub=0;
	$iva=0;
	$totIva=0;
	$subIva=0;
	$ivaIva=0;
	$haberIva=0;
	// Items
	$arrayItems = array();
	$i = 1;
	foreach ($jsonDet as $obj) {
		$descd = utf8_decode($obj->descd);
		$descWS = str_replace('"', '', utf8_decode($descd));
		$descWS = str_replace('&', '&amp;', $descWS);
		$descWS = str_replace('Ñ', 'N', $descWS);
		$descWS = str_replace('ñ', 'n', $descWS);

		$totItem = $obj->totd;
		if ($obj->exensnd=='N') {
			$subItem = round(($totItem/(($_SESSION['pIva']/100)+1)), 5);
			$ivaItem = round((($totItem/(($_SESSION['pIva']/100)+1))*($_SESSION['pIva']/100)), 5);
		} else {
			$subItem = 0;
			$ivaItem = 0;
		}
		$haberItem = ($subItem+$ivaItem);
		if ($totItem != $haberItem) {
			$subItem += ($totItem < $haberItem) ? ($totItem-$haberItem) : ($haberItem-$totItem);
		}

		$sub += $subItem;
		$iva += $ivaItem;
		$totIva += $totItem;
		$subIva += $subItem;
		$ivaIva += $ivaItem;

		array_push($arrayItems, array('NumeroLinea'=>$i, 'BienOServicio'=>'B', 'Cantidad'=>$obj->cantd, 'UnidadMedida'=>'UND', 'Descripcion'=>$descWS, 'PrecioUnitario'=>$obj->preud, 'Precio'=>$obj->subd, 'Descuento'=>$obj->descuvd, 'NombreCorto'=>'IVA', 'CodigoUnidadGravable'=>1, 'MontoGravable'=>$subItem, 'MontoImpuesto'=>$ivaItem, 'Total'=>$obj->totd));
		$i++;
		// Revisa si hay registro de existencia, si no hay lo inicia
		$select["exiartr"] = $db->query(sExiart($obj->codd, $selBodSalCod));
		if ($db->numRows($select["exiartr"]) == 0) {
	    	$db->iEx(iExiart($obj->codd, $selBodSalCod));
		}
	}

	// 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));
	}
	if ($Tipo == "FESP") {
		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($txtNomFac));
	$nomWS = str_replace('&', '&amp;', $nomWS);
	$DatosGenerales = $wsFormatsXML->DatosGenerales($Tipo, $FechaHoraEmision, $CodigoMoneda);
	if ($crNitCui=="C") {
		$Receptor = $wsFormatsXML->ReceptorCui($txtNit, $nomWS, $txtDir, $faCliencc['cli_codpos'], $faCliencc['cli_muni'], $faCliencc['cli_depto'], $pais);
	} else {
		$Receptor = $wsFormatsXML->Receptor($txtNit, $nomWS, $txtDir, $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($sTABLES)['AUTO_INCREMENT'];
	$Identificador='PRO-'.str_pad($IDInterno,9,"0",STR_PAD_LEFT);
	foreach ($wsCOFIDI->iEx($base64FEL, $Identificador) 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;

//			$Batch = 'qwer';
//			$Serial = 1111;
//			$DocumentGUID = 'qwer-1111';

// aqui iria el detalle y los demas datos

//			$select["corrtipov"] = $db->query($sCorrTipov);
//			$fetchAssoc["corrtipov"] = $db->fetchAssoc($select["corrtipov"]);
		    $numNum=$Serial;


			$select["clien"] = $db->query($sCliIva);
			if ($db->numRows($select["clien"]) == 0) {
		    	$db->iEx($iCliIva);
			} else {
		    	$db->uEx($uCliIva);
			}	

			/* else {
				$fa["facturas"] = $db->sFetchAssoc($sFacturas);
				$IDInterno = $fa["facturas"]["fact_idinterno"];
				$numInv = $fa["facturas"]["ds_num"];
				$fecAnt = $fa["facturas"]["fact_fec"];
			}  */
			$numInv	= $numNum;


			// Encabezado Factura
			$resp = $db->iEx(iuFacturas($Batch, $Serial, $DocumentGUID, $IDInterno, $tot, $txtCliCod, $txtNit, $txtNomFac, $txtDir, $txtTel, $numDcre, $numTcam, $crFpag, $txtObs, $crRet, $crReti, '', $selVendCod, '', '', '', '', $selBodSalCod, "0.00", 0, $crExp, $FechaHoraEmision));

			// VARIABLES PARA SEPARAR BIENES, SERVICIOS Y EXPORTACION
			$hayBienes=false;
			$totales["bienes"]["exentoS"]=0;
			$totales["bienes"]["exentoN"]=0;
			$totales["servicios"]["exentoS"]=0;
			$totales["servicios"]["exentoN"]=0;
			$totales["exportacion"]=0;

			// PARA REVERTIR EXISTENCIAS
	/*		foreach ($jsonDetAnt as $obj) {
				if ($obj->factd_bienser!='S') {
					$r["exiart"] .= uExiart($obj->factd_cod, $obj->factd_cant, $obj->factd_bodsal, "+").";\n";
				}
			}  */

			// RECORRER DETALLE PARA ACUMULAR QUERYS
			$i=0;
			$iUltimoBien=0;
			foreach ($jsonDet as $obj) {
				$i++;
				$codd = utf8_decode($obj->codd);
				$descd = utf8_decode($obj->descd);
				$medid = utf8_decode($obj->medid);
				$unimed = utf8_decode($obj->unimed);
				$cantd = $obj->cantd;
				$preud = $obj->preud;
				$subd = $obj->subd;
				$descud = $obj->descud;
				$descuvd = $obj->descuvd;
				$totd = $obj->totd;
				$exensnd = $obj->exensnd;
				$bienserd = $obj->bienserd;
				$cosp = $db->sFetchAssoc(sArtic($obj->codd))["art_cosp"];

				// Hay que jalar la existencia actual
				$select["exiart"] = $db->query(sExiart($codd,$selBodSalCod));
				if ($db->numRows($select["exiart"])>0) {
					$existant=($db->fetchAssoc($select["exiart"])["ea_exist"]);
				} else {
					$existant=0;
					$db->iEx(iExiart($codd,$selBodSalCod));
				}
				$existact = $existant-$cantd;
				$db->uEx(uExiart($codd, $selBodSalCod, $existact));

	            # Aqui se recalculan existencias
	            # Para revisar las existencias normales
				$select["moviie0"] = $db->query(sMoviie0($codd,$selBodSalCod));
				$fetchAssoc["moviie0"] = $db->fetchAssoc($select["moviie0"]);
				if ($db->numRows($select["moviie0"]) == 0) {
				   $sumentro=0;
	            } else {
	              $sumentro=$fetchAssoc["moviie0"]["mov_sentra"];
                }
				$select["moviis0"] = $db->query(sMoviis0($codd,$selBodSalCod));
				$fetchAssoc["moviis0"] = $db->fetchAssoc($select["moviis0"]);
				if ($db->numRows($select["moviis0"]) == 0) {
				   $sumsalio=0;
	            } else {
	               $sumsalio=$fetchAssoc["moviis0"]["mov_ssale"];
				}	               
	            $exisactu=$sumentro-$sumsalio;
				$db->uEx(uExiart($codd,$selBodSalCod,$exisactu));

				$hayBienes = true;
				$iUltimoBien = $i;
				($obj->exensnd=='N') ? $totales["bienes"]["exentoN"]+=$obj->totd : $totales["bienes"]["exentoS"]+=$obj->totd;

                // Detalle de la factura
				$resp = $db->iEx(iFact_det($IDInterno, $IDInterno, $Batch, $Serial, 0, $txtCliCod, $txtNit, $selVendCod, $selBodSalCod, $numTcam, $txtObs, $txtNomFac, $txtDir, $crExp, $tot,$cosp,$codd,$descd,$medid,$unimed,$cantd,$preud,$subd,$descud,$descuvd,$totd,$exensnd,$bienserd));

				// Detalle de documentos inventario
				$resp = $db->iEx(iDocs_det($IDInterno, $IDInterno, $Batch, $Serial, 0, $txtCliCod, $txtNit, $selVendCod, $selBodSalCod, $numTcam, $txtObs, $txtNomFac, $txtDir, $crExp, $tot,$existant,$existact, $cosp, $i, $codd, $descd, $medid, $unimed, $cantd, $preud, $subd, $descud, $descuvd, $totd, $exensnd,$bienserd));

				// Movimiento en el inventario
				$resp = $db->iEx(iMovii($IDInterno, $IDInterno, $Batch, $Serial, 0, $txtCliCod, $txtNit, $selVendCod, $selBodSalCod, $numTcam, $txtObs, $txtNomFac, $txtDir, $crExp, $tot, $cosp, $i, $codd, $descd, $medid, $unimed, $cantd, $preud, $subd, $descud, $descuvd, $totd, $exensnd, $bienserd));

			}

			// Iva ventas
			$val = calculos($tot, $crRet, $crReti, $crExp, $selTipoImpues, $numTcam, 1);
			$resp = $db->iEx(iuIva_ven($Serial, $Batch, $txtNit, $txtNomFac, $crRet, $crReti, $val["bien"], $val["serv"], $val["exen"], $val["exp"], $txtObs, $val["subb"], $val["subs"], $val["sube"], $val["ret"], $val["reti"], $val["sub"], $val["iva"], $val["tot"], 1));


			$resp = $db->iEx(iuDoctoss($Serial,$selBodSalCod, $numTcam, $txtObs, $tot, $txtCliCod, $txtNit, $txtNomFac, $txtDir, $selVendCod, $Batch, $Serial, $FechaHoraEmision));

			// SI LA FORMA DE PAGO ES AL CREDITO, ENTONCES GUARDAR EN EL MODULO DE CUENTAS POR COBRAR
			if ($crFpag==2) {
				$resp = $db->iEx(iuDoctoscc($Serial, $Batch, $txtNit, $txtNomFac, $crRet, $crReti, $val["bien"], $val["serv"], $val["exen"], $val["exp"], $txtObs, $val["subb"], $val["subs"], $val["sube"], $val["ret"], $val["reti"], $val["sub"], $val["iva"], $val["tot"], $numTcam, $txtCliCod));
			}

			// SI EL DOCUMENTO ESTA EXENTO DE IMPUESTOS, ENTONCES GUARDAR POLIZA
			if (sizeof($jsonPol)>0) {
				$db->iEx(iPolizas($Serial, $Batch, $txtObs, $txtNit));
				$db->dEx(dPoli_det($Serial, $Batch));
				$db->iEx(iPoli_det($Serial, $Batch, $txtNit, $jsonPol));
			}

			// PARA BITACORA
			$db->iEx($func->iBitacora(utf8_decode("Se creó factura IDInterno: {$IDInterno} DocumentGUID: {$DocumentGUID} No.: {$Serial} Serie: {$Batch} NIT: {$txtNit} Usuario: ").$usuNom, $bitMod, $bitForm));

			// PARA APLICAR LOS CIERRES
			foreach ($jsonPol as $obj) {
				$cta = $obj->cta;
				while (!empty($cta)) {
					$fa["cuentas"] = $db->sFetchAssoc(sCuentas($cta));
					$ctaActa = trim($fa["cuentas"]["cta_acta"]);

					$select["cierres"] = $db->query(sCierres($cta, $numAno, $numMes));
					if ($db->numRows($select["cierres"]) > 0) {
						$fa["cierres"] = $db->fetchAssoc($select["cierres"]);
						$mdebe=$fa["cierres"]["cie_mdebe"]+$obj->debe;
						$mhaber=$fa["cierres"]["cie_mhaber"]+$obj->haber;

						$db->query(uCierres($cta, $numAno, $numMes, $mdebe, $mhaber));
					} else {
						$mdebe=$obj->debe;
						$mhaber=$obj->haber;

						$db->query(iCierres($cta, $numAno, $numMes, $mdebe, $mhaber));
					}
					$cta = $ctaActa;
				}
			}

			/*if ($db->multiQuery($queryAcum) === TRUE) {
				$resp = $db->rSuccessPublic('Se guardó correctamente', 'Serie: '.$Batch.'<br> Número: '.$Serial);
			} else {
				array_push($arrayError, array("Code"=>'MySQL', "cod"=>$db->errno(), "Description"=>$db->error()));
			}   */
		} else {
			// RESPUESTA
			$Code = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Code;
			$Description = $Body->RequestTransactionResponse->RequestTransactionResult->Response->Description;

			array_push($arrayError, array("Code"=>''.$Code, "cod"=>$txtCliCod, "Description"=>''.$Description));
		}
	}



	// Por si no se pudo guardar la factura de algún cliente
	$sizeError = sizeof($arrayError);
	if ($sizeError != 0) {
		$title = $arrayError[0]["Code"]." - ".$arrayError[0]["cod"];
		$text = $arrayError[0]["Description"];
		$resp = $db->rErrorPublic($title, $text);
	}

	$db->close();
	$resp["seriedoc"]=$Batch;
	$resp["numdoc"]=$Serial;
	$resp["nit"]=$txtNit;
	$resp["idinterno"]=$IDInterno;

	return json_encode($resp);
}


function imprimir() {
	global $empCod;

	$priv = new privileges();
	if (!$priv->consult($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorConsult());
	}
	
	# QUERYS
	$sTipov = "SELECT TRIM(tv_nom) AS tv_nom FROM tipov WHERE tv_cod='{$_POST["selTipoCod"]}'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$fa["tipov"] = $db->sFetchAssoc($sTipov);

	$_SESSION["printFacturas"] = array(
		'tipoNomFEL'=>$fa["tipov"]["tv_nom"],
		'tipoFEL'	=>$_POST["selTipoCod"],
		'nom'		=>$_POST["txtNomFac"],
		'nit'		=>$_POST["txtNit"],
		'dir'		=>$_POST["txtDir"],
		'fec'		=>$_POST["dtFec"],
		'tcam'		=>$_POST["tcam"],
		'tot'		=>$_POST["dataTot"],
		'totLetras'	=>$_POST["totLetras"],
		'det' 		=>$_POST["tblDet"]
	);
	return "";
}

function calculos($tot, $retsn, $retisn, $expsn, $impues, $tcam, $tcamRet) {
	global $totales;

	$val["ret"] = 0;
	$val["reti"] = 0;

	$val["bien"] = round($totales["bienes"]["exentoN"]*$tcam, 2);
	$val["serv"] = round($totales["servicios"]["exentoN"]*$tcam, 2);
	$val["exen"] = round(($totales["bienes"]["exentoS"]+$totales["servicios"]["exentoS"])*$tcam, 2);
	$val["exp"] = round($totales["exportacion"]*$tcam, 2);

	// SUBTOTALES
	$val["subb"] = $val["bien"];
	$val["subs"] = $val["serv"];
	$val["sube"] = $val["exp"];

    // IVA, SUBTOTAL Y TOTAL
	$val["tot"] = round($tot*$tcam, 2);
	$val["sub"] = $val["subb"]+$val["subs"]+$val["exen"]+$val["sube"];
	$val["iva"] = 0;
	if ($impues=="N") {
		$val["subb"] = ($val["bien"]/(($_SESSION['pIva']/100)+1));
		$val["subs"] = ($val["serv"]/(($_SESSION['pIva']/100)+1));
		$val["sube"] = $val["exp"];

		$val["sub"] = $val["subb"]+$val["subs"]+$val["exen"]+$val["sube"];
		$val["iva"] = $val["tot"]-$val["sub"];

		// RETENCION ISR
		$val["ret"]=0;
		$pBaseisrQ = $_SESSION["pBaseisr"]/$tcamRet;
		if ($retsn=='S' && $val["sub"]>=(2500/$tcamRet) && $expsn=='N') {
			if ($val["sub"] > $pBaseisrQ) {
				$sub1 = $pBaseisrQ;
				$sub2 = $val["sub"]-$pBaseisrQ;
			} else {
				$sub1 = $val["sub"];
				$sub2 = 0;
			}
			$ret1=($sub1*$_SESSION["pIsr"])/100;
			$ret2=($sub2*$_SESSION["pIsr2"])/100;
			$val["ret"]=round($ret1+$ret2, 2);
		}
		
		// RETENCION IVA
		$val["reti"] = ($retisn=='S' && $expsn=='N') ? round(($val["iva"]*$_SESSION["pRiva"])/100, 2) : 0;
	}

	return $val;
}
?>