<?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 = "fel1110";
$bitMod = "fac";
$empCod = $_SESSION['empCod'];
$empConso = $_SESSION['empConso'];
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);
$tipoPol='010';

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

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

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

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

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

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

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

	case 'imprimir':
		echo imprimir();
		break;
}

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

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

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

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

	return json_encode($resp);
}

function consultarCorrtipov() {
	global $empCod;

	$func = new functions();

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

	# QUERYS
	$sCorrtipov = "SELECT ctv_num FROM corrtipov WHERE ctv_emp='$empCod' AND ctv_tipo='$selTipoCod'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();

	$select["corrtipov"] = $db->query($sCorrtipov);
	if ($db->numRows($select["corrtipov"])>0) {
		$numFac = ($db->fetchAssoc($select["corrtipov"])["ctv_num"]);
	} else {
		$numFac = 1;
		$r["corrtipov"] = $db->query("INSERT INTO corrtipov (ctv_emp, ctv_tipo, ctv_num) VALUES('$empCod', '$selTipoCod', $numFac);");
	}

	$resp["corrtipov"]["ctv_num"] = $numFac;
	$db->close();

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

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 guardar() {
	global $empCod, $usuNom, $empConso, $bitMod, $bitForm, $numTcam, $dtFec, $selTipoCod, $selTipoAbrev, $tipoPol, $tipoInv, $db, $func, $totales, $dtGrabado, $numInv, $soloInv;

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

	$func = new functions();

	$DocumentGUID = '';
	$selTipoCod = $_POST["selTipoCod"];
	$selTipoAbrev = $_POST["selTipoAbrev"];
	$selTipoLibrosn = $_POST["selTipoLibrosn"];
	$selTipoImpues = $_POST["selTipoImpues"];
	$numNum = $_POST["numNum"];

	$dtFec = $_POST["dtFec"];
	$numAno=date("Y", strtotime($dtFec));
	$numMes=date("n", strtotime($dtFec));

	$selBodSalCod = $_POST["selBodSalCod"];
	$crAsigEnvio = "N";
	$selTipoEnvCod = "";
	$selTipoEnvAbrev = "";
	$selTipoEnvRelatd = "";
	$numNumEnv = 0;
	$numTcam = $_POST["numTcam"];
	$txtCliCod = utf8_decode($_POST["txtCliCod"]);
	$txtNomFac = utf8_decode($_POST["txtNomFac"]);
	$txtNit = utf8_decode($_POST["txtNit"]);
	$txtDir = utf8_decode($_POST["txtDir"]);
	$txtTel = utf8_decode($_POST["txtTel"]);
	$numDcre = $_POST["numDcre"];
	$selVendCod = $_POST["selVendCod"];
	$crFpag = $_POST["crFpag"];
	$crExp = $_POST["crExp"];
	$crRet = $_POST["crRet"];
	$crReti = $_POST["crReti"];
	$txtObs = utf8_decode($_POST["txtObs"]);
	$tot=$_POST["tot"];
	$dtGrabado=date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa')));

	$jsonDet=json_decode($_POST['tblDet']);
	$jsonPol=json_decode($_POST['tblPol']);

	$jsonDetAnt=json_decode($_POST['tblDetAnt']);
	$jsonPolAnt=json_decode($_POST['tblPolAnt']);

	$tipoInv=$_POST["selTipoRelatd"];

	$arrayError = array();

	# QUERYS PARA UN REGISTRO
	$sTABLES = "SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_NAME='pedidos' AND TABLE_SCHEMA='{$_SESSION['nombredb']}'";

	$sTipov = "SELECT tv_soloinv FROM tipov WHERE tv_cod='$selTipoCod'";

	$sCorrtipov = "SELECT ctv_num FROM corrtipov WHERE ctv_emp='$empCod' AND ctv_tipo='$selTipoCod'";

	function sCliencc($cod){
		global $empCod;
		return "SELECT 
					*,
					TRIM(cli_tel) AS cli_tel,
					TRIM(cli_codpos) AS cli_codpos,
					TRIM(cli_muni) AS cli_muni,
					TRIM(cli_depto) AS cli_depto
				FROM cliencc WHERE cli_emp='$empCod' AND cli_cod='$cod'";
	}

	function iuFacturas($Batch, $Serial, $DocumentGUID, $transac, $tot, $codp, $nit, $nom, $dir, $tel, $dcre, $tcam, $fpag, $obs, $retsn, $retisn, $stat, $vencod, $lugare, $envio, $pedido, $orden, $bodsal, $pcomi, $contrato, $expsn, $asigEnvio, $tipoEnv, $serieEnv, $numEnv){
		global $empCod, $usuNom, $dtFec, $selTipoCod, $func;
		if ($func->stringToBool($_POST['nuevo'])) {
			return "INSERT INTO pedidos(fact_documentguid,fact_emp,fact_tipo,fact_serie,fact_num,fact_transac,fact_fec,fact_tot,fact_codp,fact_nit,fact_nom,fact_dir,fact_tel,fact_dcre,fact_tcam,fact_fpag,fact_obs,fact_retsn,fact_retisn,fact_stat,fact_vend,fact_ulcam,fact_lugare,fact_envio,fact_pedido,fact_orden,fact_bodsal,fact_pcomi,fact_contrato,fact_fel,fact_expsn,fact_asigenvio,fact_tipoenv,fact_serieenv,fact_numenv) VALUES ('$DocumentGUID','$empCod','$selTipoCod','$Batch',$Serial,$transac,'$dtFec','$tot','$codp','$nit','$nom','$dir','$tel',$dcre,'$tcam','$fpag','$obs','$retsn','$retisn','$stat','$vencod','$usuNom','$lugare','$envio','$pedido','$orden','$bodsal','$pcomi','$contrato','','$expsn','$asigEnvio','$tipoEnv','$serieEnv','$numEnv')";
		} else {
			return "UPDATE pedidos SET fact_fec='$dtFec',fact_tot='$tot',fact_codp='$codp',fact_nit='$nit',fact_nom='$nom',fact_dir='$dir',fact_tel='$tel',fact_dcre=$dcre,fact_tcam='$tcam',fact_fpag='$fpag',fact_obs='$obs',fact_retsn='$retsn',fact_retisn='$retisn',fact_stat='$stat',fact_vend='$vencod',fact_ulcam='$usuNom',fact_lugare='$lugare',fact_envio='$envio',fact_pedido='$pedido',fact_orden='$orden',fact_bodsal='$bodsal',fact_pcomi='$pcomi',fact_contrato='$contrato',fact_expsn='$expsn',fact_asigenvio='$asigEnvio',fact_tipoenv='$tipoEnv',fact_serieenv='$serieEnv',fact_numenv='$numEnv' WHERE fact_documentguid='$DocumentGUID' AND fact_emp='$empCod' AND fact_tipo='$selTipoCod' AND fact_serie='$Batch' AND fact_num=$Serial";
		}
	}

	function iCorrtipov($num) {
		global $empCod, $selTipoCod, $func;
		if ($func->stringToBool($_POST['nuevo'])) {
			return "UPDATE corrtipov SET ctv_num=$num+1 WHERE ctv_emp='$empCod' AND ctv_tipo='$selTipoCod';\n";
		}
		return "";
	}

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

	function sArtic($cod) {
		global $empCod;
		return "SELECT art_cosp FROM artic WHERE art_cod='$cod' AND art_emp='$empCod'";
	}

	function iDetalle($IDInterno, $transac, $Batch, $Serial, $autoriza, $codp, $nit, $vend, $bodsal, $tcam, $obs, $nom, $dir, $expsn, $tot, $asigEnvio, $tipoEnvRelatd, $numEnv, $jsonDetAnt, $jsonDet) {
		global $empCod, $dtFec, $tipoInv, $db, $selTipoCod, $totales, $numInv, $soloInv;
		$func = new functions();

		// ELIMINAR ANTES DE INSERTAR
		$dFact_det = "DELETE FROM pedidos_det WHERE factd_emp='$empCod' AND factd_tipo='$selTipoCod' AND factd_serie='$Batch' AND factd_num=$Serial";


		// VARIABLES DE ACUMULACION PARA LOS QUERYS
		$r["exiart"] = "";

		$r["fact_det"] = "{$dFact_det};\n"."INSERT INTO pedidos_det(factd_idinterno,factd_emp,factd_transac,factd_tipo,factd_serie,factd_num,factd_fec,factd_cod,factd_desc,factd_desci,factd_med,factd_unimed,factd_cant,factd_preu,factd_cosu,factd_sub,factd_descu,factd_descuv,factd_tot,factd_autoriza,factd_codp,factd_nit,factd_vend,factd_bodsal,factd_exensn,factd_bienser) VALUES \n";
		
		// VARIABLES PARA SEPARAR BIENES, SERVICIOS Y EXPORTACION
		$hayBienes=false;
		$totales["bienes"]["exentoS"]=0;
		$totales["bienes"]["exentoN"]=0;
		$totales["servicios"]["exentoS"]=0;
		$totales["servicios"]["exentoN"]=0;
		$totales["exportacion"]=0;

		// RECORRER DETALLE PARA ACUMULAR QUERYS
		$i=0;
		$iUltimoBien=0;
		foreach ($jsonDet as $obj) {
			$i++;
			$obj->codd = utf8_decode($obj->codd);
			$obj->descd = utf8_decode($obj->descd);
			$obj->medid = utf8_decode($obj->medid);
			$obj->unimed = utf8_decode($obj->unimed);
			$cosp = $db->sFetchAssoc(sArtic($obj->codd))["art_cosp"];

			$r["fact_det"].="('$IDInterno','$empCod','$transac','$selTipoCod','$Batch','$Serial','$dtFec','$obj->codd','$obj->descd','$obj->descd','$obj->medid','$obj->unimed','$obj->cantd','$obj->preud','$cosp','$obj->subd','$obj->descud','$obj->descuvd','$obj->totd',0,'$codp','$nit','$vend','$bodsal','$obj->exensnd','$obj->bienserd')".$func->addValuesSemicolon($obj, $jsonDet);

			// OPERACIONES PARA SERPARAR EL TOTAL DE BIENES Y SERVICIOS
			if ($obj->bienserd=='S') {
				$hayServicios = true;
				($obj->exensnd=='N') ? $totales["servicios"]["exentoN"]+=$obj->totd : $totales["servicios"]["exentoS"]+=$obj->totd;
			} else {
				$hayBienes = true;
				$iUltimoBien = $i;
				($obj->exensnd=='N') ? $totales["bienes"]["exentoN"]+=$obj->totd : $totales["bienes"]["exentoS"]+=$obj->totd;
			}
		}
		
		// EVALUAR SI TAMBIEN SE GUARDA EN MODULO DE INVENTARIO O SOLO EN MODULO DE FACTURACION, SEGUN BIENES O SERVICIOS

		$r = (sizeof($jsonDet)==0) ? "" : $r["fact_det"];

		return $r;
	}


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

	$soloInv = $db->sFetchAssoc($sTipov)['tv_soloinv'];
	$numNum = $db->sFetchAssoc($sCorrtipov)['ctv_num'];

	$numInv = $numNum;
	if ($func->stringToBool($_POST['nuevo'])) {
		$IDInterno = $db->sFetchAssoc($sTABLES)['AUTO_INCREMENT'];
		$fecAnt = "0000-00-00";
	} else {
		$fa["facturas"] = $db->sFetchAssoc($sFacturas);
		$IDInterno = $fa["facturas"]["fact_idinterno"];
		$fecAnt = $fa["facturas"]["fact_fec"];
	}
	$numAnoAnt=date("Y", strtotime($fecAnt));
	$numMesAnt=date("n", strtotime($fecAnt));

	$queryAcum = "";
	
	$queryAcum .= iuFacturas($selTipoAbrev, $numNum, $DocumentGUID, $IDInterno, $tot, $txtCliCod, $txtNit, $txtNomFac, $txtDir, $txtTel, $numDcre, $numTcam, $crFpag, $txtObs, $crRet, $crReti, '', $selVendCod, '', '', '', '', $selBodSalCod, "0.00", 0, $crExp, $crAsigEnvio, $selTipoEnvCod, $selTipoEnvAbrev, $numNumEnv).";\n";

	$queryAcum .= iCorrtipov($numNum);

	$queryAcum .= iDetalle($IDInterno, $IDInterno, $selTipoAbrev, $numNum, 0, $txtCliCod, $txtNit, $selVendCod, $selBodSalCod, $numTcam, $txtObs, $txtNomFac, $txtDir, $crExp, $tot, $crAsigEnvio, $selTipoEnvRelatd, $numNumEnv, $jsonDetAnt, $jsonDet);

	// PARA BITACORA
	if ($func->stringToBool($_POST['nuevo'])) {
		$queryAcum .= $func->iBitacora(utf8_decode("Se creó Documento IDInterno: {$IDInterno} DocumentGUID: {$DocumentGUID} No.: {$numNum} Serie: {$selTipoAbrev} NIT: {$txtNit} Usuario: ").$usuNom, $bitMod, $bitForm).";\n";
	} else {
		$queryAcum .= $func->iBitacora(utf8_decode("Se modificó Documento IDInterno: {$IDInterno} DocumentGUID: {$DocumentGUID} No.: {$numNum} Serie: {$selTipoAbrev} NIT: {$txtNit} Usuario: ").$usuNom, $bitMod, $bitForm).";\n";
	}

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

	$db = new dbExec();
	$resp["idinterno"]=$IDInterno;
	$resp["numdoc"]=$numNum;

	return json_encode($resp);
}


function imprimir() {
	global $empCod;

	$priv = new privileges();
	if (!$priv->consult($_SESSION['usuPriv'])) {
		return json_encode($priv->rErrorConsult());
	}
	
	# QUERYS
	$sTipov = "SELECT TRIM(tv_nom) AS tv_nom FROM tipov WHERE tv_cod='{$_POST["selTipoCod"]}'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$fa["tipov"] = $db->sFetchAssoc($sTipov);

	$_SESSION["printFacturas"] = array(
		'tipoNomFEL'=>$fa["tipov"]["tv_nom"],
		'tipoFEL'	=>$_POST["selTipoCod"],
		'nom'		=>$_POST["txtNomFac"],
		'nit'		=>$_POST["txtNit"],
		'dir'		=>$_POST["txtDir"],
		'fec'		=>$_POST["dtFec"],
		'tcam'		=>$_POST["tcam"],
		'tot'		=>$_POST["dataTot"],
		'totLetras'	=>$_POST["totLetras"],
		'det' 		=>$_POST["tblDet"]
	);
	return "";
}

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;
}
?>