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

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

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

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

function consultarClien() {
	global $empCod;
	$txtNit=utf8_decode($_POST['txtNit']);

	# QUERYS
	$sClien = "SELECT *,TRIM(cli_nom) AS cli_nom,TRIM(cli_dir) AS cli_dir,TRIM(cli_tel) AS cli_tel FROM clien WHERE cli_nit='$txtNit'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sClien, "clien");
	$db->close();

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

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

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

	$func = new functions();

	$txtNit=$_POST['txtNit'];
	$txtCli=utf8_decode($_POST['txtCli']);
	$txtDir=utf8_decode($_POST['txtDir']);
	$txtTel=utf8_decode($_POST['txtTel']);

	# QUERYS PARA UN REGISTRO
	$iClien = "INSERT INTO clien(cli_nit, cli_nom, cli_dir, cli_tel) VALUES ('$txtNit','$txtCli','$txtDir','$txtTel')";

	$uClien = "UPDATE clien SET cli_nom='$txtCli',cli_dir='$txtDir',cli_tel='$txtTel' WHERE cli_nit='$txtNit'";

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	if ($func->stringToBool($_POST['nuevo'])) {
		$resp = $db->iEx($iClien);
	} else {
		$resp = $db->uEx($uClien);
	}
	
	$db->close();

	return json_encode($resp);
}

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

	$func = new functions();

	$txtNit=$_POST['txtNit'];
	$txtCli=utf8_decode($_POST['txtCli']);

	# QUERYS
	$dClien = "DELETE FROM clien WHERE cli_nit='$txtNit'";

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$resp = $db->dEx($dClien);
	$db->iEx($func->iBitacora(utf8_decode("Se borró Cliente, Nit: $txtNit  $txtCli Usuario: ").$usuNom, $bitMod, $bitForm));
	$db->close();

	return json_encode($resp);
}
?>