<?php
include_once('../../../php/sessionStart.php');
include_once('../../../php/db/dbExec.php');
include_once('../../../php/functions.php');
include_once('../../../php/timezone.php');
include_once('../../../php/privileges.php');
include_once('../../../php/maxExecTime.php');

include_once('../ws/fel/clases.php');

$bitForm = "pov1025";
$bitMod = "pov";
$empCod = $_SESSION['empCod'];
$empConso = $_SESSION['empConso'];
$empNit = $_SESSION['empNit'];
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);
$tipoPol='010';
$pCaja = utf8_decode($_SESSION['pCaja']);

$dtFec=date("Y-m-d");

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

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

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

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

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

}


function consultarCliencc() {
	global $empCod;

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

	$txtCliCod = $_POST["txtCliCod"];

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

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

function consultarCiemes() {
	global $empCod;

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

	$func = new functions();
	$numAno=$_POST["numAno"];
	$selMesCod=$_POST["selMesCod"];

	# QUERYS
	$sCiemes = "SELECT ciem_stat FROM ciemes WHERE ciem_emp='$empCod' AND ciem_ano=$numAno AND ciem_mes=$selMesCod";

	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sCiemes, "ciemes");
	$db->close();

	return json_encode($resp);
}

function consultar() {
	global $empCod, $usuNom, $tipoPol;

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

	$func = new functions();

	$tipoPol="010";
	$selTipoCod=$_POST['selTipoCod'];
	$selTipoAbrev=$_POST['selTipoAbrev'];
	$numInterno=$_POST['numInterno'];

	# QUERYS
	$sFacturas = "SELECT
					f.*,
					c.ciem_stat,
					TRIM(f.fact_documentguid) AS fact_documentguid,
					TRIM(f.fact_guardado) AS fact_guardado,
					TRIM(cli.cli_nom) AS cli_nom,
					TRIM(cli.cli_cta) AS cli_cta
				  FROM facturas f 
				  LEFT JOIN ciemes c ON c.ciem_mes=MONTH(f.fact_fec) AND c.ciem_ano=YEAR(f.fact_fec) AND c.ciem_emp='$empCod'
				  LEFT JOIN cliencc cli ON cli.cli_emp='$empCod' AND cli.cli_cod=f.fact_codp
				  WHERE fact_emp='$empCod' AND fact_idinterno='$numInterno'";

	function sFact_det($IDInterno) {
		return "SELECT * FROM fact_det WHERE factd_idinterno='$IDInterno'";
	}

	function sPoli_det($num,$serie) {
		global $empCod, $tipoPol;
		return "SELECT * FROM poli_det WHERE pold_emp='$empCod' AND pold_tipo='$tipoPol' AND pold_num='$num' AND pold_tipoi='$serie'";
	}
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sFacturas, "facturas");
	$resp["fact_det"] = ($resp["facturas"]!=null) ? $db->sFetchAll(sFact_det($resp["facturas"]["fact_idinterno"])) : array();
	$serie=$resp["facturas"]["fact_serie"];
	$num=$resp["facturas"]["fact_num"];

	$resp["poli_det"] = $db->sFetchAll(sPoli_det($num,$serie));

	$db->close();

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

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

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

	$func = new functions();

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

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

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

	$db->close();

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


function anular() {
	global $empCod, $empNit, $usuNom, $bitMod, $bitForm, $dtFec, $tipoPol, $db, $func, $dtGrabado, $numInv, $sianulo, $txtSerie, $numNum, $numInterno, $txtNit;

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

	$func = new functions();

    $tipoPol="010";
	$selTipoCod = $_POST["selTipoCod"];
	$selTipoAbrev = $_POST["selTipoAbrev"];
	$txtSerie = $_POST["txtSerie"];
	$numNum = $_POST["numNum"];
	$numInterno = $_POST["numInterno"];
	$txtObs = utf8_decode($_POST['txtMotAnu']);
	$txtMotAnu = utf8_decode($_POST['txtMotAnu']);
	$DocumentGUID = $_POST['DocumentGUID'];
	$fechaemision = $_POST['fechaemision'];
	$txtNit = $_POST['txtNit'];
	$anu = "*** ANULADO ***";
	$FechaHoraAnulacion = $dtFec.'T'.date("H:i:s", STRTOTIME(date('h:i:sa'))).'-06:00';
	//date('Y-m-d\TH:i:s', STRTOTIME(date('h:i:sa')));
						  
	$jsonDetAnt=json_decode($_POST['tblDetAnt']);
	$jsonPolAnt=json_decode($_POST['tblPolAnt']);

	$anulado='*** ANULADO ***';

	$arrayError = array();

	# QUERYS PARA UN REGISTRO
	$sFacturas = "SELECT f.fact_idinterno, d.ds_tipo, d.ds_num, f.fact_fec, f.fact_nit FROM facturas f
				  LEFT JOIN doctoss d ON d.ds_emp=f.fact_emp AND d.ds_ftipo=f.fact_tipo AND d.ds_fserie=f.fact_serie AND d.ds_fnum=f.fact_num
				  WHERE fact_emp='$empCod' AND fact_idinterno='$numInterno'";

	$uFacturas = "UPDATE facturas SET fact_tot=0,fact_efectot=0,fact_efec=0,fact_exenval=0,fact_chval=0,fact_tarj=0,fact_vale=0,fact_cred=0,fact_dolares=0,fact_nom='$anulado',fact_dir='$anulado',fact_obs='$txtObs',fact_ulcam='$usuNom', fact_stat='A',fact_motanu='$txtMotAnu', fact_fechoranu='$FechaHoraAnulacion' WHERE fact_documentguid='$DocumentGUID' AND fact_emp='$empCod' AND fact_tipo='$selTipoCod' AND fact_serie='$txtSerie' AND fact_num=$numNum";
	
	$uIva_ven =  "UPDATE iva_ven SET ivav_clin='$anulado', ivav_bien=0, ivav_serv=0, ivav_exen=0, ivav_exp=0, ivav_con='$txtObs', ivav_subb=0, ivav_subs=0, ivav_sube=0, ivav_ret=0, ivav_reti=0, ivav_sub=0, ivav_iva=0, ivav_tot=0, ivav_ulcam='$usuNom' WHERE ivav_emp='$empCod' AND ivav_serie='$txtSerie' AND ivav_num=$numNum AND ivav_tipo='$selTipoCod'";

	$uDoctoscc = "UPDATE doctoscc SET dc_clien='$anulado', dc_bien=0, dc_serv=0, dc_exen=0, dc_exp=0, dc_con='$txtObs', dc_subb=0, dc_subs=0, dc_sube=0, dc_ret=0, dc_reti=0, dc_sub=0, dc_iva=0, dc_tot=0, dc_ulcam='$usuNom' WHERE dc_emp='$empCod' AND dc_serie='$txtSerie' AND dc_num=$numNum AND dc_tipo='$selTipoCod'";

	$dPolizas = "DELETE FROM polizas WHERE pol_emp='$empCod' AND pol_tipo='$tipoPol' AND pol_num='$numNum' AND pol_tipoi='$txtSerie'";

	$dPoli_det = "DELETE FROM poli_det WHERE pold_emp='$empCod' AND pold_tipo='$tipoPol' AND pold_num='$numNum' AND pold_tipoi='$txtSerie'";

	function uFact_det($IDInterno) {
		return "UPDATE fact_det SET factd_cant=0,factd_preu=0,factd_cosu=0,factd_sub=0,factd_descu=0,factd_descuv=0,factd_tot=0 WHERE factd_idinterno=$IDInterno";
	}

	function uDoctoss($tipo, $num){
		global $empCod, $usuNom, $anulado;
		return "UPDATE doctoss SET ds_obs='$anulado',ds_total=0,ds_ulcam='$usuNom' WHERE ds_emp='$empCod' AND ds_tipo='$tipo' AND ds_num=$num";
	}

	function uDocs_det($tipo, $num) {
		global $empCod;
		return "UPDATE docs_det SET dsd_cant=0,dsd_cantcon=0,dsd_cosu=0,dsd_descu=0,dsd_descuv=0,dsd_monto=0 WHERE dsd_emp='$empCod' AND dsd_tipo='$tipo' AND dsd_num=$num";
	}

	function uMovii($tipo, $num) {
		global $empCod;
		return "UPDATE movii SET mov_entra=0,mov_sale=0,mov_entracon=0,mov_salecon=0,mov_cosu=0,mov_preu=0 WHERE mov_emp='$empCod' AND mov_tipo='$tipo' AND mov_num=$num";
	}

	function uMovii_peps($tipo, $num) {
		global $empCod;
		return "UPDATE movii_peps SET mov_entra=0,mov_sale=0,mov_entracon=0,mov_salecon=0,mov_cosu=0,mov_preu=0 WHERE mov_emp='$empCod' AND mov_tipo='$tipo' AND mov_num=$num";
	}

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

	function uExiart_peps($cod, $cant, $bod, $signo, $fvence) {
		global $empCod;
		return "UPDATE exiart_peps SET ea_exist=ea_exist{$signo}{$cant} WHERE ea_emp='$empCod' AND ea_cod='$cod' AND ea_bod='$bod' AND ea_fvence='$fvence'";
	}

	function sMeses($mes) {
		return "SELECT mes_nom FROM meses WHERE mes_cod=$mes";
	}

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

	# PARA REVISION DE EXISTENCIAS
	function uExiartrevi($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 uExiartpepsrevi($codd,$nexist,$bodega,$lote,$fvence) { 
		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 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();

	$paso="N";
//	if ($respuesta_servicio->getCantidadErrores() == 0) {
		$paso="S";
		$fa["facturas"] = $db->sFetchAssoc($sFacturas);
		$IDInterno = $fa["facturas"]["fact_idinterno"];
		$nit = $fa["facturas"]["fact_nit"];
		$tipoInv = $fa["facturas"]["ds_tipo"];
		$numInv = $fa["facturas"]["ds_num"];
		$fecAnt = $fa["facturas"]["fact_fec"];
		$numAnoAnt=date("Y", strtotime($fecAnt));
		$numMesAnt=date("n", strtotime($fecAnt));

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

		$queryAcum = "";
		$queryAcum .= $uFacturas.";\n";
		$queryAcum .= uFact_det($IDInterno).";\n";
		//$queryAcum .= $uDoctoscc.";\n";
		if ($hayBienes) {
			$queryAcum .= $r["exiart"];
			$queryAcum .= $r["exiart_peps"];
			$queryAcum .= uDoctoss($tipoInv, $numInv).";\n";
			$queryAcum .= uDocs_det($tipoInv, $numInv).";\n";
			$queryAcum .= uMovii($tipoInv, $numInv).";\n";
			$queryAcum .= uMovii_peps($tipoInv, $numInv).";\n";
		}
//		$queryAcum .= $dPolizas.";\n";
//		$queryAcum .= $dPoli_det.";\n";
		$queryAcum .= $func->iBitacora(utf8_decode("Se anuló factura IDInterno: {$IDInterno} DocumentGUID: {$DocumentGUID} No.: {$numNum} Serie: {$txtSerie} NIT: {$nit} Usuario: ").$usuNom, $bitMod, $bitForm).";\n";

		//echo $queryAcum;
		$resp = $db->multiQueryAnEx($queryAcum);

        # Aqui se recalculan existencias
		foreach ($jsonDetAnt as $obj) {
			if ($obj->factd_bienser!='S') {
				$codd=$obj->factd_cod;
				$selBodega=$obj->factd_bodsal;
				$loted=$obj->factd_lote;
				$fvenced=$obj->factd_fvence;
	            # 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(uExiartrevi($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(uExiartpepsrevi($codd,$exisactupeps,$selBodega,$loted,$fvenced));
				//
			}
		}

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

				$fa["cierres"] = $db->sFetchAssoc(sCierres($cta, $numAnoAnt, $numMesAnt));
				$mdebe=$fa["cierres"]["cie_mdebe"]-$obj->pold_debe;
				$mhaber=$fa["cierres"]["cie_mhaber"]-$obj->pold_haber;

				$db->query(uCierres($cta, $numAnoAnt, $numMesAnt, $mdebe, $mhaber));

				$cta = $ctaActa;
			}
		}   */
//	} else {
		// Por si no se pudo anular la factura
//		$resp["mserror"]="No se anulo, hubo algun problema";
//	}
	$resp["paso"]=$paso;

	$db->close();

	return json_encode($resp);
}


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

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

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

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

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

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

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

	return $val;
}
?>