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

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

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

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

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

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

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

	case 'generarPartida':
		echo generarPartida();
		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
	$sDoctose = "SELECT *, 
		TRIM(de.de_obs) AS de_obs
		FROM doctose de WHERE de_emp='$empCod' AND de_tipo='$selTdoci' AND de_num='$numNum'";

	$sDoce_det = "SELECT *, TRIM(art.art_ctacos) AS ded_ctacos, TRIM(art.art_ctainv) AS ded_ctainv
				FROM doce_det ded
 				LEFT JOIN artic art ON ded.ded_emp = art.art_emp AND ded.ded_cod=art.art_cod
				WHERE ded_emp='$empCod' AND ded_tipo='$selTdoci' AND ded_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($sDoctose, "doctose");
	$resp["doce_det"] = $db->sFetchAll($sDoce_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, 'doctose', 'doce_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'";
	}

	/* $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);
	
	$db->close();

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

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'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sExiartpeps, "exiart_peps");
	$db->close();

	return json_encode($resp);
}

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 generarPartida() {
	global $empCod, $piva, $ctainv, $TdociInveini;

	$jsonDetao=json_decode($_POST['tblDetao'], true);
	$ctainv=$_POST['ctainv'];
	$ctainvB2=$_POST['ctainvB2'];
	$selBodega=$_POST['selBodega'];
	$selBodega2=$_POST['selBodega2'];
	$TdociInveini=$_POST['TdociInveini'];
	$piva=$_POST['piva'];

	$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) {
		// Para tomar las cuentas de costo e inventario
		$cod = $rec["codd"];
        $bodega = $selBodega;
        $bodega2 = $selBodega2;
		$ctainv = $rec["ctainv"];
		$ctacos = $rec["ctacos"];
		$ctainv2 = $rec["ctainv"];
		$ctacos2 = $rec["ctacos"];
		$numtot = $rec["numtot"];

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

		// Para cuenta de Inventario Bodega Entra
		$i = $func->multiSearch($resp["ctaInv"], array('cta' => (string)$ctainv2));
		if ($i >= 0) {
 		    $resp["ctaInv"][$i]["cta_debe"] += $numtot;  
 		    ///$jsonDetao[$j]["numtot"];
		} else {
			$fa["ctaInv"] = $db->sFetchAssoc(sCuentas((string)$ctainv2,$numtot,0));
		    array_push($resp["ctaInv"], array("cta"=>$ctainv2,"cta_nom"=>$fa["ctaInv"]["cta_nom"],"cta_debe"=>$numtot,"cta_haber"=>$cero));
		}
		// Para cuenta de costos Bodega sale
		$i = $func->multiSearch($resp["ctaCos"], array('cta' => (string)$ctacos2));
		if ($i >= 0) {
			$resp["ctaCos"][$i]["cta_haber"] += $numtot;   
			///$jsonDetao[$j]["numtot"];
		} else {
			$fa["ctaCos"] = $db->sFetchAssoc(sCuentas((string)$ctacos2,0,$numtot));
		    array_push($resp["ctaCos"], array("cta"=>$ctacos2,"cta_nom"=>$fa["ctaCos"]["cta_nom"],"cta_debe"=>$cero,"cta_haber"=>$numtot));
		}
		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, $selBodega, $selBodega2, $txtCon, $sumtot, $piva, $TdociPartsn, $TdociRelatpol, $TdociAfecos, $TdociInveini, $crPror, $dtGrabado, $numTcam;

	$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'];
	$Bodeganom=$_POST['BodegaNom'];
	$selBodega2=$_POST['selBodega2'];
	$Bodeganom2=$_POST['BodegaNom2'];
	$Bodegaant=$_POST['Bodegaant'];
	$Bodegaant2=$_POST['Bodegaant2'];
	$numTcam=1.00;
	$crPror='N';
	$txtCon=$_POST['txtCon'];
	$sumtot=$_POST['sumtot'];
	$piva=$_POST['piva'];
	$jsonDetao=json_decode($_POST['tblDetao']);
	$jsonPol=json_decode($_POST['tblPol']);
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));
	$jsonPolAnt=json_decode($_POST['tblPolAnt']);
	$jsonDetaoAnt=json_decode($_POST['tblDetaoAnt']);
	$numAnio=date("Y", strtotime($dtFec));
	$numMes=date("n", strtotime($dtFec));
	$numAnioAnt=date("Y", strtotime($dtFecant));
	$numMesAnt=date("n", strtotime($dtFecant));

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

    $iDoctose="INSERT INTO doctose(de_emp, de_tipo, de_num, de_fec, de_fecapli, de_bodent, de_bodsal, de_tcam, de_obs, de_total, de_prorsn, de_ulcam) VALUES ('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$selBodega2','$selBodega','$numTcam','$txtCon', '$sumtot','$crPror','$usuNom')";

	$uDoctose="UPDATE doctose SET de_fec='$dtFec', de_fecapli='$dtFec', de_bodent='$selBodega2', de_bodsal='$selBodega', de_obs='$txtCon', de_total=$sumtot, de_ulcam='$usuNom' WHERE de_emp='$empCod' AND de_tipo='$selTdoci' AND de_num='$numNum'";

	$dDoce_det="DELETE FROM doce_det WHERE ded_emp='$empCod' AND ded_tipo='$selTdoci' AND ded_num='$numNum'";
	$dMovii="DELETE FROM movii WHERE mov_emp='$empCod' AND mov_tipo='$selTdoci' AND mov_num='$numNum'";

	function iDoce_det($codd, $descd, $cantd, $unimed, $medid, $cosud, $numtot) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $dtFec, $selBodega, $selBodega2, $numtcam, $txtCon, $sumtot, $crPror;
		return "INSERT INTO doce_det(ded_emp, ded_tipo, ded_num, ded_fec, ded_fecapli, ded_cod, ded_cant, ded_desc, ded_med, ded_unimed, ded_cosu, ded_cost, ded_exesn) VALUES('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$codd','$cantd','$descd','$unimed','$medid','$cosud','$numtot','N')";
	}

	function iMovii($codd, $cantd, $cosud, $precio) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $dtFec, $selBodega, $selBodega2, $numtcam, $txtCon, $sumtot, $crPror;
		return "INSERT INTO movii (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_fserie,mov_fnum) VALUES ('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$codd','$selBodega2','$selBodega','$cantd','$cantd','$cosud','$precio','',0)";
	}

	function uArtic($codd, $cosa, $cosr, $cosp) { 
		global $empCod, $usuNom, $dtFec;
		return "UPDATE artic SET art_cosa=$cosa, art_cosr=$cosr, art_cosp=$cosp, art_uent='$dtFec' WHERE art_emp='$empCod' AND art_cod='$codd'";
	}

	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;
		return "SELECT * FROM exiart WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}

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

	function uOrdendc($codd, $serieo, $numorden, $recibido) { 
		global $empCod, $usuNom, $selSerieo, $numOrdenc;
		return "UPDATE ordendc SET odd_crecibido=$recibido WHERE odd_emp='$empCod' AND odd_serie='$serieo' AND odd_num='$numorden' AND odd_cod='$codd'";
	}

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

	# 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") {

		// PARA REGISTRAR EL DOCUMENTO
		$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 {
		  if ($func->stringToBool($_POST['nuevo'])) {
		      //$numdoc=$fetchAssoc["corrtdoci"]["ctdi_corr"];
			  $nuevocorr=$numdoc+1;
			  $db->uEx(uCorrTdoci($nuevocorr));
	  	   }
		}

		$db->dEx($dDoce_det);
		$db->dEx($dMovii);
		if ($func->stringToBool($_POST['nuevo'])) {
			$resp= $db->iEx($iDoctose);
			$db->iEx($func->iBitacora(utf8_decode("Se creo El documento $TdociNom  Numero.: $numdoc de  Bodega: $selBodega a Bodega: $selBodega2  Fecha: $dtFec Usuario: ").$usuNom, $bitMod, $bitForm));
		} else {
			$resp= $db->uEx($uDoctose);
			$db->iEx($func->iBitacora(utf8_decode("Se modifico El documento $TdociNom  Numero.: $numdoc de  Bodega: $selBodega a Bodega: $selBodega2  Fecha: $dtFec Usuario: ").$usuNom, $bitMod, $bitForm));
		}
		// Para quitar lo que estaba antes # Esta parte se bloqueo porque abajo se recalcula
		foreach ($jsonDetaoAnt as $obja) {
			$codd = trim($obja->ded_cod);
			$descd = trim($obja->ded_desc);
			$unimed = $obja->ded_med;
			$medid = $obja->ded_unimed;
			$cantd = $obja->ded_cant;
			$cosud = $obja->ded_cosu;
			$numtot = $obja->ded_cost;
			$entra=$cantd;
			$sale=$cantd;
			$ivaud=0;
			$ivatot=0;

			$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,$Bodegaant2));
			$fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
			if ($db->numRows($select["exiart"]) == 0) {
				$exiante=0;
	        } else {
	           $exiante=$fetchAssoc["exiart"]["ea_exist"];
	        }
	        $nuevaexiste=$exiante-($cantd);

			$select["exiarts"] = $db->query(sExiart($codd,$Bodegaant));
			$fetchAssoc["exiarts"] = $db->fetchAssoc($select["exiarts"]);
			if ($db->numRows($select["exiarts"]) == 0) {
				$exiants=0;
	        } else {
	          $exiants=$fetchAssoc["exiarts"]["ea_exist"];
	        }
	        $nuevaexists=$exiants+$cantd;

			if ($bienser!='S') {
				if ($db->numRows($select["exiart"]) == 0) {
					$db->iEx(iExiart($codd,$nuevaexiste,$Bodegaant2));
		        } else {
					$db->uEx(uExiart($codd,$nuevaexiste,$Bodegaant2));
		        }
				if ($db->numRows($select["exiarts"]) == 0) {
					$db->iEx(iExiart($codd,$nuevaexists,$Bodegaant));
		        } else {
					$db->uEx(uExiart($codd,$nuevaexists,$Bodegaant));
		        }
		    }
		}   
	

		$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;
				}
			}
		}
		foreach ($jsonDetao as $obj) {
			$codd = trim($obj->codd);
			$descd = utf8_decode(trim($obj->descd));
			$unimed = $obj->unimed;
			$medid = $obj->medid;
			$cantd = $obj->cantd;
			$cosud = $obj->cosud;
			$nuevocosto = $obj->cosud;
			$numtot = $obj->numtot;
			$entra=$cantd;
			$sale=$cantd;
			$ivaud=0;
			$ivatot=0;

			$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"];

	        // Verifica Existencias anteriores en ambas bodegas
			$select["exiart"] = $db->query(sExiart($codd,$selBodega2));
			$fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
			if ($db->numRows($select["exiart"]) == 0) {
				$exiante=0;
	        } else {
	          $exiante=$fetchAssoc["exiart"]["ea_exist"];
	        }
	        $nuevaexiste=$exiante+$cantd;

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

	        // Registra el detalle
			$db->query(iDoce_det($codd, $descd, $cantd, $unimed, $medid, $cosud, $numtot));

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

				// Entrada
				if ($db->numRows($select["exiart"]) == 0) {
					$db->iEx(iExiart($codd,$nuevaexiste,$selBodega2));
	            } else {
					$db->uEx(uExiart($codd,$nuevaexiste,$selBodega2));
	            }
				// Salida
				if ($db->numRows($select["exiarts"]) == 0) {
					$db->iEx(iExiart($codd,$nuevaexists,$selBodega));
	            } else {
					$db->uEx(uExiart($codd,$nuevaexists,$selBodega));
	            } 

	            # Aqui se realculan las 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,$exisactu,$selBodega));

				# Para bodega2
				$select["moviie0"] = $db->query(sMoviie0($codd,$selBodega2));
				$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,$selBodega2));
				$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,$exisactu,$selBodega2));
				//
	        }
		}
		$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;
	//return $func->jsonEncodeArray($resp, "tipoabo");
	return json_encode($resp);
}

function anular() {
	global $empCod, $usuNom, $bitMod, $bitForm, $selTdoci, $TdociNom, $dtFec, $dtFecant,  $Bodegaant, $Bodegaant2, $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'];
	$Bodegaant=$_POST['Bodegaant'];
	$Bodegaant2=$_POST['Bodegaant2'];
	$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']);
	$anu='**** ANULADO ****';
	$valcero=0;

	# QUERYS PARA UN REGISTRO

	$uDoctose="UPDATE doctose SET de_numoc=0, de_obs='$anu', de_total=0, de_ulcam='$usuNom' WHERE de_emp='$empCod' AND de_tipo='$selTdoci' AND de_num='$numNum'";

	$uDoce_det="UPDATE doce_det SET ded_cant=0, ded_boni=0, ded_cosu=0, ded_cost=0, ded_stat='A' WHERE ded_emp='$empCod' AND ded_tipo='$selTdoci' AND ded_num='$numNum'";

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

	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, $nexist, $bodega) { 
		global $empCod, $usuNom, $selBodega;
		return "UPDATE exiart SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}
	
	# EJECUCION DE QUERYS 
	$db = new dbExec();

	// Para quitar lo que estaba antes
	foreach ($jsonDetaoAnt as $obja) {
		$codd = trim($obja->ded_cod);
		$descd = trim($obja->ded_desc);
		$unimed = $obja->ded_med;
		$medid = $obja->ded_unimed;
		$cantd = $obja->ded_cant;
		$cosud = $obja->ded_cosu;
		$numtot = $obja->ded_cost;
		$entra=$cantd;
		$sale=$cantd;
		$ivaud=0;
		$ivatot=0;

		$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,$Bodegaant2));
		$fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
		if ($db->numRows($select["exiart"]) == 0) {
			$exiante=0;
        } else {
           $exiante=$fetchAssoc["exiart"]["ea_exist"];
        }
        $nuevaexiste=$exiante-($cantd);

		$select["exiarts"] = $db->query(sExiart($codd,$Bodegaant));
		$fetchAssoc["exiarts"] = $db->fetchAssoc($select["exiarts"]);
		if ($db->numRows($select["exiarts"]) == 0) {
			$exiants=0;
        } else {
          $exiants=$fetchAssoc["exiarts"]["ea_exist"];
        }
        $nuevaexists=$exiants+$cantd;

		if ($bienser!='S') {
			if ($db->numRows($select["exiart"]) == 0) {
				$db->iEx(iExiart($codd,$nuevaexiste,$Bodegaant2));
	        } else {
				$db->uEx(uExiart($codd,$nuevaexiste,$Bodegaant2));
	        }
			if ($db->numRows($select["exiarts"]) == 0) {
				$db->iEx(iExiart($codd,$nuevaexists,$Bodegaant));
	        } else {
				$db->uEx(uExiart($codd,$nuevaexists,$Bodegaant));
	        }
	    }
	}

	$resp = $db->anEx($uDoctose);
	$db->uEx($uDoce_det);
	$db->uEx($uMovii);
	//
	$db->iEx($func->iBitacora(utf8_decode("Se Anulo El documento $TdociNom  Numero.: $numNum  Bodega: $Bodegaant2 a  $Bodegaant Fecha: $dtFecant Usuario: ").$usuNom, $bitMod, $bitForm));
	$db->close();

	return json_encode($resp);
}

function borrar() {
	global $empCod, $usuNom, $bitMod, $bitForm, $selTdoci, $TdociNom, $dtFec, $dtFecant,  $Bodegaant, $Bodegaant2, $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'];
	$Bodegaant=$_POST['Bodegaant'];
	$Bodegaant2=$_POST['Bodegaant2'];
	$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']);
	$anu='**** ANULADO ****';
	$valcero=0;

	# QUERYS PARA UN REGISTRO


	$dDoctose="DELETE FROM doctose WHERE de_emp='$empCod' AND de_tipo='$selTdoci' AND de_num='$numNum'";

	$dDoce_det="DELETE FROM doce_det WHERE ded_emp='$empCod' AND ded_tipo='$selTdoci' AND ded_num='$numNum'";

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

	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, $nexist, $bodega) { 
		global $empCod, $usuNom, $selBodega;
		return "UPDATE exiart SET ea_exist='$nexist' WHERE ea_emp='$empCod' AND ea_cod='$codd' AND ea_bod='$bodega'";
	}
	
	# EJECUCION DE QUERYS 
	$db = new dbExec();

	// Para quitar lo que estaba antes
	foreach ($jsonDetaoAnt as $obja) {
		$codd = trim($obja->ded_cod);
		$descd = trim($obja->ded_desc);
		$unimed = $obja->ded_med;
		$medid = $obja->ded_unimed;
		$cantd = $obja->ded_cant;
		$cosud = $obja->ded_cosu;
		$numtot = $obja->ded_cost;
		$entra=$cantd;
		$sale=$cantd;
		$ivaud=0;
		$ivatot=0;

		$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,$Bodegaant2));
		$fetchAssoc["exiart"] = $db->fetchAssoc($select["exiart"]);
		if ($db->numRows($select["exiart"]) == 0) {
			$exiante=0;
        } else {
           $exiante=$fetchAssoc["exiart"]["ea_exist"];
        }
        $nuevaexiste=$exiante-($cantd);

		$select["exiarts"] = $db->query(sExiart($codd,$Bodegaant));
		$fetchAssoc["exiarts"] = $db->fetchAssoc($select["exiarts"]);
		if ($db->numRows($select["exiarts"]) == 0) {
			$exiants=0;
        } else {
          $exiants=$fetchAssoc["exiarts"]["ea_exist"];
        }
        $nuevaexists=$exiants+$cantd;

		if ($bienser!='S') {
			if ($db->numRows($select["exiart"]) == 0) {
				$db->iEx(iExiart($codd,$nuevaexiste,$Bodegaant2));
	        } else {
				$db->uEx(uExiart($codd,$nuevaexiste,$Bodegaant2));
	        }
			if ($db->numRows($select["exiarts"]) == 0) {
				$db->iEx(iExiart($codd,$nuevaexists,$Bodegaant));
	        } else {
				$db->uEx(uExiart($codd,$nuevaexists,$Bodegaant));
	        }
	    }
	}
	$resp = $db->dEx($dDoctose);
	$db->dEx($dDoce_det);
	$db->dEx($dMovii);
	//
	$db->iEx($func->iBitacora(utf8_decode("Se Borro El documento $TdociNom  Numero.: $numNum  Bodega: $Bodegaant2 a $Bodegaant  Fecha: $dtFecant Usuario: ").$usuNom, $bitMod, $bitForm));
	$db->close();

	return json_encode($resp);
}


?>