<?php
//include "clase.conexion.php";
class clsUsuario extends clsConexion{
	public $varTitulo = "MAESTRO DE USUARIOS";
	public $varMyTabla  = "_sys_usuario";
	public $varMyID  	  = "id_usuario";
	function FormuBusqueda() {
		$varTabla=array("id"=>"tabla", "name"=>"table", "tamano"=>"420", "clase"=>"FormTitulo", "titulo"=>$this->varTitulo." - BUSQUEDA",
						"formu"=>array("id"=>"form", "name"=>"form", "metodo"=>"POST", "onsubmit"=>"return false;"),						
						"ocult"=>array(array("tipo"=>"oculto", "id"=>"titu", "name"=>"titu", "valor"=>$this->varTitulo),
									   array("tipo"=>"oculto", "id"=>"opt", "name"=>"opt", "valor"=>$Opcion)
									  ),
						"conte"=>array(array("titulo"=>"Codigo :", "clase1"=>"FormCampo1", "clase2"=>"interior", "tamano"=>"80",
											 "campo" =>array("tipo"=>"texto", "id"=>"cod", "name"=>"cod", "valor"=>$_POST["cod"], 
											 "alinear"=>"center", "ancho"=>"70")),								   
									   array("titulo"=>"Usuario :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
											 "campo" =>array("tipo"=>"texto", "id"=>"usu", "name"=>"usu", "valor"=>$_POST["usu"], "ancho"=>"306")),
									   array("titulo"=>"Trabajador :", "clase1"=>"FormCampo1", "clase2"=>"interior", 
											 "campo" =>array("tipo"=>"texto", "id"=>"tra", "name"=>"tra", "valor"=>$_POST["tra"], "ancho"=>"306")),							   
									   ),
					  "boton"=>array(array("tipo"=>"submit", "id"=>"bcon", "name"=>"bcon", "ancho"=>"100", "texto"=>"Buscar",
					  					   "clase"=>"boton_buscar", "click"=>"javascript:xBuscarJS()"),
									 array("tipo"=>"button", "id"=>"bexp", "name"=>"bexp", "ancho"=>"100", "texto"=>"Exportar",
									 	   "clase"=>"boton_exportar", "click"=>"javascript:xExportarJS()"),								
									 array("tipo"=>"button", "id"=>"bnew", "name"=>"bnew", "ancho"=>"100", "texto"=>"Nuevo", 
										   "clase"=>"boton_nuevo", "click"=>"javascript:FormuRegistroJS('NEW','')"),
									 )
					);
		return $this->setTablaForm($varTabla);
		}
 	
	function GridDatos($varForm  = NULL, 
					   $varField = NULL, 
					   $varOrder = NULL
					   ) {
		$varCod = (isset($varForm["cod"]) && $varForm["cod"]<>'')? $varForm["cod"]:"NULL";
		$varNom = $varForm["nam"];
		$varUsr = (isset($_SESSION["_CUSE"]))?$_SESSION["_CUSE"]:1;
		$varFie = (isset($varField) && $varField<>'')? "'$varField'":"NULL";
		$varOrd = (isset($varOrder) && $varOrder<>'')? "'$varOrder'":"NULL";
		
		$sql = "call spQuery_Sistema_Usuario('$varForm[cod]', '$varForm[usu]','$varForm[tra]', $_SESSION[_CUSE], $varFie, $varOrd);";
		$varTabla=array("id"=>"theTable", "name"=>"theTable", "tamano"=>"1000", "sql_cab"=>$sql, "pages"=>50,
						"conte"=>array(array("titulo"=>"CUSU",   	"ancho"=>"20" , "alinear"=>"center", "tipo"=>"texto"),
									   array("titulo"=>"NOMPRE COMPLETO",  "ancho"=>"30", "fijo"=>"SI", "funcion"=>array("contar")), 
									   array("titulo"=>"USUARIO",	"ancho"=>"50", "clase"  =>"sortable"),									   
									   array("titulo"=>"CTRA",     	"ancho"=>"20", "alinear"=>"center"), 
									   array("titulo"=>"TRABAJADOR","ancho"=>"100", "clase"  =>"sortable", "fijo"=>"SI"),
									   array("titulo"=>"FCREADO",  	"ancho"=>"100", "alinear"=>"center", "fijo"=>"SI"),
									   array("titulo"=>"FUPDATE",  	"ancho"=>"100", "oculto"=>"SI"),
									   array("titulo"=>"UCREADO",  	"ancho"=>"100", "alinear"=>"center"),
									   array("titulo"=>"UUPDATE",  	"ancho"=>"100", "oculto"=>"SI")
									   ),
						"boton"=>array(array("tipo"=>"img", "id"=>"bbus", "name"=>"bbus", "img"=>"../images/16x16/table_edit.png", 
											 "toltip"=>array(array("valor"=>"HAGA CLICK PARA <b>EDITAR</b> LA BONIFICACION<br><b>"),
																 array("valor"=>0, "tipo"=>"INDEX"),
																 array("valor"=>" - "),
																 array("valor"=>1, "tipo"=>"INDEX"),
																 array("valor"=>"</b>")
																),
											 "click"=>array("funcion"=>"FormuRegistroJS",
															"param"=>array(array("valor"=>"EDIT", "tipo"=>"TEXTO"),
																		   array("valor"=>0, 	  "tipo"=>"INDEX")
																		  )
															)
											 
											),
									   array("tipo"=>"img", "id"=>"badd", "name"=>"badd", "img"=>"../images/16x16/table_delete.png", 
											 "toltip"=>array(array("valor"=>"HAGA CLICK PARA <b>ELIMINAR</b> LA BONIFICACION<br><b>"),
																 array("valor"=>0, "tipo"=>"INDEX"),
																 array("valor"=>" - "),
																 array("valor"=>1, "tipo"=>"INDEX"),
																 array("valor"=>"</b>")
																),
											 "click"=>array("funcion"=>"xEliminarJS",
															"param"=>array(array("valor"=>0, "tipo"=>"INDEX"),
																		   array("valor"=>1, "tipo"=>"INDEX"),
																		   array("valor"=>"this", "tipo"=>"NUM"),
																		   )
															)
											 )
									)
						);
		return $this->SetGridTabla2($varTabla);
		}
	
	function FormuRegistro($varOpt=NULL, $varCod=NULL) {
		if($varOpt=="NEW") {
			$SubTit = $this->varTitulo." - NUEVO";			
			$varLock = "NO";
			$varCod = "-1";
			}
		else {
			$SubTit =  $this->varTitulo." - EDITAR";
			$varLock = "SI";			
			$sql = "select U.*, (select concat(apellido_paterno, ' ', apellido_materno, ' ', nombre) 
					from _sv_trabajador V where V.id_trabajador=U.id_trabajador) as vendedor 
					from ".$this->varMyTabla." U where ".$this->varMyID." = $varCod";
			$this->AbrirConexion();
			$rs = $this->Query($sql);
			$this->CerrarConexion();
			$Fila = $this->FetchArray($rs);
			}
		
		$varFormu=array("id"=>"form", "name"=>"form", "metodo"=>"POST", "onsubmit"=>"return validaFormAccion(this,'N')");
		$varTabla=array("id"=>"table", "name"=>"table", "tamano"=>"400", "clase"=>"FormTitulo", "titulo"=>$SubTit,						
						"ocult"=>array(array("tipo"=>"oculto", "id"=>"titu", "name"=>"titu", "valor"=>$SubTit),
									   array("tipo"=>"oculto", "id"=>"opt" , "name"=>"opt" , "valor"=>$varOpt)
									  ),
						"conte"=>array(array("titulo"=>"Codigo :", "clase1"=>"FormCampo1", "clase2"=>"interior",
											 "campo"=>array("tipo"=>"text", "id"=>"cod", "name"=>"cod", "valor"=>$Fila["id_usuario"], 
															"ancho"=>"50", "alinear"=>"center", "locked"=>"SI", "clase"=>"inputDisable")
											 ),
									   array("titulo"=>"Usuario :", "clase1"=>"FormCampo1", "clase2"=>"interior",
											 "campo"=>array("tipo"=>"text", "id"=>"user", "name"=>"user", "valor"=>$Fila["usuario"], 
															"ancho"=>"100", "alinear"=>"center")
											 ),
									   array("titulo"=>"Clave :", "clase1"=>"FormCampo1", "clase2"=>"interior",
											 "campo"=>array("tipo"=>"clave", "id"=>"pass", "name"=>"pass", "valor"=>NULL, 
															"ancho"=>"100", "alinear"=>"center")
											 ),
									   array("titulo"=>"Nombre :", "clase1"=>"FormCampo1", "clase2"=>"interior", "tamano"=>"80",
											 "campo"=>array("tipo"=>"text", "id"=>"nom", "name"=>"nom", "valor"=>$Fila["nombre"], "ancho"=>"280")
											 ),
									   array("titulo"=>"Nro. DNI :", "clase1"=>"FormCampo1", "clase2"=>"interior",
											 "campo"=>array("tipo"=>"text", "id"=>"dni", "name"=>"dni", "valor"=>$Fila["dni"], 
															"ancho"=>"100", "alinear"=>"center", "maxchar"=>8)
											 ),
									   array("titulo"=>"Trabajador :", "clase1"=>"FormCampo1", "clase2"=>"interior",
											 "campo"=>array("tipo"=>"varios",
															"contenido"=>array(array("tipo"=>"text", "id"=>"tcod", "name"=>"tcod", "valor"=>$Fila["id_trabajador"],
																					 "ancho"=>"50", "alinear"=>"center", 
																					 "keypress"=>"return SoloEnteros(event)",
																					 "blur"=>"xajax_seleccionar_trabajador(this.value)", 
																					 "dclick"=>"fn_cargar_listado_trabajador('tcod', 'tnom')"),
																			   array("tipo"=>"text", "id"=>"tnom", "name"=>"tnom", "valor"=>$Fila["vendedor"], 
																					 "ancho"=>"250", "clase"=>"inputDisable", "locked"=>"SI")
																			   )
														 	)
											 )
									   ),
						"boton"=>array(array("tipo"=>"button", "id"=>"bsav", "name"=>"bsav", "ancho"=>"100",
											 "clase"=>"boton_guardar", "texto"=>"Grabar", "click"=>"javascrip:xGrabarJS()"),
									   array("tipo"=>"button", "id"=>"breg", "name"=>"breg", "ancho"=>"100",
											 "clase"=>"boton_cancelar", "texto"=>"Cancelar", "click"=>"javascrip:xajax_xRegresar()")
									  )
						);
		
		$sql1 = "select (select 'SI' from _sys_usuario_cp U where U.id_usuario=$varCod and U.id_condicion=C.id_condicion) as CHECKED,
				 id_condicion, nombre, dias
				 from _sv_tipo_condicion C 
				 where _estado = 'A';";
		$this->AbrirConexion();
		$rs1 = $this->Query($sql1);
		$this->CerrarConexion();
		$varExiste = $this->NumFilas($rs1);
		
		$varTab_1=array("id"=>"tab1", "name"=>"tab1", "tamano"=>"600", "clase"=>"FormTitulo", "titulo"=>"CONDICIONES DE VENTA ASIGNADOS", "sql"=>$sql1,
						"ocult"=>array(array("tipo"=>"oculto", "id"=>"num1", "name"=>"num1", "valor"=>$varNum1)),
						"conte"=>array(array("titulo"=>"SEL", "clase"=>"FormTitulo", "tamano"=>"30", "alinear"=>"center", "alto"=>"25",
											 "campo"=>array("tipo"=>"check", "id"=>"ven1", "name"=>"ven1", "alinear"=>"center", 
											 				"id_value"=>"1", "id_check"=>"0")
											 ),
									   array("titulo"=>"CCON", "clase"=>"FormTitulo", "tamano"=>"40", "alinear"=>"center", 
											 "campo"=>array("tipo"=>"simple", "alinear"=>"center")
											),
									   array("titulo"=>"NOMBRE CONDICION", "clase"=>"FormTitulo", "tamano"=>"300", 
											 "campo"=>array("tipo"=>"simple", "alinear"=>"center")
											),
									   array("titulo"=>"DIAS", "clase"=>"FormTitulo", "tamano"=>"40", "alinear"=>"center", 
											 "campo"=>array("tipo"=>"simple", "alinear"=>"center")
											)							   
									   )
						);
		
		$sql2 = "select (select 'SI' from _sys_usuario_almacen U 
						 where U.id_usuario=$varCod and U.id_empresa=A.id_empresa and U.id_almacen=A.id_almacen) as CHECKED,
				A.id_almacen as CALM, A.nombre as ALMACEN,
				A.id_empresa AS CEMP, E.nombre AS EMPRESA		
				from _sv_almacen A
				inner join _sv_empresa E ON A.id_empresa = E.id_empresa
				where A._estado='A'";
		$this->AbrirConexion();
		$rs2 = $this->Query($sql2);
		$this->CerrarConexion();
		$varExiste = $this->NumFilas($rs2);
		
		$varTab_2=array("id"=>"tab2", "name"=>"tab2", "tamano"=>"600", "clase"=>"FormTitulo", "titulo"=>"ALMACENES x EMPRESA ASIGNADOS", "sql"=>$sql2,
						"ocult"=>array(array("tipo"=>"oculto", "id"=>"num2", "name"=>"num2", "valor"=>$varNum1)),
						"conte"=>array(array("titulo"=>"SEL", "clase"=>"FormTitulo", "tamano"=>"30", "alinear"=>"center", "alto"=>"25",
											 "campo"=>array("tipo"=>"check", "id"=>"alm", "name"=>"alm", "alinear"=>"center", 
											 				"id_value"=>"1", "id_check"=>"0")
											 ),
									   array("titulo"=>"CALM", "clase"=>"FormTitulo", "tamano"=>"40", "alinear"=>"center", 
											 "campo"=>array("tipo"=>"simple", "alinear"=>"center")
											),
									   array("titulo"=>"ALMACEN", "clase"=>"FormTitulo", "tamano"=>"300", 
											 "campo"=>array("tipo"=>"simple", "alinear"=>"center")
											),
									   array("titulo"=>"CEMP", "clase"=>"FormTitulo", "tamano"=>"40", "alinear"=>"center", 
											 "campo"=>array("tipo"=>"simple", "alinear"=>"center")
											),
									   array("titulo"=>"EMPRESA", "clase"=>"FormTitulo", "tamano"=>"300", 
											 "campo"=>array("tipo"=>"simple", "alinear"=>"center")
											)							   
									   )
						);
						
		$sql3 = "select S.id_sistema, S.nombre, 
				(select id_rol from _sys_usuario_sistema_rol R WHERE R.id_sistema=S.id_sistema and R.id_usuario=$varCod) AS id_rol
				from _sys_sistema S 
				where S._estado='A';";
		$this->AbrirConexion();
		$rs3 = $this->Query($sql3);
		$this->CerrarConexion();
		$varExiste = $this->NumFilas($rs3);
		$sqlrol = "select id_rol, nombre from _sys_rol where _estado='A' and id_sistema = varSis;";
		$varTab_3=array("id"=>"tab2", "name"=>"tab2", "tamano"=>"600", "clase"=>"FormTitulo", "titulo"=>"ALMACENES x EMPRESA ASIGNADOS", "sql"=>$sql3,
						"ocult"=>array(array("tipo"=>"oculto", "id"=>"num3", "name"=>"num3", "valor"=>$varNum3)),
						"conte"=>array(array("titulo"=>"CSIS", "clase"=>"FormTitulo", "tamano"=>"40", "alinear"=>"center", 
											 "campo"=>array("tipo"=>"texto", "id"=>"sis", "name"=>"sis", "alinear"=>"center", "ancho"=>"40",
											 				"locked"=>"SI", "clase"=>"inputDisable")
											),
									   array("titulo"=>"SISTEMA", "clase"=>"FormTitulo", "tamano"=>"300", 
											 "campo"=>array("tipo"=>"simple", "alinear"=>"center")
											),
									   array("titulo"=>"ROL", "clase"=>"FormTitulo", "tamano"=>"250", 									   		 
											 "campo"=>array("tipo"=>"select", "id"=>"rol", "name"=>"rol", "alinear"=>"center", "valor"=>2,					 				
											 				"sql"=>$sqlrol, "titulo"=>"--[[SELECCIONAR]]--", "ancho"=>"250",
															"var"  =>array("varSis"=>0))
											)							   
									   )
						);
										
		$varTabs =array(array("name"=>"Condiciones de Venta",
							  "tipo"=>"det",  "alto"=>"300", "ancho"=>"620", "tabla"=>$varTab_1
							  ),
						array("name"=>"Almacenes x Empresa",
							  "tipo"=>"det",  "alto"=>"300", "ancho"=>"620", "tabla"=>$varTab_2
							  ),
						array("name"=>"Roles x Sistema",
							  "tipo"=>"det",  "alto"=>"300", "ancho"=>"620", "tabla"=>$varTab_3
							  )
						);
		$varMyTable = $this->setTablaFormTabs($varFormu, $varTabla, $varTabs);
		
		return $varMyTable;	
		}
		
	function ProcesoGrabar($varForm = NULL) {		
		$varUsr = (isset($_SESSION["_CUSE"])) ? $_SESSION["_CUSE"] : 1;	
		$varCod = ($varForm["cod"]=="")? "NULL" : $varForm["cod"];
		$varVen = ($varForm["tcod"]=="")? "0" : $varForm["tcod"];
		$varFlagPass = (isset($varForm["pass"]) && $varForm["pass"]<>"")?"S":NULL;

		// Insertamos/Actualizamos datos del Usuario
		$sql = "call spMante_Sistema_Usuario('$varForm[opt]', $varCod, $varVen, '$varForm[nom]', '$varForm[dni]', 
				'$varForm[user]', '$varForm[pass]', '$varFlagPass', $varUsr)";
		$this->AbrirConexion();
		$rs = $this->Query($sql);
		$this->CerrarConexion();
		$fila = $this->FetchArray($rs);		
		$varIde = $fila[0];
		// Eliminamos Condiciones de Venta Asignados
		$sql = "DELETE FROM _sys_usuario_cp WHERE id_usuario = $varCod;";
		$this->AbrirConexion();
		$rs = $this->Query($sql);
		$this->CerrarConexion();	
		//Registramos el Detalle de las Condiciones de Venta
		$sqldet = "";
		foreach ($varForm["ven1"] as $varVen) {
			$sqldet.= "insert into _sys_usuario_cp values($varCod, $varVen, NOW(), NOW(), $varUsr, $varUsr, 'A');";			
			}
		$this->AbrirConexion();
		$this->Query($sqldet);
		$this->CerrarConexion();
		
		// Eliminamos Almacenes x Empresa Asignados
		$sql = "DELETE FROM _sys_usuario_almacen WHERE id_usuario = $varCod;";
		$this->AbrirConexion();
		$rs = $this->Query($sql);
		$this->CerrarConexion();	
		//Registramos el Detalle de los Almacenes x Empresa
		$sqldet = "";
		foreach ($varForm["alm"] as $varAlm) {
			$sqldet.= "insert into _sys_usuario_almacen values($varCod,(select id_empresa from _sv_almacen where id_almacen=$varAlm), $varAlm, 
					   NOW(),NOW(),$varUsr,$varUsr,'A');";			
			}
		$this->AbrirConexion();
		$this->Query($sqldet);
		$this->CerrarConexion();
		$varsql1 = $sqldet;
		
		$sqldet = "";
		$varSisTemp = "";
		foreach ($varForm["rol"] as $varIx =>$varRol) {
			$varSis = $varForm["sis"][$varIx];
			$varSisTemp.= ($varSisTemp=="")?$varSis:",".$varSis;
			$varRol = ($varRol<>"Ninguno")?$varRol:"NUL";
			$sqldet.= "call spMante_Usuario_Sistema_Rol($varCod, $varSis, $varRol, $varUsr);";
			}
		$sqldel = "DELETE FROM _sys_usuario_sistema_rol WHERE id_usuario = $varCod and id_sistema in ($varSisTemp);";
		$this->AbrirConexion();
		$this->Query($sqldel);
		$this->Query($sqldet);
		$this->CerrarConexion();
		
		return "OK";
		}
	
	function ProcesoEliminar($varCod) {
		$varUsr = (isset($_SESSION["_CUSE"]))?$_SESSION["_CUSE"]:1;
		$sql = "update ".$this->varMyTabla." set _estado = 'X', _date_update=NOW(), _user_update=$varUsr where ".$this->varMyID."= '".$varCod."';";
		$this->AbrirConexion();
		$this->Query($sql);
		$this->CerrarConexion();
		}
	}
	
?>