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

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

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

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

	$func = new functions();


	$sMovAcu = "SELECT ma_emp,ma_ban,SUM(ma_debe) AS ma_sdebe, SUM(ma_haber) AS ma_shaber FROM mov_acu 
	            WHERE ma_emp='$empCod' GROUP BY ma_emp,ma_ban";

	
	function sSaldob($numBan) { 
		global $empCod;
		return "SELECT * FROM saldob WHERE salb_emp='$empCod' AND salb_num=$numBan";
	}

	function uSaldob($numBan,$Saldo) { 
		global $empCod, $usuNom;
		return "UPDATE saldob SET salb_saldo=$Saldo WHERE salb_emp='$empCod' AND salb_num=$numBan";
	}

	function iSaldob($numBan,$Saldo) { 
		global $empCod, $usuNom;
		return "INSERT INTO saldob(salb_emp, salb_num, salb_saldo) VALUES('$empCod',$numBan,$Saldo)";
	}
	
	# EJECUCION DE QUERYS 
	$db = new dbExec();

	$select["mov_acu"]=$db->query($sMovAcu);

	// PARA APLICAR LOS CIERRES
	while ($rec = $db->fetchAssoc($select["mov_acu"])) {
		$numBan = $rec["ma_ban"];
		$Saldo = $rec["ma_sdebe"]-$rec["ma_shaber"];

		$select["saldob"] = $db->query(sSaldob($numBan));
		if ($db->numRows($select["saldob"]) > 0) {
			$db->query(uSaldob($numBan, $Saldo));
			} else {
			$db->query(iSaldob($numBan, $Saldo));
		}
	}

	$resp = $db->iEx($func->iBitacora(utf8_decode("Revisaron los saldos bancarios de la empresa $empCod Usuario: ").$usuNom, $bitMod, $bitForm));

	$db->close();

		$resp['msgWarning'] = array(
			'error'=>true,
			'msg'=>array(
				'title'=>'FINALIZO PROCESO',
				'text'=>'Se realizo revision de saldos bancarios'
			),
		); 

	return json_encode($resp);
}

?>