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

$bitForm = "pov4040";
$bitMod = "pov";
$empCod = $_SESSION['empCod'];
$usuCod = utf8_decode($_SESSION['usuCod']);
$usuNom = utf8_decode($_SESSION['usuNom']);

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

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

function consultar() {
	global $empCod;

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

	$func = new functions();

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

	# QUERYS
	$sTipov = "SELECT *, TRIM(tv.tv_nom) AS tv_nom
				FROM tipov tv
				LEFT JOIN corrtipov ctv ON ctv_emp='$empCod' AND ctv_tipo=tv_cod
				WHERE tv_cod='$txtCod'";

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

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

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

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

	$func = new functions();

	$txtCod = utf8_decode($_POST["txtCod"]);
	$numCorr = $_POST["numCorr"];

	# QUERYS PARA UN REGISTRO
	$sCorrTipov = "SELECT * FROM corrtipov WHERE ctv_emp='$empCod' AND ctv_tipo='$txtCod'";

	$uCorrTipov = "UPDATE corrtipov set ctv_num='$numCorr' WHERE ctv_emp='$empCod' AND ctv_tipo='$txtCod'";

	$iCorrTipov = "INSERT INTO corrtipov(ctv_emp, ctv_tipo, ctv_num) VALUES ('$empCod','$txtCod','$numCorr')";

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$select["corrtipov"] = $db->query($sCorrTipov);
	if ($db->numRows($select["corrtipov"]) == 0) {
		$resp = $db->iEx($iCorrTipov);
		$db->iEx($func->iBitacora(utf8_decode("Se creó Correlativo Serie  $txtCod  Usuario: ").$usuNom, $bitMod, $bitForm));
    } else {
		$resp = $db->iEx($uCorrTipov);
		$db->iEx($func->iBitacora(utf8_decode("Se Modifico Correlativo Serie  $txtCod  Usuario: ").$usuNom, $bitMod, $bitForm));
    }
	$db->close();
	return json_encode($resp);
}

?>