 <?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');

$bitForm = "inv1035";
$bitMod = "inv";
$empCod = $_SESSION['empCod'];
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);

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

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

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

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

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

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

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

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

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

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

}

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

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

	$func = new functions();

	$numNum=$_POST['numNum'];
	$selTdoci=$_POST['selTdoci'];
	$TdociRelatpol=$_POST['TdociRelatpol'];

	# QUERYS
	$sDoctoss = "SELECT *, 
		TRIM(ds.ds_obs) AS ds_obs
		FROM doctoss ds WHERE ds_emp='$empCod' AND ds_tipo='$selTdoci' AND ds_num='$numNum'";

	$sDocs_det = "SELECT *, TRIM(art.art_ctacos) AS dsd_ctacos, TRIM(art.art_ctainv) AS dsd_ctainv
				FROM docs_det dsd
 				LEFT JOIN artic art ON dsd.dsd_emp = art.art_emp AND dsd.dsd_cod=art.art_cod
				WHERE dsd_emp='$empCod' AND dsd_tipo='$selTdoci' AND dsd_num='$numNum'";

	$sPoli_det = "SELECT *, TRIM(pold_cta) AS pold_cta FROM poli_det WHERE pold_emp='$empCod' AND pold_ban=0 AND pold_tipo='$TdociRelatpol' AND pold_num='$numNum'";

	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sDoctoss, "doctoss");
	$resp["docs_det"] = $db->sFetchAll($sDocs_det);
	$resp["poli_det"] = $db->sFetchAll($sPoli_det);
	$db->close();

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


function consultarCorr() {
	global $empCod;

	$func = new functions();

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

	# QUERYS
	$sCorrtdoci = "SELECT ctdi_corr FROM corrtdoci WHERE ctdi_emp='$empCod' AND ctdi_tipo='$selTdoci'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();

	$select["corrtdoci"] = $db->query($sCorrtdoci);
	if ($db->numRows($select["corrtdoci"])>0) {
		$numDoc = ($db->fetchAssoc($select["corrtdoci"])["ctdi_corr"]);
	} else {
		$numDoc = 1;
		$r["corrtdoci"] = $db->query("INSERT INTO corrtdoci (ctdi_emp, ctdi_tipo, ctdi_num) VALUES('$empCod', '$selTdoci', $numDoc);");
	}

	$resp["corrtdoci"]["ctdi_corr"] = $numDoc;
	$db->close();

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


function consultarArtic() {
	global $empCod, $selBod;

	$func = new functions();

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

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

	function sExiart_peps($codigo) { 
		global $empCod, $selBod;
		return "SELECT *
				FROM exiart_peps  
				WHERE ea_emp='$empCod' AND ea_bod='$selBod' AND ea_cod='$codigo' AND ea_exist>0 GROUP BY ea_cod ORDER BY ea_fvence";
	}

	/* $sExiart = "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='$txtCod'"; */

	$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);
	//$resp["imgArtic"] = "imgArticulos/$empCod"."_".$func->imgCharacters($txtCod).".jpeg?".rand(1,9999);
	$resp["exiart"] = $db->sFetchAll(sExiart($codigo));
	$resp["imgArtic"] = "imgArticulos/$empCod"."_".$func->imgCharacters($codigo).".jpeg?".rand(1,9999);

	$resp["exiart_peps"] = $db->sFetchAssoc(sExiart_peps($codigo));
	
	$db->close();

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

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

	$func = new functions();
	$dtFec=$_POST['dtFec'];
	$nAnio=date("Y", strtotime($dtFec));
	$nMes=date("n", strtotime($dtFec));

	# QUERYS
	$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$nAnio AND ciem_mes=$nMes";
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp["ciemes"] = $db->sfetchAssoc($sCiemes);
	$db->close();
	$func = new functions();
	return $func->jsonEncodeArray($resp, "ciemes");
}

function consultarCta() {
	global $empCod;
	$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 generarPartida() {
	global $empCod;
	$jsonDetao=json_decode($_POST['tblDetao'], true);
	$ctainv=$_POST['ctainv'];

	$func = new functions();
	# QUERYS
	function sCuentas($cta,$debe,$haber) {
		global $empCod;
		return "SELECT TRIM(cta) AS cta, TRIM(cta_nom) AS cta_nom, $debe AS cta_debe, $haber AS cta_haber
				FROM cuentas c WHERE cta='$cta' AND cta_emp='$empCod'";
	}
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$cero=0;
	// Para la cuenta de Inventarios
	$resp["ctaInv"]=array();
	// Para la cuenta de costos
	$resp["ctaCos"]=array();
	$j=0;
	foreach ($jsonDetao as $rec) {
		$rec["ctainv"] = $ctainv;
		$numtot = $rec["numtot"];

		$i = $func->multiSearch($resp["ctaInv"], array('cta' => (string)$rec["ctainv"]));
		if ($i >= 0) {
			$resp["ctaInv"][$i]["cta_haber"] += $numtot;
		} else {
			$fa["ctaInv"] = $db->sFetchAssoc(sCuentas((string)$rec['ctainv'],0,$numtot));
		    array_push($resp["ctaInv"], array("cta"=>$rec["ctainv"],"cta_nom"=>$fa["ctaInv"]["cta_nom"],"cta_debe"=>$cero,"cta_haber"=>$numtot));
		}
		// Para cuenta de costos
		$rec["ctacos"] = TRIM($rec["ctacos"]);
		$i = $func->multiSearch($resp["ctaCos"], array('cta' => (string)$rec["ctacos"]));
		if ($i >= 0) {
			$resp["ctaCos"][$i]["cta_debe"] += $numtot;
		} else {
			$fa["ctaCos"] = $db->sFetchAssoc(sCuentas((string)$rec['ctacos'],$numtot,0));
		    array_push($resp["ctaCos"], array("cta"=>$rec["ctacos"],"cta_nom"=>$fa["ctaCos"]["cta_nom"],"cta_debe"=>$numtot,"cta_haber"=>$cero));
		}
		unset($jsonDetao[$j]);
		$j++;
	}
	$db->close();

	return $func->jsonEncodeArrayEach($resp, array('ctaInv', 'ctaCos'));
}


function guardar() {
	global $empCod, $usuNom, $bitMod, $bitForm, $numNum, $numdoc, $selTdoci, $TdociNom, $dtFec, $dtFecant, $selBodega, $selBodegaant, $txtCon, $sumtot, $piva, $numAnio, $numMes, $numAnioAnt, $numMesAnt, $TdociPartsn, $TdociRelatpol, $TdociAfecos, $TdociInveini, $dtGrabado;

	$func = new functions();

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

	$numNum=$_POST['numNum'];
	$numdoc=$_POST['numNum'];
	$selTdoci=$_POST['selTdoci'];
	$TdociNom=$_POST['TdociNom'];
	$TdociPartsn=$_POST['TdociPartsn'];
	$TdociRelatpol=$_POST['TdociRelatpol'];
	$TdociAfecos=$_POST['TdociAfecos'];
	$TdociInveini=$_POST['TdociInveini'];
	$dtFec=$_POST['dtFec'];
	$dtFecant=$_POST['dtFecant'];
	$selBodega=$_POST['selBodega'];
	$selBodegaant=$_POST['selBodegaant'];
	$Bodeganom=$_POST['BodegaNom'];
	$txtCon=$_POST['txtCon'];
	$sumtot=$_POST['sumtot'];
	$jsonDetao=json_decode($_POST['tblDetao']);
	$jsonPol=json_decode($_POST['tblPol']);
	$jsonDetaoAnt=json_decode($_POST['tblDetaoAnt']);
	$jsonPolAnt=json_decode($_POST['tblPolAnt']);
	$numAnio=date("Y", strtotime($dtFec));
	$numMes=date("n", strtotime($dtFec));
	$numAnioAnt=date("Y", strtotime($dtFecant));
	$numMesAnt=date("n", strtotime($dtFecant));
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));

	# QUERYS PARA UN REGISTRO
	$sCorrTdoci = "SELECT * FROM corrtdoci WHERE ctdi_emp='$empCod' AND ctdi_tipo='$selTdoci'";

	function iCorrTdoci($nuevocorr) { 
		global $empCod, $usuNom, $selTdoci;
		return "INSERT INTO corrtdoci(ctdi_emp, ctdi_tipo, ctdi_corr) VALUES ('$empCod','$selTdoci',$nuevocorr)";
	}
	function uCorrTdoci($nuevocorr) { 
		global $empCod, $usuNom, $selTdoci;
		return "UPDATE corrtdoci SET ctdi_corr=$nuevocorr WHERE ctdi_emp='$empCod' and ctdi_tipo='$selTdoci'";
	}

	$iDoctoss="INSERT INTO doctoss(ds_emp, ds_tipo, ds_num, ds_fec, ds_fecapli, ds_bodsal, ds_tcam, ds_obs, ds_total, ds_ulcam, ds_lentrega,ds_obsfac) VALUES ('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$selBodega',1,'$txtCon', '$sumtot','$usuNom','','')";


	$uDoctoss="UPDATE doctoss SET ds_fec='$dtFec', ds_fecapli='$dtFec', ds_bodsal='$selBodega', ds_obs='$txtCon', ds_total=$sumtot, ds_ulcam='$usuNom' WHERE ds_emp='$empCod' AND ds_tipo='$selTdoci' AND ds_num='$numNum'";

	$dDocs_det="DELETE FROM docs_det WHERE dsd_emp='$empCod' AND dsd_tipo='$selTdoci' AND dsd_num='$numNum'";
	$dMovii="DELETE FROM movii WHERE mov_emp='$empCod' AND mov_tipo='$selTdoci' AND mov_num='$numNum'";
	$dMoviipeps="DELETE FROM movii_peps WHERE mov_emp='$empCod' AND mov_tipo='$selTdoci' AND mov_num='$numNum'";

	function iDocs_det($codd, $descd, $cantd, $unimed, $medid, $cosud, $numtot, $cosmovi, $exiant, $nuevaexist, $lote, $fvence) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $dtFec, $selBodega, $txtCon, $sumtot, $crPror;
		return "INSERT INTO docs_det(dsd_emp, dsd_tipo, dsd_num, dsd_fec, dsd_fecapli, dsd_cod, dsd_cant, dsd_desc, dsd_descfac,dsd_med, dsd_unimed, dsd_unit, dsd_monto, dsd_cosu, dsd_exiant, dsd_exipos, dsd_lote, dsd_fvence) VALUES('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$codd','$cantd','$descd','$descd','$unimed','$medid','$cosud','$numtot', '$cosmovi', '$exiant','$nuevaexist','$lote','$fvence')";
	}

	function iMovii($codd, $cantd, $cosud, $precio) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $dtFec, $selBodega, $numtcam, $selSerieo, $numOrdenc, $txtCon, $sumtot, $crPror;
		return "INSERT INTO movii (mov_emp, mov_tipo, mov_num, mov_fec, mov_fecapli, mov_cod, mov_bodsal, mov_sale, mov_cosu, mov_preu,mov_fserie,mov_fnum) VALUES ('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$codd','$selBodega','$cantd','$cosud','$precio','',0)";
	}

	function iMoviipeps($codd, $cantd, $cosud, $precio, $lote, $fvence) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $dtFec, $selBodega, $txtCon, $sumtot, $crPror;
		return "INSERT INTO movii_peps (mov_emp, mov_tipo, mov_num, mov_fec, mov_fecapli, mov_cod, mov_bodent, mov_bodsal, mov_entra, mov_sale, mov_cosu, mov_preu, mov_lote, mov_fvence, mov_fserie, mov_fnum) VALUES ('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$codd','','$selBodega', 0, '$cantd','$cosud','$precio','$lote','$fvence','',0)";
	}

	function sArtic($codd) { 
		global $empCod, $usuNom;
		return "SELECT * FROM artic WHERE art_emp='$empCod' AND art_cod='$codd'";
	}

	function sExiart($codd,$bodega) { 
		global $empCod, $usuNom, $selBodega;
		return "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}

	function uExiart($codd,$bodega, $nexist) { 
		global $empCod, $usuNom, $selBodega;
		return "UPDATE exiart SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}
	function iExiart($codd,$bodega, $nexist) { 
		global $empCod, $usuNom, $selBodega;
		return "INSERT INTO exiart(ea_emp,ea_cod,ea_bod,ea_exist) VALUES('$empCod','$codd','$bodega','$nexist')";
	}

	function sExiartpeps($codd,$bodega,$fvence) { 
		global $empCod, $usuNom;
		return "SELECT * FROM exiart_peps WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega' AND ea_fvence='$fvence'";
	}

	function uExiartpeps($codd,$nexist,$bodega,$lote,$fvence,$cosu) { 
		global $empCod, $usuNom;
		return "UPDATE exiart_peps SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega' AND ea_fvence='$fvence'";
	}
	function iExiartpeps($codd,$nexist,$bodega,$lote,$fvence,$cosu) { 
		global $empCod, $usuNom;
		return "INSERT INTO exiart_peps(ea_emp,ea_cod,ea_bod,ea_exist,ea_lote,ea_fvence,ea_cosu) VALUES('$empCod','$codd','$bodega','$nexist','$lote','$fvence',$cosu)";
	}

	# QUERY PARA ACTUALIZAR LA ORDEN DE COMPRA
	function iPolizas($fecha,$banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCodp, $txtCon, $dtGrabado;
		return "INSERT INTO polizas(pol_emp, pol_fec, pol_ban, pol_tipo, pol_num, pol_con, pol_ulcam, pol_grabado, pol_stat, pol_tipoi, pol_nit) VALUES ('$empCod','$fecha','$banco','$tipo','$numero','$txtCon','$usuNom','$dtGrabado','','','')";
	}

	function uPolizas($fecha,$banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCon, $dtGrabado;
		return "UPDATE polizas SET pol_fec='$fecha', pol_con='$txtCon', pol_ulcam='$usuNom', pol_grabado='$dtGrabado' WHERE pol_emp='$empCod' AND pol_ban='$banco' AND pol_tipo='$tipo' AND pol_num='$numero'";
	}
	function sPolizas($banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCon, $dtGrabado;
		return "SELECT *, TRIM(pol_con) AS pol_con FROM polizas WHERE pol_emp='$empCod' AND pol_ban='$banco' AND pol_tipo='$tipo' AND pol_num='$numero'";
	}

	function sPoli_det($banco,$tipo,$numero) { 
		global $empCod;
		return "SELECT * FROM poli_det WHERE pold_emp='$empCod' AND pold_ban='$banco' AND pold_tipo='$tipo' AND pold_num='$numero'";
	}

	function dPolizas($banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCon, $dtGrabado;
		return "DELETE FROM polizas WHERE pol_emp='$empCod' AND pol_ban='$banco' AND pol_tipo='$tipo' AND pol_num='$numero'";
	}

	function dPoli_det($banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCon, $dtGrabado;
		return "DELETE FROM poli_det WHERE pold_emp='$empCod' AND pold_ban='$banco' AND pold_tipo='$tipo' AND pold_num='$numero'";
	}

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

	# QUERYS PARA PARTIDA
	function iPoli_det($fecha,$banco,$tipo,$numero,$cta,$ctan,$debe,$haber) { 
		global $empCod;
		return "INSERT INTO poli_det(pold_emp, pold_fec, pold_ban, pold_tipo, pold_num, pold_cta, pold_ctan, pold_debe, pold_haber,pold_tipoi,pold_nit) VALUES ('$empCod','$fecha','$banco','$tipo','$numero','$cta','$ctan','$debe','$haber','','')";
	}

	# 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'";
	}
	function sMoviie0peps($codd, $bodega, $fvence) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_entra) AS mov_sentrapeps
	            FROM movii_peps WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodent='$bodega' AND mov_fvence='$fvence' GROUP BY '$empCod','$bodega','$codd','$fvence'";
	}

	function sMoviis0peps($codd, $bodega, $fvence) { 
	    global $empCod, $usuNom;
	    return "SELECT mov_emp,mov_cod,mov_bodent,mov_bodsal,
	            SUM(mov_sale) AS mov_ssalepeps
	            FROM movii_peps WHERE mov_emp='$empCod' AND mov_cod='$codd' AND mov_bodsal='$bodega' AND mov_fvence='$fvence' GROUP BY '$empCod','$bodega','$codd','$fvence'";
	}
	///

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	// Revisa si hay algun problema en la partida, para ver si permite grabar o no
	$probpol1="X";
	$probpol2="A";	
	$probpol3="A";	
	if ($TdociPartsn != 'S') {
	  $probpol2="X";	
	  $probpol3="X";	
	}
	foreach ($jsonPol as $obj) {
		$ctapol = trim($obj->cta);
		$debe = trim($obj->debe);
		$haber = trim($obj->haber);

		$select["cuentas"] = $db->query(sCuentas($ctapol));
		$fetchAssoc["cuentas"] = $db->fetchAssoc($select["cuentas"]);
		$ctaC = trim($fetchAssoc["cuentas"]["cta"]);
		if ($db->numRows($select["cuentas"]) == 0) {
			$probpol1 = "A";
		}
		//if ($ctapol == $ctaprov) {
			$probpol2 = "X";
		//}
		//if ($ctapol == $ctaprov && $totQ == $debe) {
			$probpol3 = "X";
		//}
	}
	//

	if ($probpol1 == "X") {
		$select["corrtdoci"] = $db->query($sCorrTdoci);
		$fetchAssoc["corrtdoci"] = $db->fetchAssoc($select["corrtdoci"]);
		if ($db->numRows($select["corrtdoci"]) == 0) {
		  //$numdoc=1;
		  $nuevocorr=$numdoc+1;
		  $db->iEx(iCorrTdoci($nuevocorr));
		} else {
	      //$numdoc=$fetchAssoc["corrtdoci"]["ctdi_corr"];
		  if ($func->stringToBool($_POST['nuevo'])) {
		  	$nuevocorr=$numdoc+1;
		  	$db->uEx(uCorrTdoci($nuevocorr));
		  }
		}
			
		// PARA REGISTRAR EL DOCUMENTO
		$db->dEx($dDocs_det);
		$db->dEx($dMovii);
		$db->dEx($dMoviipeps);
		if ($func->stringToBool($_POST['nuevo'])) {
			$resp = $db->iEx($iDoctoss);
			$db->iEx($func->iBitacora(utf8_decode("Se creo El documento $TdociNom  Numero.: $numdoc de  Bodega: $selBodega Fecha: $dtFec Usuario: ").$usuNom, $bitMod, $bitForm));
		} else {
			$resp = $db->uEx($uDoctoss);
			$db->iEx($func->iBitacora(utf8_decode("Se Modifico El documento $TdociNom  Numero.: $numdoc  Bodega: $selBodegaant Fecha: $dtFecant Usuario: ").$usuNom, $bitMod, $bitForm));
		}
		// Para quitar lo que estaba antes
		foreach ($jsonDetaoAnt as $obja) {
			$codd = trim($obja->dsd_cod);
			$descd = trim($obja->dsd_desc);
			$unimed = $obja->dsd_med;
			$medid = $obja->dsd_unimed;
			$cantd = $obja->dsd_cant;
			$cosud = $obja->dsd_unit;
			$numtot = $obja->dsd_monto;
			$sale=$cantd;
			$loted = $obja->dsd_lote;
			$fvenced = $obja->dsd_fvence;
			$select["artic"] = $db->query(sArtic($codd));
			$fetchAssoc["artic"] = $db->fetchAssoc($select["artic"]);
            $antcosp=$fetchAssoc["artic"]["art_cosp"];
            $antcosa=$fetchAssoc["artic"]["art_cosa"];
            $antcosr=$fetchAssoc["artic"]["art_cosr"];
            $precio=$fetchAssoc["artic"]["art_pre1"];
            $bienser=$fetchAssoc["artic"]["art_bienser"];

			$select["exiart"] = $db->query(sExiart($codd,$selBodegaant));
			$fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
			if ($db->numRows($select["exiart"]) == 0) {
				$exiant=0;
            } else {
              $exiant=$fetchAssoc["exiart"]["ea_exist"];
            }
            $nuevaexist=$exiant+($cantd);

			if ($db->numRows($select["exiart"]) == 0) {
				$db->iEx(iExiart($codd,$selBodegaant,$nuevaexist));
            } else {
				$db->uEx(uExiart($codd,$selBodegaant,$nuevaexist));
            }

	        # Para existencia Peps
			$select["exiarts_peps"] = $db->query(sExiartpeps($codd,$selBodegaant,$fvenced));
			$fetchAssoc["exiarts_peps"] = $db->fetchAssoc($select["exiarts_peps"]);
			if ($db->numRows($select["exiarts_peps"]) == 0) {
				$exiantspeps=0;
	        } else {
	          $exiantspeps=$fetchAssoc["exiarts_peps"]["ea_exist"];
	        }
	        $nuevaexistspeps=$exiantspeps+$cantd;
		}

		$db->dEx(dPolizas(0,$TdociRelatpol,$numdoc));
		$db->dEx(dPoli_det(0,$TdociRelatpol,$numdoc));
		if ($TdociPartsn == 'S') {
			// PARA APLICAR LOS CIERRES
			foreach ($jsonPolAnt as $obja) {
				$ctapol = $obja->pold_cta;
				$cta = $obja->pold_cta;
				$ctanom = $obja->pold_ctan;
				$debe = $obja->pold_debe;
				$haber = $obja->pold_haber;
				while (!empty($cta)) {
					$select["cuentas"] = $db->query(sCuentas($cta));
					$select["cierres"] = $db->query(sCierres($cta, $numAnioAnt, $numMesAnt));

					$fetchAssoc["cuentas"] = $db->fetchAssoc($select["cuentas"]);
					$ctaActa = trim($fetchAssoc["cuentas"]["cta_acta"]);

					if ($db->numRows($select["cierres"]) > 0) {
						$fetchAssoc["cierres"] = $db->fetchAssoc($select["cierres"]);
						$mdebe=$fetchAssoc["cierres"]["cie_mdebe"]-$obja->pold_debe;
						$mhaber=$fetchAssoc["cierres"]["cie_mhaber"]-$obja->pold_haber;

						$db->query(uCierres($cta, $numAnioAnt, $numMesAnt, $mdebe, $mhaber));
					} else {
						$mdebe=$obja->debe*-1;
						$mhaber=$obja->haber*-1;
						$db->query(iCierres($cta, $numAnioAnt, $numMesAnt, $mdebe, $mhaber));
					}
					$cta = $ctaActa;
				}
			}
		}

        // Para aplicar lo que se modifico
		foreach ($jsonDetao as $obj) {
			$codd = trim($obj->codd);
			$descd = trim($obj->descd);
			$unimed = $obj->unimed;
			$medid = $obj->medid;
			$cantd = $obj->cantd;
			$cosud = $obj->cosud;
			$nuevocosto = $obj->cosud;
			$numtot = $obj->numtot;
			$loted = $obj->loted;
			$fvenced = $obj->fvenced;
			$sale=$cantd;

			$select["artic"] = $db->query(sArtic($codd));
			$fetchAssoc["artic"] = $db->fetchAssoc($select["artic"]);
            $antcosp=$fetchAssoc["artic"]["art_cosp"];
            $antcosa=$fetchAssoc["artic"]["art_cosa"];
            $antcosr=$fetchAssoc["artic"]["art_cosr"];
            $precio=$fetchAssoc["artic"]["art_pre1"];
            $bienser=$fetchAssoc["artic"]["art_bienser"];

			$select["exiart"] = $db->query(sExiart($codd,$selBodega));
			$fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
			if ($db->numRows($select["exiart"]) == 0) {
				$exiant=0;
            } else {
              $exiant=$fetchAssoc["exiart"]["ea_exist"];
            }
            $nuevaexist=$exiant-($cantd);

			$select["exiarts_peps"] = $db->query(sExiartpeps($codd,$selBodega,$fvenced));
			$fetchAssoc["exiarts_peps"] = $db->fetchAssoc($select["exiarts_peps"]);
			if ($db->numRows($select["exiarts_peps"]) == 0) {
				$exiantspeps=0;
	        } else {
	          $exiantspeps=$fetchAssoc["exiarts_peps"]["ea_exist"];
	        }
	        $nuevaexistspeps=$exiantspeps-$cantd;

            // Registra el detalle
			$db->query(iDocs_det($codd, $descd, $cantd, $unimed, $medid, $cosud, $numtot, $antcosp, $exiant, $nuevaexist, $loted, $fvenced));

		    $nuevocosp=$antcosp;
		    $nuevocosr=$antcosr;
		    $nuevocosa=$antcosa;
		    $cosmovii=$cosud;

			if ($bienser!='S') {
				// registra movimiento, Cambia existencia y costos
				$db->query(iMovii($codd, $sale, $cosmovii, $precio));

				# registra movimiento, Cambia existencia peps
				$db->query(iMoviipeps($codd, $sale, $cosud, $precio, $loted, $fvenced));

				//$db->uEx(uArtic($codd));
				/* Esta parte se bloqueo porque abajo se recalcula
				if ($db->numRows($select["exiart"]) == 0) {
					$db->iEx(iExiart($codd,$selBodega,$nuevaexist));
	            } else {
					$db->uEx(uExiart($codd,$selBodega,$nuevaexist));
	            }

				// Salida peps
				if ($db->numRows($select["exiarts_peps"]) == 0) {
					$db->iEx(iExiartpeps($codd,$nuevaexistspeps,$selBodega,$loted,$fvenced,$cosud));
	            } else {
					$db->uEx(uExiartpeps($codd,$nuevaexistspeps,$selBodega,$loted,$fvenced,$cosud));
	            }
				*/

	            # Aqui se recalculan existencias
	            # Para revisar las existencias normales
				$select["moviie0"] = $db->query(sMoviie0($codd,$selBodega));
				$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,$selBodega));
				$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,$selBodega,$exisactu));

	            # Para revisar las existencias normales peps
				$select["moviie0peps"] = $db->query(sMoviie0peps($codd,$selBodega,$fvenced));
				$fetchAssoc["moviie0peps"] = $db->fetchAssoc($select["moviie0peps"]);
				if ($db->numRows($select["moviie0peps"]) == 0) {
				   $sumentropeps=0;
	            } else {
	               $sumentropeps=$fetchAssoc["moviie0peps"]["mov_sentrapeps"];
	            }
				$select["moviis0peps"] = $db->query(sMoviis0peps($codd,$selBodega,$fvenced));
				$fetchAssoc["moviis0peps"] = $db->fetchAssoc($select["moviis0peps"]);
				if ($db->numRows($select["moviis0peps"]) == 0) {
				   $sumsaliopeps=0;
	            } else {
	               $sumsaliopeps=$fetchAssoc["moviis0peps"]["mov_ssalepeps"];
	            }
	            $exisactupeps=$sumentropeps-$sumsaliopeps;
				$db->uEx(uExiartpeps($codd,$exisactupeps,$selBodega,$loted,$fvenced,$nuevocosto));
				//
	        }
		}
		$db->dEx(dPolizas(0,$TdociRelatpol,$numdoc));
		$db->dEx(dPoli_det(0,$TdociRelatpol,$numdoc));
		if ($TdociPartsn == 'S') {
			// PARA APLICAR LOS CIERRES
			foreach ($jsonPol as $obj) {
				$ctapol = $obj->cta;
				$cta = $obj->cta;
				$ctanom = $obj->ctaNom;
				$debe = $obj->debe;
				$haber = $obj->haber;
				while (!empty($cta)) {
					$select["cuentas"] = $db->query(sCuentas($cta));
					$select["cierres"] = $db->query(sCierres($cta, $numAnio, $numMes));

					$fetchAssoc["cuentas"] = $db->fetchAssoc($select["cuentas"]);
					$ctaActa = trim($fetchAssoc["cuentas"]["cta_acta"]);

					if ($db->numRows($select["cierres"]) > 0) {
						$fetchAssoc["cierres"] = $db->fetchAssoc($select["cierres"]);
						$mdebe=$fetchAssoc["cierres"]["cie_mdebe"]+$obj->debe;
						$mhaber=$fetchAssoc["cierres"]["cie_mhaber"]+$obj->haber;

						$db->query(uCierres($cta, $numAnio, $numMes, $mdebe, $mhaber));
					} else {
						$mdebe=$obj->debe;
						$mhaber=$obj->haber;
						$db->query(iCierres($cta, $numAnio, $numMes, $mdebe, $mhaber));
					}
					$cta = $ctaActa;
				}
				$db->iEx(iPoli_det($dtFec,0,$TdociRelatpol,$numdoc,$ctapol,$ctanom,$debe,$haber));
			}
			$db->iEx(iPolizas($dtFec,0,$TdociRelatpol,$numdoc));
		}
	}
	//$resp["tipoabo"] = $db->query($sTipoabo);
	$db->close();
	
	$resp["dtGrabado"]=$dtGrabado;
	$resp["numdoc"]=$numdoc;
	$resp["probpol1"]=$probpol1;
	//$resp["TdociAfecos"]=$TdociAfecos;
	//$resp["TdociInveini"]=$TdociInveini;
	//return $func->jsonEncodeArray($resp, "tipoabo");
	return json_encode($resp);
}

function anular() {
	global $empCod, $usuNom, $bitMod, $bitForm, $selTdoci, $TdociNom, $dtFec, $dtFecant,  $selBodegaant, $numNum,  $piva, $numAnio, $numMes, $numAnioAnt, $numMesAnt, $TdociRelatpol;

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

	$func = new functions();

	$numNum=$_POST['numNum'];
	$numdoc=$_POST['numNum'];
	$selTdoci=$_POST['selTdoci'];
	$TdociNom=$_POST['TdociNom'];
	$TdociRelatpol=$_POST['TdociRelatpol'];
	$selBodegaant=$_POST['selBodegaant'];
	$dtFec=$_POST['dtFec'];
	$dtFecant=$_POST['dtFecant'];
	$numAnio=date("Y", strtotime($dtFec));
	$numMes=date("n", strtotime($dtFec));
	$numAnioAnt=date("Y", strtotime($dtFecant));
	$numMesAnt=date("n", strtotime($dtFecant));
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));
	$jsonDetaoAnt=json_decode($_POST['tblDetaoAnt']);
	$jsonPolAnt=json_decode($_POST['tblPolAnt']);
	$anu='**** ANULADO ****';
	$valcero=0;

	# QUERYS PARA UN REGISTRO


	$uDoctoss="UPDATE doctoss SET ds_obs='$anu', ds_total=0, ds_ulcam='$usuNom' WHERE ds_emp='$empCod' AND ds_tipo='$selTdoci' AND ds_num='$numNum'";

	$uDocs_det="UPDATE docs_det SET dsd_cant=0, dsd_unit=0, dsd_monto=0, dsd_stat='A' WHERE dsd_emp='$empCod' AND dsd_tipo='$selTdoci' AND dsd_num='$numNum'";

	$uMovii="UPDATE movii SET mov_sale=0, mov_stat='A' WHERE mov_emp='$empCod' AND mov_tipo='$selTdoci' AND mov_num='$numNum'";
	$uMoviipeps="UPDATE movii_peps SET mov_sale=0, mov_stat='A' WHERE mov_emp='$empCod' AND mov_tipo='$selTdoci' AND mov_num='$numNum'";

	function sExiart($codd,$bodega) { 
		global $empCod, $usuNom, $selBodega;
		return "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}

	function uExiart($codd,$bodega, $nexist) { 
		global $empCod, $usuNom, $selBodega;
		return "UPDATE exiart SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}
	
	function sExiartpeps($codd,$bodega,$fvence) { 
		global $empCod, $usuNom;
		return "SELECT * FROM exiart_peps WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega' AND ea_fvence='$fvence'";
	}

	function uExiartpeps($codd,$nexist,$bodega,$lote,$fvence,$cosu) { 
		global $empCod, $usuNom;
		return "UPDATE exiart_peps SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega' AND ea_fvence='$fvence'";
	}
	function iExiartpeps($codd,$nexist,$bodega,$lote,$fvence,$cosu) { 
		global $empCod, $usuNom;
		return "INSERT INTO exiart_peps(ea_emp,ea_cod,ea_bod,ea_exist,ea_lote,ea_fvence,ea_cosu) VALUES('$empCod','$codd','$bodega','$nexist','$lote','$fvence',$cosu)";
	}

	# QUERY PARA ACTUALIZAR LA ORDEN DE COMPRA
	function dPolizas($banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCon, $dtGrabado;
		return "DELETE FROM polizas WHERE pol_emp='$empCod' AND pol_ban='$banco' AND pol_tipo='$tipo' AND pol_num='$numero'";
	}

	function dPoli_det($banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCon, $dtGrabado;
		return "DELETE FROM poli_det WHERE pold_emp='$empCod' AND pold_ban='$banco' AND pold_tipo='$tipo' AND pold_num='$numero'";
	}

	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')";	    
	}
	
	# QUERYS PARA VARIOS REGISTROS

	# EJECUCION DE QUERYS 
	$db = new dbExec();

	// Para quitar lo que estaba antes
	foreach ($jsonDetaoAnt as $obja) {
		$codd = trim($obja->dsd_cod);
		$descd = trim($obja->dsd_desc);
		$unimed = $obja->dsd_med;
		$medid = $obja->dsd_unimed;
		$loted = $obja->dsd_lote;
		$fvenced = $obja->dsd_fvence;
		$cantd = $obja->dsd_cant;
		$cosud = $obja->dsd_unit;
		$numtot = $obja->dsd_monto;
		$sale=$cantd;

		$select["exiart"] = $db->query(sExiart($codd,$selBodegaant));
		$fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
		if ($db->numRows($select["exiart"]) == 0) {
			$exiant=0;
	    } else {
	      $exiant=$fetchAssoc["exiart"]["ea_exist"];
	    }
	    $nuevaexist=$exiant+($cantd);

		if ($db->numRows($select["exiart"]) != 0) {
			$db->uEx(uExiart($codd,$selBodegaant,$nuevaexist));
	    }

        # Para existencia Peps
		$select["exiarts_peps"] = $db->query(sExiartpeps($codd,$selBodegaant,$fvenced));
		$fetchAssoc["exiarts_peps"] = $db->fetchAssoc($select["exiarts_peps"]);
		if ($db->numRows($select["exiarts_peps"]) == 0) {
			$exiantspeps=0;
        } else {
          $exiantspeps=$fetchAssoc["exiarts_peps"]["ea_exist"];
        }
        $nuevaexistspeps=$exiantspeps+$cantd;
		if ($db->numRows($select["exiarts_peps"]) == 0) {
			$db->iEx(iExiartpeps($codd,$nuevaexistspeps,$selBodegaant,$loted,$fvenced,$cosud));
        } else {
			$db->uEx(uExiartpeps($codd,$nuevaexistspeps,$selBodegaant,$loted,$fvenced,$cosud));
        }
	}
	$db->dEx(dPolizas(0,$TdociRelatpol,$numdoc));
	$db->dEx(dPoli_det(0,$TdociRelatpol,$numdoc));
	// PARA APLICAR LOS CIERRES
	foreach ($jsonPolAnt as $obja) {
		$ctapol = $obja->pold_cta;
		$cta = $obja->pold_cta;
		$ctanom = $obja->pold_ctan;
		$debe = $obja->pold_debe;
		$haber = $obja->pold_haber;
		while (!empty($cta)) {
			$select["cuentas"] = $db->query(sCuentas($cta));
			$select["cierres"] = $db->query(sCierres($cta, $numAnioAnt, $numMesAnt));

			$fetchAssoc["cuentas"] = $db->fetchAssoc($select["cuentas"]);
			$ctaActa = trim($fetchAssoc["cuentas"]["cta_acta"]);

			if ($db->numRows($select["cierres"]) > 0) {
				$fetchAssoc["cierres"] = $db->fetchAssoc($select["cierres"]);
				$mdebe=$fetchAssoc["cierres"]["cie_mdebe"]-$obja->pold_debe;
				$mhaber=$fetchAssoc["cierres"]["cie_mhaber"]-$obja->pold_haber;

				$db->query(uCierres($cta, $numAnioAnt, $numMesAnt, $mdebe, $mhaber));
			} else {
				$mdebe=$obja->debe*-1;
				$mhaber=$obja->haber*-1;
				$db->query(iCierres($cta, $numAnioAnt, $numMesAnt, $mdebe, $mhaber));
			}
			$cta = $ctaActa;
		}
	}

	$resp = $db->anEx($uDoctoss);
	$db->uEx($uDocs_det);
	$db->uEx($uMovii);
	$db->uEx($uMoviipeps);

	//
	$db->iEx($func->iBitacora(utf8_decode("Se Anulo El documento $TdociNom  Numero.: $numNum  Bodega: $selBodegaant Fecha: $dtFecant Usuario: ").$usuNom, $bitMod, $bitForm));
	$db->close();

	return json_encode($resp);
}

function borrar() {
	global $empCod, $usuNom, $bitMod, $bitForm, $selTdoci, $TdociNom, $dtFec, $dtFecant,  $selBodegaant, $numNum,  $piva, $numAnio, $numMes, $numAnioAnt, $numMesAnt, $TdociRelatpol;

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

	$func = new functions();

	$numNum=$_POST['numNum'];
	$numdoc=$_POST['numNum'];
	$selTdoci=$_POST['selTdoci'];
	$TdociNom=$_POST['TdociNom'];
	$TdociRelatpol=$_POST['TdociRelatpol'];
	$selBodegaant=$_POST['selBodegaant'];
	$dtFec=$_POST['dtFec'];
	$dtFecant=$_POST['dtFecant'];
	$numAnio=date("Y", strtotime($dtFec));
	$numMes=date("n", strtotime($dtFec));
	$numAnioAnt=date("Y", strtotime($dtFecant));
	$numMesAnt=date("n", strtotime($dtFecant));
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));
	$jsonDetaoAnt=json_decode($_POST['tblDetaoAnt']);
	$jsonPolAnt=json_decode($_POST['tblPolAnt']);
	$anu='**** ANULADO ****';
	$valcero=0;

	# QUERYS PARA UN REGISTRO


	$dDoctoss="DELETE FROM doctoss WHERE ds_emp='$empCod' AND ds_tipo='$selTdoci' AND ds_num='$numNum'";

	$dDocs_det="DELETE FROM docs_det WHERE dsd_emp='$empCod' AND dsd_tipo='$selTdoci' AND dsd_num='$numNum'";

	$dMovii="DELETE FROM movii WHERE mov_emp='$empCod' AND mov_tipo='$selTdoci' AND mov_num='$numNum'";
	$dMoviipeps="DELETE FROM movii_peps WHERE mov_emp='$empCod' AND mov_tipo='$selTdoci' AND mov_num='$numNum'";


	function sExiart($codd,$bodega) { 
		global $empCod, $usuNom, $selBodega;
		return "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}

	function uExiart($codd,$bodega, $nexist) { 
		global $empCod, $usuNom, $selBodega;
		return "UPDATE exiart SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}
	
	function sExiartpeps($codd,$bodega,$fvence) { 
		global $empCod, $usuNom;
		return "SELECT * FROM exiart_peps WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega' AND ea_fvence='$fvence'";
	}

	function uExiartpeps($codd,$nexist,$bodega,$lote,$fvence,$cosu) { 
		global $empCod, $usuNom;
		return "UPDATE exiart_peps SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega' AND ea_fvence='$fvence'";
	}
	function iExiartpeps($codd,$nexist,$bodega,$lote,$fvence,$cosu) { 
		global $empCod, $usuNom;
		return "INSERT INTO exiart_peps(ea_emp,ea_cod,ea_bod,ea_exist,ea_lote,ea_fvence,ea_cosu) VALUES('$empCod','$codd','$bodega','$nexist','$lote','$fvence',$cosu)";
	}

	# QUERY PARA ACTUALIZAR LA ORDEN DE COMPRA
	function dPolizas($banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCon, $dtGrabado;
		return "DELETE FROM polizas WHERE pol_emp='$empCod' AND pol_ban='$banco' AND pol_tipo='$tipo' AND pol_num='$numero'";
	}

	function dPoli_det($banco,$tipo,$numero) { 
		global $empCod, $usuNom, $txtCon, $dtGrabado;
		return "DELETE FROM poli_det WHERE pold_emp='$empCod' AND pold_ban='$banco' AND pold_tipo='$tipo' AND pold_num='$numero'";
	}

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

	
	# QUERYS PARA VARIOS REGISTROS

	# EJECUCION DE QUERYS 
	$db = new dbExec();

	// Para quitar lo que estaba antes
	foreach ($jsonDetaoAnt as $obja) {
		$codd = trim($obja->dsd_cod);
		$descd = trim($obja->dsd_desc);
		$unimed = $obja->dsd_med;
		$medid = $obja->dsd_unimed;
		$loted = $obja->dsd_lote;
		$fvenced = $obja->dsd_fvence;
		$cantd = $obja->dsd_cant;
		$cosud = $obja->dsd_unit;
		$numtot = $obja->dsd_monto;
		$sale=$cantd;

		$select["exiart"] = $db->query(sExiart($codd,$selBodegaant));
		$fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
		if ($db->numRows($select["exiart"]) == 0) {
			$exiant=0;
	    } else {
	      $exiant=$fetchAssoc["exiart"]["ea_exist"];
	    }
	    $nuevaexist=$exiant+($cantd);

		if ($db->numRows($select["exiart"]) != 0) {
			$db->uEx(uExiart($codd,$selBodegaant,$nuevaexist));
	    }

        # Para existencia Peps
		$select["exiarts_peps"] = $db->query(sExiartpeps($codd,$selBodegaant,$fvenced));
		$fetchAssoc["exiarts_peps"] = $db->fetchAssoc($select["exiarts_peps"]);
		if ($db->numRows($select["exiarts_peps"]) == 0) {
			$exiantspeps=0;
        } else {
          $exiantspeps=$fetchAssoc["exiarts_peps"]["ea_exist"];
        }
        $nuevaexistspeps=$exiantspeps+$cantd;
		if ($db->numRows($select["exiarts_peps"]) == 0) {
			$db->iEx(iExiartpeps($codd,$nuevaexistspeps,$selBodegaant,$loted,$fvenced,$cosud));
        } else {
			$db->uEx(uExiartpeps($codd,$nuevaexistspeps,$selBodegaant,$loted,$fvenced,$cosud));
        }

	}
	$db->dEx(dPolizas(0,$TdociRelatpol,$numdoc));
	$db->dEx(dPoli_det(0,$TdociRelatpol,$numdoc));
	// PARA APLICAR LOS CIERRES
	foreach ($jsonPolAnt as $obja) {
		$ctapol = $obja->pold_cta;
		$cta = $obja->pold_cta;
		$ctanom = $obja->pold_ctan;
		$debe = $obja->pold_debe;
		$haber = $obja->pold_haber;
		while (!empty($cta)) {
			$select["cuentas"] = $db->query(sCuentas($cta));
			$select["cierres"] = $db->query(sCierres($cta, $numAnioAnt, $numMesAnt));

			$fetchAssoc["cuentas"] = $db->fetchAssoc($select["cuentas"]);
			$ctaActa = trim($fetchAssoc["cuentas"]["cta_acta"]);

			if ($db->numRows($select["cierres"]) > 0) {
				$fetchAssoc["cierres"] = $db->fetchAssoc($select["cierres"]);
				$mdebe=$fetchAssoc["cierres"]["cie_mdebe"]-$obja->pold_debe;
				$mhaber=$fetchAssoc["cierres"]["cie_mhaber"]-$obja->pold_haber;

				$db->query(uCierres($cta, $numAnioAnt, $numMesAnt, $mdebe, $mhaber));
			} else {
				$mdebe=$obja->debe*-1;
				$mhaber=$obja->haber*-1;
				$db->query(iCierres($cta, $numAnioAnt, $numMesAnt, $mdebe, $mhaber));
			}
			$cta = $ctaActa;
		}
	}

	$resp = $db->dEx($dDoctoss);
	$db->dEx($dDocs_det);
	$db->dEx($dMovii);
	$db->dEx($dMoviipeps);
	//
	$db->iEx($func->iBitacora(utf8_decode("Se Borro El documento $TdociNom  Numero.: $numNum  Bodega: $selBodegaant Fecha: $dtFecant Usuario: ").$usuNom, $bitMod, $bitForm));
	$db->close();

	return json_encode($resp);
}

function consultarExist() {
	global $empCod;

	$func = new functions();

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

	# QUERYS
	$sExiart = "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$txtCodd' AND ea_bod='$selBodega'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sExiart, "exiart");
	$db->close();

	return json_encode($resp);
}

function consultarLisExispeps() {
	global $empCod;
	$txtCodd=utf8_decode($_POST['txtCodd']);
	$selBodega=utf8_decode($_POST['selBodega']);

	# QUERYS
	$sExiartpeps = "SELECT * FROM exiart_peps WHERE ea_emp='$empCod' AND ea_cod='$txtCodd' AND ea_bod='$selBodega' AND ea_exist>0 ORDER BY ea_emp,ea_cod,ea_fvence";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp["exiart_peps"] = $db->sFetchAll($sExiartpeps);
	$db->close();

	$func = new functions();

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


function consultarExistpeps() {
	global $empCod;

	$func = new functions();

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

	# QUERYS
	$sExiartpeps = "SELECT * FROM exiart_peps WHERE ea_emp='$empCod' AND ea_cod='$txtCodd' AND ea_bod='$selBodega' AND ea_fvence='$dtFvenced' ORDER BY ea_fvence";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sExiartpeps, "exiart_peps");
	$db->close();

	return json_encode($resp);
}


?>