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

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

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

	case 'consultarArtic':
		echo consultarArtic();
		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 'procesar':
		echo procesar();
		break;

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

	case 'datosbase':
		echo datosbase();
		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'];

	# QUERYS
	$sProrrat = "SELECT * FROM prorrat WHERE prt_emp='$empCod' AND prt_num='$numNum'";

	$sPrt_det1 = "SELECT *, TRIM(art.art_ctacos) AS pd1_ctacos, TRIM(art.art_ctainv) AS pd1_ctainv 
				 FROM prt_det1 pd1 LEFT JOIN artic art ON pd1.pd1_emp=art.art_emp AND pd1.pd1_codpro=art.art_cod 
				 WHERE pd1_emp='$empCod' AND pd1_num='$numNum'";

	$sPrt_detc = "SELECT * FROM prt_detc WHERE prdc_emp='$empCod' AND prdc_num='$numNum'";

	$sPrt_detf = "SELECT * FROM prt_detf WHERE prdf_emp='$empCod' AND prdf_num='$numNum'";

	$sPrt_partida = "SELECT * FROM prt_partida WHERE pold_emp='$empCod' AND pold_num='$numNum'";

	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sProrrat, "prorrat");
	$resp["prt_det1"] = $db->sFetchAll($sPrt_det1);
	$resp["prt_detc"] = $db->sFetchAll($sPrt_detc);
	$resp["prt_detf"] = $db->sFetchAll($sPrt_detf);
	$resp["prt_partida"] = $db->sFetchAll($sPrt_partida);
	$db->close();

	$func = new functions();
	//return $func->jsonEncodeArray($resp, array('abonos', 'poli_det', 'abo_det'));
	return $func->jsonEncodeArray($resp, 'prorrat', 'prt_det1', 'prt_detc', 'prt_detf', 'prt_partida');
}

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

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

	$func = new functions();

	# QUERYS
	$sProrgas1 = "SELECT *, TRIM(prg_cod) AS prg_cod, TRIM(prg_nom) AS prg_nom FROM prorgas WHERE prg_tipo='C'";

	$sProrgas2 = "SELECT *, TRIM(prg_cod) AS prg_cod, TRIM(prg_nom) AS prg_nom FROM prorgas WHERE prg_tipo='F'";

	# EJECUCION DE QUERYS
	$db = new dbExec();
	//$resp = $db->sEx($sDoctose, "doctose");
	$resp["prorgas1"] = $db->sFetchAll($sProrgas1);
	$resp["prorgas2"] = $db->sFetchAll($sProrgas2);
	$db->close();

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

function consultarimpor() {
	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
	$sDoctose = "SELECT *, TRIM(de_obs) AS de_obs, TRIM(de_bodent) AS de_bodent FROM doctose
				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'";

	$sDoce_detsum = "SELECT *, SUM(ded_cant) AS ded_sumcant FROM doce_det
				WHERE ded_emp='$empCod' AND ded_tipo='$selTdoci' AND ded_num='$numNum' GROUP BY ded_emp,ded_tipo,ded_num";

	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sDoctose, "doctose");
	$resp["doce_detsum"] = $db->sFetchAssoc($sDoce_detsum);
	$resp["doce_det"] = $db->sFetchAll($sDoce_det);
	$db->close();

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

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

	$func = new functions();
	# QUERYS
	$sprtcorr = "SELECT * FROM prtcorr WHERE pc_emp='$empCod'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp["prtcorr"] = $db->sFetchAssoc($sprtcorr);
	$db->close();

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

function consultarProvcp() {
	global $empCod;
	$txtCod=utf8_decode($_POST['txtCod']);

	# QUERYS
	$sProvcp = "SELECT *, TRIM(pro_nom) AS pro_nom, TRIM(pro_retsn) AS pro_retsn FROM provcp WHERE pro_emp='$empCod' AND pro_cod='$txtCod'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sProvcp, "provcp");
	$db->close();

	$func = new functions();

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

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

	$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"] = TRIM($rec["ctainv"]);
		$i = $func->multiSearch($resp["ctaInv"], array('cta' => (string)$rec["ctainv"]));
		if ($i >= 0) {
			$resp["ctaInv"][$i]["cta_debe"] += $jsonDetao[$j]["total"];
		} else {
			$fa["ctaInv"] = $db->sFetchAssoc(sCuentas((string)$rec['ctainv'],$rec['total'],0));
		    array_push($resp["ctaInv"], array("cta"=>$rec["ctainv"],"cta_nom"=>$fa["ctaInv"]["cta_nom"],"cta_debe"=>$rec['total'],"cta_haber"=>$cero));
		}
		// 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_haber"] += $jsonDetao[$j]["total"];
		} else {
			$fa["ctaCos"] = $db->sFetchAssoc(sCuentas((string)$rec['ctacos'],0,$rec['total']));
		    array_push($resp["ctaCos"], array("cta"=>$rec["ctacos"],"cta_nom"=>$fa["ctaCos"]["cta_nom"],"cta_debe"=>$cero,"cta_haber"=>$rec['total']));
		}
		unset($jsonDetao[$j]);
		$j++;
	}
	$db->close();

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


function guardar() {
	global $empCod, $usuNom, $bitMod, $bitForm, $selTdoci, $TdociNom, $dtFec,  $numImpor, $numTcam, $numAnio, $numMes, $numNum;

	$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'];
	$numImpor=$_POST['numImpor'];
	$bodega=$_POST['bodega'];
	$dtFec=$_POST['dtFec'];
	$numTcam=$_POST['numTcam'];
	$jsonDetao=json_decode($_POST['tblDetao']);
	$jsonDetaG1=json_decode($_POST['tblDetaG1']);
	$jsonDetaG2=json_decode($_POST['tblDetaG2']);
	$jsonPol=json_decode($_POST['tblPol']);
	$numAnio=date("Y", strtotime($dtFec));
	$numMes=date("n", strtotime($dtFec));
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));

	# QUERYS PARA UN REGISTRO
	$sPrtCorr = "SELECT * FROM prtcorr WHERE pc_emp='$empCod'";

	function iPrtCorr($nuevocorr) { 
		global $empCod, $usuNom;
		return "INSERT INTO prtcorr(pc_emp, pc_corr) VALUES ('$empCod',$nuevocorr)";
	}
	function uPrtCorr($nuevocorr) { 
		global $empCod, $usuNom;
		return "UPDATE prtcorr SET pc_corr=$nuevocorr WHERE pc_emp='$empCod'";
	} 

	/*function iDoctose($numdoc) { 
		global $empCod, $usuNom, $selTdoci, $dtFec, $selBodega, $numTcam, $selSerieo, $numOrdenc, $txtCon, $sumtot, $crPror;
		return "INSERT INTO doctose(de_emp, de_tipo, de_num, de_fec, de_fecapli, de_bodent, de_tcam, de_serieoc, de_numoc, de_obs, de_total, de_prorsn, de_ulcam) VALUES ('$empCod','$selTdoci','$numdoc','$dtFec','$dtFec','$selBodega','$numTcam','$selSerieo','$numOrdenc','$txtCon', '$sumtot','$crPror','$usuNom')";
	} */

	$iProrrat="INSERT INTO prorrat(prt_emp, prt_num, prt_tcam, prt_fec, prt_tipod, prt_numd, prt_bodega, prt_ulcam) VALUES ('$empCod','$numNum','$numTcam','$dtFec','$selTdoci','$numImpor','$bodega', '$usuNom')";

	$uProrrat="UPDATE prorrat SET prt_fec='$dtFec', prt_tcam='$numTcam', prt_tipod='$selTdoci', prt_numd='$numImpor', prt_bodega='$bodega', prt_ulcam='$usuNom' WHERE prt_emp='$empCod' AND prt_num='$numNum'";

	$dPrt_det1="DELETE FROM prt_det1 WHERE pd1_emp='$empCod' AND pd1_num='$numNum'";
	$dPrt_detc="DELETE FROM prt_detc WHERE prdc_emp='$empCod' AND prdc_num='$numNum'";
	$dPrt_detf="DELETE FROM prt_detf WHERE prdf_emp='$empCod' AND prdf_num='$numNum'";
	$dPrt_partida="DELETE FROM prt_partida WHERE pold_emp='$empCod' AND pold_num='$numNum'";


	function iPrt_det1($codd, $descd, $cantd, $cosuq, $totq, $distrib, $gastos, $dai, $total, $cosunit) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $numImpor, $dtFec;
		return "INSERT INTO prt_det1(pd1_emp, pd1_num, pd1_tipod, pd1_numd, pd1_codpro, pd1_desc, pd1_cant, pd1_cosu, pd1_tfobq, pd1_pord, pd1_gastq, pd1_dai, pd1_vtotal, pd1_costuq) VALUES('$empCod','$numNum','$selTdoci','$numImpor','$codd','$descd','$cantd','$cosuq','$totq','$distrib','$gastos','$dai','$total','$cosunit')";
	}

	function iPrt_detc($tipog, $nomg, $vald) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $numImpor, $dtFec;
		return "INSERT INTO prt_detc(prdc_emp, prdc_num, prdc_tipog, prdc_nomg, prdc_vald) VALUES('$empCod','$numNum','$tipog','$nomg','$vald')";
	}

	function iPrt_detf($tipog, $nomg, $valq) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $numImpor, $dtFec;
		return "INSERT INTO prt_detf(prdf_emp, prdf_num, prdf_tipog, prdf_nomg, prdf_valq) VALUES('$empCod','$numNum','$tipog','$nomg','$valq')";
	}

	function iPrt_partida($cta, $ctanom, $debe, $haber) { 
		global $empCod, $usuNom, $numNum, $selTdoci, $numImpor, $dtFec;
		return "INSERT INTO prt_partida(pold_emp, pold_num, pold_cta, pold_ctan, pold_debe, pold_haber) VALUES('$empCod','$numNum','$cta','$ctanom','$debe','$haber')";
	}

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

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	// Revisa si hay algun problema en la partida, para ver si permite grabar o no
	$probpol1="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 ($probpol1 == "X") {
		// Cambiar Correlativo
		$select["prtcorr"] = $db->query($sPrtCorr);
		$fetchAssoc["prtcorr"] = $db->fetchAssoc($select["prtcorr"]);
		if ($db->numRows($select["prtcorr"]) == 0) {
		  //$numdoc=1;
		  $nuevocorr=$numdoc+1;
		  $db->iEx(iPrtCorr($nuevocorr));
		} else {
          //$numdoc=$fetchAssoc["corrtdoci"]["ctdi_corr"];
		  $nuevocorr=$numdoc+1;
		  $db->uEx(uPrtCorr($nuevocorr));
		}
		// PARA REGISTRAR EL DOCUMENTO
		$db->dEx($dPrt_det1);
		$db->dEx($dPrt_detc);
		$db->dEx($dPrt_detf);
		$db->dEx($dPrt_partida);

		if ($func->stringToBool($_POST['nuevo'])) {
			$resp = $db->iEx($iProrrat);
			$db->query($func->iBitacora(utf8_decode("Se creó Prorrateo No.: $numNum  Usuario: ").$usuNom, $bitMod, $bitForm));
		} else {
			$resp = $db->uEx($uProrrat);
			$db->query($func->iBitacora(utf8_decode("Se modificó Prorrateo No.: $numNum Usuario: ").$usuNom, $bitMod, $bitForm));
		}

        // Para aplicar lo que se modifico
		foreach ($jsonDetao as $obj) {
			$codd = trim($obj->codd);
			$descd = trim($obj->descd);
			$cantd = $obj->cantd;
			$cosuq = $obj->cosuq;
			$totq = $obj->totq;
			$distrib = $obj->distrib;
			$gastos = $obj->gastos;
			$dai=$obj->dai;
			$total=$obj->total;
			$cosunit=$obj->cosunit;
            // Registra el detalle
			$db->query(iPrt_det1($codd, $descd, $cantd, $cosuq, $totq, $distrib, $gastos, $dai, $total, $cosunit));
		}
		foreach ($jsonDetaG1 as $objg1) {
			$codg1 = trim($objg1->codg1);
			$descg1 = trim($objg1->descg1);
			$valg1 = $objg1->valg1;
            // Registra el detalle G1
			$db->query(iPrt_detc($codg1, $descg1, $valg1));
		}
		foreach ($jsonDetaG2 as $objg2) {
			$codg2 = trim($objg2->codg2);
			$descg2 = trim($objg2->descg2);
			$valg2 = $objg2->valg2;
            // Registra el detalle G2
			$db->query(iPrt_detf($codg2, $descg2, $valg2));
		}
		foreach ($jsonPol as $objpol) {
			$cta = trim($objpol->cta);
			$ctanom = trim($objpol->ctaNom);
			$debe = $objpol->debe;
			$haber = $objpol->haber;
            // Registra el detalle Partida
			$db->query(iPrt_partida($cta, $ctanom, $debe, $haber));
		}
	}
	//$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 procesar() {
	global $empCod, $usuNom, $bitMod, $bitForm, $Tipopol, $numNum, $numdoc, $numAnio, $numMes, $dtGrabado;

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

	$func = new functions();

	$numNum=$_POST['numNum'];
	$numdoc=$_POST['numNum'];
	$dtFec=$_POST['dtFec'];
    $Tipopol="0030";
	$numAnio=date("Y", strtotime($dtFec));
	$numMes=date("n", strtotime($dtFec));
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));

	# QUERYS PARA UN REGISTRO
	$sProrrat = "SELECT * FROM prorrat WHERE prt_emp='$empCod' AND prt_num='$numNum'";

	$sPrt_det1 = "SELECT * FROM prt_det1 WHERE pd1_emp='$empCod' AND pd1_num='$numNum'";

	$sPrt_partida = "SELECT * FROM prt_partida WHERE pold_emp='$empCod' AND pold_num='$numNum'";

	$uProrrat = "UPDATE prorrat SET prt_stat='P' WHERE prt_emp='$empCod' AND prt_num='$numNum'";

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

	function uArtic($codd, $cosa, $cosr, $cosp) { 
		global $empCod, $usuNom;
		return "UPDATE artic SET art_cosa=$cosa, art_cosr=$cosr, art_cosp=$cosp 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 sMoviis0($codd, $fecha, $bodega) { 
	    global $empCod, $usuNom, $selBodega, $dtFec;
	    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' AND mov_fec>='$fecha' GROUP BY '$empCod','$codd'";
	}
	function sMoviie0($codd, $fecha, $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' AND mov_fec>='$fecha' GROUP BY '$empCod','$codd'";
	}

	function uDoctose($tipod, $numd) { 
		global $empCod, $usuNom, $numNum;
		return "UPDATE doctose SET de_proya='S', de_nprorrateo='$numNum' WHERE de_emp='$empCod' AND de_tipo='$tipod' AND de_num='$numd'";
	}

	# QUERY PARA POLIZA
	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) 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) VALUES ('$empCod','$fecha','$banco','$tipo','$numero','$cta','$ctan','$debe','$haber')";
	}


	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$select["prorrat"] = $db->query($sProrrat);
	$select["prt_det1"] = $db->query($sPrt_det1);
	$select["prt_partida"] = $db->query($sPrt_partida);

	$rec = $db->fetchAssoc($select["prorrat"]);
    $fecha=$rec["prt_fec"];
    $bodega=$rec["prt_bodega"];
    $tipod=$rec["prt_tipod"];
    $numd=$rec["prt_numd"];
	while ($recDet = $db->fetchAssoc($select["prt_det1"])) {
		$codd=$recDet["pd1_codpro"];
		$cant=$recDet["pd1_cant"];
		$costuq=$recDet["pd1_costuq"];
		$costotq=round($cant*$costuq,5);

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

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

		  $select["movii"] = $db->query(sMoviis0($codd,$fecha,$bodega));
		  $recms0 = $db->fetchAssoc($select['movii']);
		  $sSalemov=$recms0["mov_ssale"];

		  $select["movii"] = $db->query(sMoviie0($codd,$fecha,$bodega));
		  $recme0 = $db->fetchAssoc($select['movii']);
		  $sEntramov=$recme0["mov_sentra"];
		  $exiant=($exiant+$sSalemov)-$sEntramov;
        }
        if ($exiant<=0) {
           $nuevocosp=$costuq;
           $nuevocosr=$costuq;
           $nuevocosa=$antcosp;
        } else {
           if ($antcosp>0) {
              $anttot=round($exiant*$antcosp,5);
              $sumcostos=round($anttot+$costotq,5);
              $sumexis=$cant+$exiant;
              $nuevocosp=round($sumcostos/$sumexis,5);
  			  $nuevocosr=$costuq;
  			  $nuevocosa=$antcosp;
           } else {
	          $nuevocosp=$costuq;
	          $nuevocosr=$costuq;
	          $nuevocosa=$antcosp;
		   }
        }
    	$db->uEx(uArtic($codd, $nuevocosa, $nuevocosr, $nuevocosp));
	}
    $db->uEx($uProrrat);
    $db->uEx(uDoctose($tipod,$numd));
	$db->iEx($func->iBitacora(utf8_decode("Se Procceso Prorrateo Numero.: $numNum Usuario: ").$usuNom, $bitMod, $bitForm));
	// Para registrar la poliza
    $db->dEx(dPolizas(0,$Tipopol,$numdoc));
	$db->dEx(dPoli_det(0,$Tipopol,$numdoc));
	while ($recDetpart = $db->fetchAssoc($select["prt_partida"])) {
		$ctapol=$recDetpart["pold_cta"];
		$cta=$recDetpart["pold_cta"];
		$ctanom=$recDetpart["pold_ctan"];
		$debe=$recDetpart["pold_debe"];
		$haber=$recDetpart["pold_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"]+$recDetpart["pold_debe"];
				$mhaber=$fetchAssoc["cierres"]["cie_mhaber"]+$recDetpart["pold_haber"];

				$db->query(uCierres($cta, $numAnio, $numMes, $mdebe, $mhaber));
			} else {
				$mdebe=$recDetpart["pold_debe"];
				$mhaber=$recDetpart["pold_haber"];
				$db->query(iCierres($cta, $numAnio, $numMes, $mdebe, $mhaber));
			}
			$cta = $ctaActa;
		}
		$db->iEx(iPoli_det($fecha,0,$Tipopol,$numNum,$ctapol,$ctanom,$debe,$haber));
	}

	$db->iEx(iPolizas($fecha,0,$Tipopol,$numNum));
	//$resp["tipoabo"] = $db->query($sTipoabo);
	$db->close();
	
	$resp["dtGrabado"]=$dtGrabado;
	//$resp["TdociAfecos"]=$TdociAfecos;
	//$resp["TdociInveini"]=$TdociInveini;
	//return $func->jsonEncodeArray($resp, "tipoabo");
	return json_encode($resp);
}

function borrar() {
	global $empCod, $usuNom, $bitMod, $bitForm, $numNum;

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

	$func = new functions();

	$numNum=$_POST['numNum'];
	$numdoc=$_POST['numNum'];

	# QUERYS PARA UN REGISTRO

	$dProrrat="DELETE FROM prorrat WHERE prt_emp='$empCod' AND prt_num='$numNum'";
	$dPrt_det1="DELETE FROM prt_det1 WHERE pd1_emp='$empCod' AND pd1_num='$numNum'";
	$dPrt_detc="DELETE FROM prt_detc WHERE prdc_emp='$empCod' AND prdc_num='$numNum'";
	$dPrt_detf="DELETE FROM prt_detf WHERE prdf_emp='$empCod' AND prdf_num='$numNum'";
	$dPrt_partida="DELETE FROM prt_partida WHERE pold_emp='$empCod' AND pold_num='$numNum'";

	
	# QUERYS PARA VARIOS REGISTROS

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$resp = $db->dEx($dProrrat);
	$db->dEx($dPrt_det1);
	$db->dEx($dPrt_detc);
	$db->dEx($dPrt_detf);
	$db->dEx($dPrt_partida);
	//
	$db->iEx($func->iBitacora(utf8_decode("Se Borro El Prorrateo Numero.: $numNum Usuario: ").$usuNom, $bitMod, $bitForm));
	$db->close();

	return json_encode($resp);
}

function cerrarorden() {
	global $empCod, $usuNom, $bitMod, $bitForm;

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

	$func = new functions();

	$numNum=$_POST['numNum'];
	$selSerieo=$_POST['selSerieo'];
	$selSerieoNom=$_POST['selSerieoNom'];
	$statn='C';

	# QUERYS PARA UN REGISTRO

	$uOrdenc = "UPDATE ordenc SET od_stat='$statn' WHERE od_emp='$empCod' AND od_serie='$selSerieo' AND od_num='$numNum'";

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

	$resp = $db->uEx($uOrdenc);

	//
	$db->iEx($func->iBitacora(utf8_decode("Se Cerro Orden de Compra Serie $selSerieoNom  No.: $numNum  Usuario: ").$usuNom, $bitMod, $bitForm));

	$db->close();

	return json_encode($resp);
}

?>