 <?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 = "inv1040";
$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 'consultarCorr':
		echo consultarCorr();
		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'];

	# QUERYS
	$sInvefis = "SELECT *, 
		TRIM(inf.if_obs) AS if_obs
		FROM invefis inf WHERE if_emp='$empCod' AND if_tipo='$selTdoci' AND if_num='$numNum'";

	$sInvef_det = "SELECT *
				FROM invefdet infd
 				LEFT JOIN artic art ON infd.infd_emp = art.art_emp AND infd.infd_cod=art.art_cod
				WHERE infd_emp='$empCod' AND infd_tipo='$selTdoci' AND infd_num='$numNum'";


	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sInvefis, "invefis");
	$resp["invefdet"] = $db->sFetchAll($sInvef_det);
	$db->close();

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


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;

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

	/* $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 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 guardar() {
	global $empCod, $usuNom, $bitMod, $bitForm, $numNum, $numdoc, $selTdoci, $TdociNom, $dtFec, $dtFecant, $selBodega, $selBodegaant, $txtCon, $numAnio, $numMes, $numAnioAnt, $numMesAnt;

	$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'];
	$dtFec=$_POST['dtFec'];
	$dtFecant=$_POST['dtFecant'];
	$selBodega=$_POST['selBodega'];
	$selBodegaant=$_POST['selBodegaant'];
	$Bodeganom=$_POST['BodegaNom'];
	$txtCon=$_POST['txtCon'];
	$jsonDetao=json_decode($_POST['tblDetao']);
	$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));
	$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'";
	}

	$iInvefis="INSERT INTO invefis(if_emp, if_tipo, if_num, if_fec, if_fecapli, if_bod, if_obs, if_ulcam) VALUES ('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$selBodega','$txtCon','$usuNom')";


	$uInvefis="UPDATE invefis SET if_fec='$dtFec', if_fecapli='$dtFec', if_bod='$selBodega', if_obs='$txtCon', if_ulcam='$usuNom' WHERE if_emp='$empCod' AND if_tipo='$selTdoci' AND if_num='$numNum'";

	$dInvef_det="DELETE FROM invefdet WHERE infd_emp='$empCod' AND infd_tipo='$selTdoci' AND infd_num='$numNum'";

	function iInvef_det($codd, $descd, $cantd, $unimed, $medid) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $dtFec, $selBodega, $txtCon;
		return "INSERT INTO invefdet(infd_emp, infd_tipo, infd_num, infd_fec, infd_fecapli, infd_cod, infd_cant, infd_desc, infd_med, infd_unimed) VALUES('$empCod','$selTdoci','$numNum','$dtFec','$dtFec','$codd','$cantd','$descd','$unimed','$medid')";
	}

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


	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$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"];
	  $nuevocorr=$numdoc+1;
	  $db->uEx(uCorrTdoci($nuevocorr));
	}
		
	// PARA REGISTRAR EL DOCUMENTO
	$db->dEx($dInvef_det);
	if ($func->stringToBool($_POST['nuevo'])) {
		$resp= $db->iEx($iInvefis);
		$db->iEx($func->iBitacora(utf8_decode("Se creo La Toma Fisica $TdociNom  Numero.: $numdoc de  Bodega: $selBodega Fecha: $dtFec Usuario: ").$usuNom, $bitMod, $bitForm));
	} else {
		$resp= $db->uEx($uInvefis);
		$db->iEx($func->iBitacora(utf8_decode("Se Modifico La Toma Fisica $TdociNom  Numero.: $numdoc  Bodega: $selBodegaant Fecha: $dtFecant Usuario: ").$usuNom, $bitMod, $bitForm));
	}

    // 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;
		$sale=$cantd;
        // Registra el detalle
		$db->query(iInvef_det($codd, $descd, $cantd, $unimed, $medid));
	}
	$db->close();
	
	$resp["dtGrabado"]=$dtGrabado;
	$resp["numdoc"]=$numdoc;
	//$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;

	$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'];
	$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']);
	$anu='**** ANULADO ****';
	$valcero=0;

	# QUERYS PARA UN REGISTRO


	$uInvefis="UPDATE invefis SET if_obs='$anu', if_ulcam='$usuNom' WHERE if_emp='$empCod' AND if_tipo='$selTdoci' AND if_num='$numNum'";

	$uInvef_det="UPDATE invef_det SET infd_cant=0 WHERE infd_emp='$empCod' AND infd_tipo='$selTdoci' AND infd_num='$numNum'";
	
	# QUERYS PARA VARIOS REGISTROS

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$resp = $db->anEx($uInvefis);
	$db->uEx($uInvef_det);
	//
	$db->iEx($func->iBitacora(utf8_decode("Se Anulo La Toma Fisica $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;

	$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'];
	$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']);
	$anu='**** ANULADO ****';
	$valcero=0;

	# QUERYS PARA UN REGISTRO


	$dInvefis="DELETE FROM invefis WHERE if_emp='$empCod' AND if_tipo='$selTdoci' AND if_num='$numNum'";
	$dInvef_det="DELETE FROM invefdet WHERE infd_emp='$empCod' AND infd_tipo='$selTdoci' AND infd_num='$numNum'";

	
	# QUERYS PARA VARIOS REGISTROS

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$resp = $db->dEx($dInvefis);
	$db->dEx($dInvef_det);
	//
	$db->iEx($func->iBitacora(utf8_decode("Se Borro La Toma Fisica $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);
}


?>