<?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 = "fac4020";
$bitMod = "fac";
$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;

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

function consultar() {
	global $empCod;
	$txtCod=utf8_decode($_POST['txtCod']);

	# QUERYS
	$sVendedor = "SELECT *,TRIM(vend_nom) AS vend_nom, trim(vend_dir) AS vend_dir FROM vendedor WHERE vend_cod='$txtCod'";
	
	# EJECUCION DE QUERYS
	$db = new dbExec();
	$resp = $db->sEx($sVendedor, "vendedor");
	$db->close();

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

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

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

	$func = new functions();

	$txtCod=$_POST['txtCod'];
	$txtNom=utf8_decode($_POST['txtNom']);
	$txtDir=utf8_decode($_POST['txtDir']);
	$txtTel=$_POST['txtTel'];
	$txtCel=$_POST['txtCel'];
	$numPorc=$_POST['numPorc'];

	# QUERYS PARA UN REGISTRO
	$iVendedor = "INSERT INTO vendedor(vend_cod, vend_nom, vend_dir, vend_tel, vend_cel, vend_porc) VALUES ('$txtCod','$txtNom','$txtDir','$txtTel','$txtCel','$numPorc')";

	$uVendedor = "UPDATE vendedor SET vend_nom='$txtNom',vend_dir='$txtDir',vend_tel='$txtTel',vend_cel='$txtCel',vend_porc='$numPorc' WHERE vend_cod='$txtCod'";

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	if ($func->stringToBool($_POST['nuevo'])) {
		$resp = $db->iEx($iVendedor);
		$db->iEx($func->iBitacora(utf8_decode("Se creó vendedor: $txtCod  $txtNom Usuario: ").$usuNom, $bitMod, $bitForm));
	} else {
		$resp = $db->uEx($uVendedor);
		$db->iEx($func->iBitacora(utf8_decode("Se modificó vendedor: $txtCod  $txtNom Usuario: ").$usuNom, $bitMod, $bitForm));
	}
	
	$db->close();

	return json_encode($resp);
}

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

	$func = new functions();

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

	# QUERYS
	$dVendedor = "DELETE FROM vendedor WHERE vend_cod='$txtCod'";

	# EJECUCION DE QUERYS 
	$db = new dbExec();
	$resp = $db->dEx($dVendedor);
	$db->iEx($func->iBitacora(utf8_decode("Se borró vendedor: $txtCod  $txtNom Usuario: ").$usuNom, $bitMod, $bitForm));
	$db->close();

	return json_encode($resp);
}
?>