<?php
	include ("../include/dbpg.php");
	include ("../include/fn.php");
	include ("../include/fx.php");
	include ("../include/fn_ws3.php");
	$agente =strtolower(@$_GET["MimoAgent"]);
	$psw_agente =@$_GET["MimoPassword"];
	$area =@$_GET["idarea"];
	$Ip =@$_GET["Ip"];
	$host=@$_GET["hostname"];
	$mac=@$_GET["mac"];
	$modulo =@$_GET["modulo"];
	$version=@$_GET["version"];
	$proceso_defecto =2;
	$ldap="";
	error_log("DEBUG: kml_login_gestor_colas, usuario = " . $agente);

	if ($version<>"V.0.6.3CM" && $version<>"V.0.6.4CM" && $version<>"V.0.6.4SM")
	{
		echo('<resultado><estado>error</estado><mensaje>Version ' . $version . ' incorrecta, favor actualizar</mensaje></resultado>');
		exit();
	}
	if (!$modulo)
	{
		$modulo = 0;
	}
	if ($agente != '' && $area != '')
	{
		$conn = db_connect(HOST, USER, PASS, DB);
		$sSql = 'Select t02_configuracion_general from t02_area where t02_id_area =' . $area;
		$rs=$conn->query($sSql);
        	if ($row = $rs->fetch())
		{
			/*
			$configuracion_general=$row['t02_configuracion_general'];
			$ldap = valor_campo($configuracion_general,'<ldap>','</ldap>');
			if ($ldap=='1')
			{
				//consumir ws ldap para validar y continuar o salir
				datos = json_decode(ejecuta_ldap_claro($agente, $psw_agente));
				if(!$datos->habilitado)
				{
					echo('<resultado><estado>error</estado><mensaje>' . $datos->mensaje . '</mensaje></resultado>');
                                        exit();
				}
			}
			 */

			$json = file_get_contents('http://geko.vtr.cl/claro/?usuario='. $agente);
			$datos_eac_claro = json_decode($json);
			if (!$datos_eac_claro->user->status)
			{
				 echo('<resultado><estado>error</estado><mensaje>No Habilitado</mensaje></resultado>');
                                 exit();
			}
		}
		$sSql = <<<EOT
				SELECT t04_password,a.t04_id_ejecutivo,t02_area,c.t01_licencia,t04_fecha_bloqueo,t02_servidor_ftp,
				t02_usuario_ftp,t02_password_ftp, t11_hostname,t11_modulo,t08_fecha_deslogeo,t08_fecha_logeo,d.t11_id,t02_configuracion_general
				FROM t04_ejecutivo a join t02_area b on a.t02_id_area = b.t02_id_area
				join t01_servicio c on b.t01_id_servicio = c.t01_id_servicio
				left join t08_log_ejecutivo d on a.t08_id_log = d.t08_id_log
				left join t11_pc e on d.t11_id=e.t11_id
				WHERE t04_usuario = '$agente' and a.t02_id_area= $area;
			EOT;

		//echo($sSql);
		//exit();

		$rs=$conn->query($sSql);
		if ($row = $rs->fetch())
		{
			//validar si el ejecutivo está logeado
			if (is_null($row['t08_fecha_logeo']) ===false)
			{
				if (is_null($row->t08_fecha_deslogeo))
				{
					//detecto que está logeado
					if($row['t11_hostname']<>$host)
					{
						//detecto que está conectado en otro PC
						echo <<<'EOT'
						<resultado>
							<estado>error</estado>
							<mensaje>Ejecutivo Conectado en Otro PC $row->t11_hostname Modulo $row->t11_modulo</mensaje>
						</resultado>
						EOT;
						exit();
					}
				}
			}
			//el ejecutivo existe en el area			
			$licencia = $row['t01_licencia'];
			$id_pc = $row['t11_id'];
			$Idagente = $row['t04_id_ejecutivo'];
			$fecha_bloqueo = $row['t04_fecha_bloqueo'];
			$servidor = $row['t02_servidor_ftp'];
			$usuario = $row['t02_usuario_ftp'];
			$password = $row['t02_password_ftp'];
			$nombre_area = $row['t02_area'];
			$password_agente = $row['t04_password'];
			$configuracion_general=$row['t02_configuracion_general'];

			//libero los registros que quedaron tomados
			$sSql='update gc07_solicitud set gc07_estado = 99, gc07_termino=now() where t04_id_ejecutivo = ' .  $Idagente . ' and gc07_termino is null';
			$stmt = $conn->prepare($sSql);
			$stmt->execute();

			//libero los registros de log que quedaron tomado
			$sSql='update gc08_log_solicitud set gc08_termino = gc08_fecha where t04_id_ejecutivo = ' . $Idagente . ' and gc08_termino is null';
                        $stmt = $conn->prepare($sSql);
                        $stmt->execute();
            		if ($ldap !='1')
            		{
				if ($password_agente <>$psw_agente)
				{ 
					echo <<<'EOT'
					<resultado>
						<estado>error</estado>
						<mensaje>Clave Incorrecta de Usuario</mensaje>
					</resultado>
					EOT;
                                        exit();
				}
			}
			//bajo la session anterior que se quedo conectada
			$sSql ='update t08_log_ejecutivo set t08_fecha_deslogeo=now() where t08_fecha_deslogeo is null and ';
			if (is_null($id_pc))
				$sSql .= ' t04_id_ejecutivo = ' .  $Idagente . ';';
			else
				$sSql .= ' (t04_id_ejecutivo = ' . $Idagente . ' or t11_id=' . $id_pc .');';

			$stmt = $conn->prepare($sSql);
    			$stmt->execute();
			if ($fecha_bloqueo <>'')
			{
				//desbloqueo al agente que esta entrando
				$sSql ='update t04_ejecutivo set t04_fecha_bloqueo=null where t04_id_ejecutivo = ' . $Idagente . ';';
				$stmt = $conn->prepare($sSql);
                		$stmt->execute();
			}
		}
		else
		{	//traer datos desde servidor central
			//el ejecutivo no existe en el area
			//buscamos si existe en otra area:

			$conn2 = db_connect('geko.vtr.cl', USER, PASS, 'gekocentral');
			
			$sSql =<<<'EOT'
				SELECT a.* FROM t04_ejecutivo a WHERE t04_usuario = '$agente' and t04_fecha_bloqueo is null 
				order by t04_fecha_creacion desc limit 1
				EOT;
			$rs=$conn2->query($sSql);
			if ($row = $rs->fetch())
			{
				$campos_carga = <<<'EOT'
				'$row->t04_nombres', 
				'$row->t04_apellido_paterno',
				'$row->t04_apellido_materno',
				'$row->t04_rut',
				'$row->t04_email',
				'$row->t04_usuario_tango',
				'$row->t04_observacion'
				EOT;
			}else
			{
				$campos_carga = 'null,null,null,null,null,null,null';
			}
			$sSql ='SELECT a.t03_id_supervisor,d.t01_licencia,t02_servidor_ftp,t02_usuario_ftp,t02_password_ftp,t02_area,t02_configuracion_general FROM t03_supervisor a join t02_area b on a.t02_id_area = b.t02_id_area join t10_usuario_servicio c on a.t10_id_usuario_servicio = c.t10_id_usuario_servicio and c.t01_id_servicio = b.t01_id_servicio join t01_servicio d on c.t01_id_servicio = d.t01_id_servicio and d.t01_id_servicio = b.t01_id_servicio WHERE a.t02_id_area =' . $area . ' and t03_fecha_bloqueo is null and t10_fecha_bloqueo is null limit 1';
			$rs=$conn2->query($sSql);
			if ($row = $rs->fetch())
			{	
				//tengo un supervisor activo en el area
				$licencia = $row->t01_licencia;
				$supervisor = $row->t03_id_supervisor;
				$servidor = $row->t02_servidor_ftp;
				$usuario = $row->t02_usuario_ftp;
				$password = $row->t02_password_ftp;
				$nombre_area = $row->t02_area;
				$configuracion_general=$row->t02_configuracion_general;
								
				//inserto el ejecutivo nuevo
				$sSql ="insert into t04_ejecutivo (t02_id_area,t03_id_supervisor,t04_fecha_creacion,
						t04_usuario,t04_password,t04_nombres,t04_apellido_paterno,t04_apellido_materno,
						t04_rut,t04_email,t04_usuario_tango,t04_observacion)						
						values($area,$supervisor,now(),'$agente','$psw_agente',$campos_carga)";
										
				$stmt = $conn2->prepare($sSql);
                $stmt->execute();                
				$Idagente = $conn2->lastInsertId("t04_ejecutivo_t04_id_ejecutivo_seq");

				//inserto el ejecutivo nuevo
				$sSql ="insert into t04_ejecutivo (t04_id_ejecutivo,t02_id_area,t03_id_supervisor,t04_fecha_creacion,
						t04_usuario,t04_password,t04_nombres,t04_apellido_paterno,t04_apellido_materno,
						t04_rut,t04_email,t04_usuario_tango,t04_observacion)
						values($Idagente,$area,$supervisor,now(),'$agente','$psw_agente',$campos_carga)";

				//lo cargo en el modelo local:				
				$stmt = $conn->prepare($sSql);
                $stmt->execute();
				

				//inserto la habilidad de emergencia (por defecto)
				$sSql ="INSERT INTO gc03_habilidad_ejecutivo(
						            gc01_id_habilidad, t02_id_area, t04_id_ejecutivo, t09_id_usuario, 
						            gc03_desde, gc03_hasta, gc03_prioridad)
						    VALUES (5, $area, $Idagente, 1, 
						    		'2017-01-01 00:00:00','2030-12-31 23:59:59',1);";

				$stmt = $conn2->prepare($sSql);
                $stmt->execute();
				$Idagente = $conn2->lastInsertId("t04_ejecutivo_t04_id_ejecutivo_seq");

				//lo cargo en el modelo local:
				$stmt = $conn->prepare($sSql);
                $stmt->execute();
				$Idagente = $conn2->lastInsertId("t04_ejecutivo_t04_id_ejecutivo_seq");
			}
			else
			{
				free_result($rs);
				//no tengo ejecutivo activo en el area y tampoco supervisor
				//inserto la alerta en el servidor y salgo con error				
				$sSql ="insert into t15_log_servidor(t15_fecha,t02_id_area,t15_estado,t15_descripcion,t15_codigo) 
					values (now(),$area,3,'Sin Supervisor Activo en la Sucursal',2);";
				$stmt = $conn->prepare($sSql);
 				$stmt->execute();	
				$sSql ="update t02_area set t02_estado = 3 where t02_id_area = $area";
				$stmt = $conn->prepare($sSql);
                $stmt->execute();?>
				<resultado>
					<estado>error</estado>
					<mensaje>No existe supervisor Activo en la sucursal, contacte a su supervisor</mensaje>
				</resultado>
				<?php
				exit();
			}
		}
		//Busco el id del PC en el modelo (por IP)
		$sSql = "select t11_id from t11_pc where t11_hostname='$host' and t02_id_area =$area limit 1;";
		$rs=$conn->query($sSql);
		if ($row = $rs->fetch())
		{	
			//tengo el pc en el modelo
			$id_pc = $row['t11_id']; 
			//echo("el id de PC es $id_pc");
		}
		else
		{
			$sSql = "insert into t11_pc(t11_ip,t11_hostname,t11_mac,t02_id_area,t11_fecha,t11_estado,t11_version,t11_botonera,t11_fecha_conexion)
					values ('$Ip','$host','$mac',$area,now(),1,'$version','$version',now());";
			$stmt = $conn->prepare($sSql);
            		$stmt->execute();
            		$id_pc = $conn->lastInsertId("t11_pc_t11_id_seq");			
		}

		$sSql ="update t11_pc set t11_botonera ='$version', t11_ip='$Ip',t11_hostname = '$host',t11_mac = '$mac', t11_fecha_conexion = now(),t11_estado = 2,t11_modulo=$modulo where t11_id = $id_pc;";

	 	$stmt = $conn->prepare($sSql);
 		$stmt->execute();

	
		$sSql ="Insert into t08_log_ejecutivo(t02_id_area,t04_id_ejecutivo,t08_fecha_logeo,t11_id,t08_estado) values($area," . $Idagente . ",now(),$id_pc,0)";
		$stmt = $conn->prepare($sSql);
        $stmt->execute();
        $id_log = $conn->lastInsertId("t08_log_ejecutivo_t08_id_log_seq");
		
		$sSql ="update t04_ejecutivo set t08_id_log = ". $id_log ." where t04_id_ejecutivo = ". $Idagente . "";
		
		$stmt = $conn->prepare($sSql);
        $stmt->execute();

		//bloqueo cualquier otra cuenta (de otras areas) del agente que esta entrando
		$sSql ="update t04_ejecutivo
		set t04_fecha_bloqueo=now() where t04_id_ejecutivo <> $Idagente and t04_usuario = '$agente' ;";
				
		$stmt = $conn->prepare($sSql);
        $stmt->execute();

        $sSql="Select count(*) from gc01_habilidad where t02_id_area=$area and gc01_derivacion='1';";
        $derivacion =0;
        $rs=$conn->query($sSql);
		if ($row = $rs->fetch())
		{	
			$derivacion =$row[0];
		}
		$sSql ="
		SELECT distinct t00_codigo,t00_descripcion
			FROM  t00_diccionario 
			WHERE t00_zona =  'Ejecutivo' and t00_codigo>=5 and t00_codigo<>99
		";
		
		$cantidad=0;
		$estados ="";
		foreach ($conn->query($sSql) as $data) 
		{		
			$cantidad +=1;
			$estados .="<estado$cantidad><codigo>" . $data["t00_codigo"] ."</codigo><descripcion>" . ewConvertToUtf8($data["t00_descripcion"]) . "</descripcion></estado$cantidad>";
		}
		?>	
		<resultado>
			<estado>ok</estado>
			<debug>si</debug>
            <area>
            	<servidor><?php echo($servidor);?></servidor>
            	<usuario><?php echo($usuario);?></usuario>
            	<password><?php echo($password);?></password>
                <nombre_area><?php echo($nombre_area);?></nombre_area>
                <derivacion><?php echo($derivacion)?></derivacion>
                <cfg><?php echo($configuracion_general);?></cfg>
            </area>
            <agente>
            	<id_agente><?php echo($Idagente);?></id_agente>
                <proceso><?php echo($proceso_defecto);?></proceso>
            	<id_log><?php echo($id_log);?></id_log>
            	<licencia><?php echo($licencia);?></licencia>
            	<id_pc><?php echo($id_pc);?></id_pc>
            </agente>
            <estados>
            	<cantidad><?php echo($cantidad)?></cantidad>
            	<?php echo($estados)?>
            </estados>
		</resultado>
		<?php
	}else{?>	
	<resultado>
		<estado>error</estado>
		<mensaje>Datos no enviados</mensaje>
	</resultado>
	<?php
	}?>
