B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=9.85
@EndOfDesignText@
#Region Shared Files
'#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
	'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
	'###########################################################################################################
	'######################           PULL         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
	'###########################################################################################################
	'######################           PUSH         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=github&Args=..\..\
	'###########################################################################################################
	'######################      PUSH TORTOISE GIT     #########################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=TortoiseGitProc&Args=/command:commit&Args=/path:"./../../"&Args=/closeonend:2
	'###########################################################################################################
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip

Sub Class_Globals
	Private Root As B4XView
	Private xui As XUI
	Public login As B4XMainPage
	Public principal As C_Principal
	Public clientes As C_Clientes
	Public cliente As C_Cliente
	Public productos As C_Productos
	Public updateAvailable As C_UpdateAvailable
	Public mapas As C_Mapas
	Public nuevoCliente As C_NuevoCliente
	Public ticketsDia As C_TicketsDia
	Public noVenta As C_NoVenta
	Public nota As C_Nota
	Public pedidos As C_Pedidos
	Public promos As C_Promos
	Public historico As C_Historico

	Public historicobat As C_historicobat
	Dim reqManager As DBRequestManager
	Dim v As String = Application.VersionName
	Dim ruta As String
	Dim tgl As Toggle
	Dim lat_gps, lon_gps As String
	Dim usuario As String
	Dim batt As Int
	Dim skmt As SQL
	Dim montoActual, clientesTotal, clientesVenta, clientesVisitados,almacen, rutaPreventa As String
	Dim server, fechaRuta As String
	Dim Logger As Boolean
	Dim mac_impresora As String
	Dim Phn As PhoneId
	
	Dim user As EditText
	Dim pass As EditText
	Dim c As Cursor
	Dim existe As String
	Dim paso1 As String
	Private IMEN As Label
	Dim IMEI As String = ""
	Dim alterno As String
	Private b_menu As Button
	Dim PopupMenu As RSPopupMenu
	Dim cmd As DBCommand
	Private PDF As Button
	Private bpv1 As BatteryProgressView
	Dim batterystatus(11) As Int
	Private bu As BatteryUtilities
	Private b_apk As Button
	Private i_engrane As ImageView
	Private p_Main As Panel
	Private p_appUpdate As Panel
	Private b_regesar As Button
	Private l_version As Label
	Private ImageView1 As ImageView
	Private Label2 As Label
	Dim Entrar As Button
	Dim tipo_venta As String = Subs.traeTipoVentaDeBD
	Dim bTerminarClicked As Boolean = False
	Private lv_server As ListView
	Private l_server As Label
	Private b_envioBD As Button
	Public Provider As FileProvider
	Public rutaBDBackup = ""
	Private B4XSwitch1 As B4XSwitch
	Private p_validacion As Panel
	Private B4XSwitch2 As B4XSwitch
	Dim x As Int
	Private et_codigo As EditText
	Dim buscandoActualizacion As Boolean = False
	Dim actualizacionRevisada As Boolean = False 'Parte de la funcionalidad "appUpdater"
	Private b_actualizacion As Button
	Private et_server As EditText
	Dim intentUsado As Boolean = False
	Private p_importarBDWA As Panel
	Private cb_importarBDWA As CheckBox
	
	Dim pkg As PackageManager
End Sub

Public Sub Initialize
'	B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Log("#####   CREAMOS MAINPAGE LOGIN")
	B4XPages.GetManager.LogEvents = True
	Root = Root1
	Root.LoadLayout("login")
'	B4XPages.SetTitle(Me, "Guna Preventa")

	
	login.Initialize
	B4XPages.AddPage("Login", login)
	principal.Initialize
	B4XPages.AddPage("Principal", principal)
	clientes.Initialize
	B4XPages.AddPage("Clientes", clientes)
	cliente.Initialize
	B4XPages.AddPage("Cliente", cliente)
	productos.Initialize
	B4XPages.AddPage("Productos", productos)
	updateAvailable.Initialize
	B4XPages.AddPage("updateAvailable", updateAvailable)
	mapas.Initialize
	B4XPages.AddPage("Mapas", mapas)
	nuevoCliente.Initialize
	B4XPages.AddPage("NuevoCliente", nuevoCliente)
	ticketsDia.Initialize
	B4XPages.AddPage("TicketsDia", ticketsDia)
	noVenta.Initialize
	B4XPages.AddPage("NoVenta", noVenta)
	nota.Initialize
	B4XPages.AddPage("Nota", nota)
	pedidos.Initialize
	B4XPages.AddPage("Pedidos", pedidos)
	promos.Initialize
	B4XPages.AddPage("Promos", promos)
	historico.Initialize
	B4XPages.AddPage("Historico", historico)
	historicobat.Initialize
	B4XPages.AddPage("historicobat", historicobat)
	
	
	p_Main.Height = Root.Height
	p_Main.Width = Root.Width
	ruta = Starter.ruta
	Provider.Initialize
	If File.Exists(File.DirInternal, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", File.DirInternal, "kmt.db")
	End If
	skmt.Initialize(File.DirInternal,"kmt.db", True)
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS IMPRESORA (HABILITADA)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PLAN_LEALTAD (PL_CLIENTE TEXT, PL_BANDERA TEXT)")
	
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ABONOSP(NOTA TEXT, CLIENTE TEXT, SALDO_PENDIENTE TEXT, FECHA TEXT)")

	
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS COMENTARIOS (COMENTARTIO TEXT, CLIENTE TEXT, DESCARGADO TEXT)")
'	skmt.ExecNonQuery("DROP TABLE IF EXISTS CAT_PROMOS_DESCUENTOS")
	Subs.agregaColumna("PLAN_LEALTAD", "DESCARGADO", "TEXT")
	Subs.agregaColumna("PEDIDO_CLIENTE", "PC_FACTURA", "INTEGER")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS GPS (HABILITADO)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_PROMOS_DESCUENTOS (CAT_PD_ALMACEN TEXT, CAT_PD_COD_PROMO TEXT, CAT_PD_RANGO INT, CAT_PD_VIGENCIA TEXT, CAT_PD_DESCUENTO TEXT, CAT_PD_PRODUCTO TEXT, CAT_PD_TIER TEXT)")
	Subs.agregaColumna("CAT_PROMOS_DESCUENTOS", "CAT_PD_RANGO2", "INT")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD2 (CAT_GP_CODPROMO TEXT, CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD TEXT, CAT_GP_DEV TEXT, CAT_GP_ALMACEN NUM, CAT_GP_ID TEXT, CAT_GP_NOMBRE TEXT, CAT_GP_IMP1 TEXT, CAT_GP_IMP2 TEXT, CAT_GP_PRECIO TEXT, CAT_GP_CLASIF TEXT, CAT_GP_STS TEXT, CAT_GP_TIPO TEXT, CAT_GP_SUBTIPO TEXT, CAT_GP_IMG )")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PROMO_ESP (HVD_CLIENTE)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_PROMO_ESP(CAT_PE_ID TEXT,CAT_PE_IDPROMO TEXT,CAT_PE_MONTO TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CUOTAS (HC_META6 TEXT, HC_META5 TEXT, HC_META4 TEXT, HC_META3 TEXT, HC_META2 TEXT, HC_META1 TEXT, HC_RUTA TEXT, HC_CUOTA1 TEXT, HC_CUOTA2 TEXT, HC_CUOTA3 TEXT, HC_CUOTA4 TEXT, HC_CUOTA5 TEXT, HC_CUOTA6 TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_GPS (HGDATE TEXT, HGLAT TEXT, HGLON TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_STAY_STORE (HSS_CODIGO TEXT, HSS_IN TEXT, HSS_OUT TEXT, HSS_TOT TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_STAY_OUT (HSO_INI TEXT, HSO_FIN TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS INVENT_X_ENVIAR (ALMACEN TEXT, PROID TEXT, CANTIDAD TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_RESUM_APK (HIST_RA_OBJMES TEXT, HIST_RA_VENTA TEXT, HIST_RA_TENDENCIA TEXT, HIST_RA_ALCANCE TEXT, HISR_RA_DRAOBJ TEXT, HIST_RA_DRAVTA TEXT, HIST_RA_DSOBJ TEXT, HIST_RA_DSVTA TEXT, HIST_RA_VPOOBJ TEXT, HIST_RA_VPOVTA TEXT, HIST_RA_COBCCC TEXT, HIST_RA_CTES TEXT, HIST_RA_ECO TEXT, HIST_RA_VISITPLAN TEXT, HIST_RA_VISIREAL TEXT, HIST_RA_COBVISIT TEXT, HIST_RA_FRECCOMPOBJ TEXT, HIST_RA_FRECCOMREAL TEXT, HIST_RA_VENTAMES1 TEXT, HIST_RA_VENTAMES2 TEXT, HIST_RA_VENTAMES3 TEXT, HIST_RA_VENTAMES4 TEXT, HIST_RA_RECHAZO TEXT, HIST_RA_RECHAZOPORCEN TEXT, HIST_RA_SEMANA1 TEXT, HIST_RA_SEMANA1_DIAS TEXT, HIST_RA_SEMANA1_DRA TEXT, HIST_RA_SEMANA2 TEXT, HIST_RA_SEMANA2_DIAS TEXT, HIST_RA_SEMANA2_DRA TEXT, HIST_RA_SEMANA3 TEXT, HIST_RA_SEMANA3_DIAS TEXT, HIST_RA_SEMANA4 TEXT, HIST_RA_SEMANA3_DRA TEXT, HIST_RA_SEMANA4_DIAS TEXT, HIST_RA_SEMANA4_DRA TEXT, HIST_RA_SEMANA5 TEXT, HIST_RA_SEMANA5_DIAS TEXT, HIST_RA_SEMANA5_DRA TEXT, HIST_RA_SEMANA1_LPT TEXT, HIST_RA_SEMANA2_LPT TEXT, HIST_RA_SEMANA3_LPT TEXT, HIST_RA_SEMANA4_LPT TEXT, HIST_RA_SEMANA5_LPT TEXT, HIST_RA_RUTA TEXT, HIST_RA_IDALMACEN TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_COMISIONES_MOVIL (HCM_IDALMACEN TEXT, HCM_RUTA TEXT, HCM_TOTAL_V TEXT, HCM_TOTAL_VIVE TEXT, HCM_TOTAL_GUNA TEXT,	HCM_TOTAL_BEB TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_GEOCERCA (HGCLIENTE TEXT, HGDATE TEXT, HGLAT TEXT, HGLON TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_FACE (HFCLIENTE TEXT, HFALIAS TEXT, HFRUTA TEXT, HFALMACEN TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_GPS(FECHA INTEGER, LAT TEXT, LON TEXT)")
	skmt.ExecNonQuery("CREATE VIEW IF NOT EXISTS CATALOGO AS Select CAT_GP_CLASIF, CAT_GP_ID FROM CAT_GUNAPROD UNION Select CAT_GP_CLASIF, CAT_GP_ID FROM CAT_GUNAPROD GROUP BY CAT_GP_CLASIF, CAT_GP_ID")
	skmt.ExecNonQuery("CREATE VIEW IF NOT EXISTS total_marcas AS 	Select  cat_gp_clasif, sum(pe_costo_tot) As total from CATALOGO, pedido where pe_proid = cat_gp_id 	And pe_cliente <> 0 	group by cat_gp_clasif")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_MARCAS_CUOTAS ( HMC_MARCA TEXT, HMC_TOTAL TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CODIGO_BARRAS(CODIGOKMTS TEXT, CODIGOB TEXT, LAT TEXT, LON TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ENCUESTA_MODULO1(CLIENTE TEXT,ALMACEN TEXT, P1 TEXT, P2 TEXT, P3 TEXT, P4 TEXT, P5 TEXT, P6 TEXT, P7 TEXT, P8 TEXT, P9 TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ENCUESTA_MODULO2 (CLIENTE TEXT, ALMACEN TEXT,P1 TEXT, P2 TEXT, P3 TEXT , P4 TEXT, P5 TEXT, P6 TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_ENCUESTA_PREGUNTA (CAT_EP_ID TEXT,CAT_EP_IDTIPOPREGUNTA TEXT,CAT_CE_DESCRIPCION TEXT,CAT_EP_PREGUNTA TEXT,CAT_EP_RES1_PRED TEXT,CAT_EP_RES2_PRED TEXT,CAT_EP_RES3_PRED TEXT,CAT_EP_ORDEN_PREGUNTA TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ENCUESTA_MODULO3(CLIENTE TEXT,ALMACEN TEXT, P1 TEXT, P2 TEXT, P3 TEXT, P4 TEXT, P5 TEXT, P6 TEXT, P7 TEXT, P8 TEXT, P9 TEXT, P10 TEXT, P11 TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ENCUESTA_MODULO4 (CLIENTE TEXT, ALMACEN TEXT,P1 TEXT, P2 TEXT, P3 TEXT , P4 TEXT, P5 TEXT, P6 TEXT, P7 TEXT, P8 TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ENCUESTA_MODULO5 (CLIENTE TEXT, ALMACEN TEXT,P1 TEXT, P2 TEXT, P3 TEXT , P4 TEXT, P5 TEXT, P6 TEXT, P7 TEXT, P8 TEXT, P9 TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENCUESTA2(HE_CLIENTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENCUESTA_CLIENTE (HEC_CLIENTE TEXT, HEC_MODULO TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENCUESTA_AVISO_GIRO (HEAV_CLIENTE TEXT, HEAV_MODULO TEXT, HEAV_AVISO TEXT, HEAV_GIRO TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_ENCUESTA (HE_CLIE TEXT, HE_RES TEXT, HE_FECHA TEXT, HE_TIPO TEXT, HE_LAT TEXT, HE_LON TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS kmt_info3(CAT_CL_FOTO BLOB, CAT_CL_NUM_SERIEFISICO TEXT, CAT_CL_MTOCOMPRA TEXT, CAT_CL_CEDIS TEXT, CAT_CL_LAT TEXT, CAT_CL_LONG TEXT, CAT_CL_FBAJA TEXT, CAT_CL_FALTA TEXT, CAT_CL_CP TEXT, CAT_CL_EDO TEXT, CAT_CL_MUNI TEXT, CAT_CL_COLONIA TEXT, CAT_CL_CALLE2 TEXT, CAT_CL_CALLE1 TEXT, CAT_CL_NOINT TEXT, CAT_CL_NOEXT TEXT, CAT_CL_CALLE TEXT, CAT_CL_EMAIL TEXT, CAT_CL_TELEFONO TEXT, CAT_CL_ATIENTE2 TEXT, CAT_CL_ATIENDE1 TEXT, CAT_CL_NOMBRE TEXT, CAT_CL_GIRO TEXT, CAT_CL_DIAS_VISITA TEXT, CAT_CL_TIPO_RUTA TEXT, CAT_CL_RUTA TEXT, CAT_CL_CODIGO TEXT, gestion NUMERIC)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_PRO2265(H_IDCLIENTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_PRO3054(H_IDCLIENTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_PRO3055(H_IDCLIENTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTA_SUPLENCIA(RS_RUTA TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TICKET_IMPRESO (idCliente TEXT)")
'	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_VARIABLES (CAT_VA_DESCRIPCION TEXT, CAT_VA_VALOR TEXT)")
	Subs.agregaColumna("HIST_ENCUESTA", "HE_LAT", "TEXT")
	Subs.agregaColumna("HIST_ENCUESTA", "HE_FOTO", "BLOB")
	Subs.agregaColumna("kmt_info3", "foto", "BLOB")
	Subs.agregaColumna("PEDIDO", "PE_RECALCULO", "TEXT")
	Subs.agregaColumna("PEDIDO", "PE_RECCEDIS", "TEXT")
	Subs.agregaColumna("PEDIDO", "PE_RECALCULOTOT", "TEXT")
	Subs.agregaColumna("HIST_ENCUESTA", "HE_LON", "TEXT")
	Subs.agregaColumna("HIST_VENTAS", "HVD_FECHA", "TEXT")
	Subs.agregaColumna("kmt_info3", "encuesta", "TEXT")
	Subs.agregaColumna("kmt_info3", "CAT_CL_CLASIFICADOR3", "TEXT")
	Subs.agregaColumna("kmt_info3", "CAT_CL_CLASIFICADOR2", "TEXT")
	Subs.agregaColumna("kmt_info3", "CAT_CL_TIPOCLIENTE", "TEXT")
	Subs.agregaColumna("kmt_info3", "CAT_CL_LIMITECREDITO", "TEXT")
	Subs.agregaColumna("kmt_info3", "CAT_CL_DIASCREDITO", "TEXT")
	Subs.agregaColumna("kmt_info3", "CAT_CL_BCREDITO", "TEXT") '##########################  CODIGO PARA CREDITOS ####################
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DEV", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_PA_BSEGMENTA", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_LISTAPRECIO", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_PA_SEGMENTAV", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_PA_BSEGMENTA", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_PA_SEGMENTAV", "TEXT")
	Subs.agregaColumna("PEDIDO", "PE_RECCANT", "TEXT")
	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna "P10" en la tabla
		c=skmt.ExecQuery("SELECT COUNT(*) AS fCol FROM pragma_table_info('ENCUESTA_MODULO3') WHERE name='P10'")
		c.Position = 0
		If c.GetString("fCol") = 0 Then 'Si no esta la columna FECHA la agregamos
			skmt.ExecNonQuery("ALTER TABLE ENCUESTA_MODULO3 ADD COLUMN P10 TEXT")
		End If
	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
		Try
			skmt.ExecNonQuery("ALTER TABLE ENCUESTA_MODULO3 ADD COLUMN P10 TEXT")
		Catch
			Log(LastException)
		End Try
	End Try
	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna "P11" en la tabla
		c=skmt.ExecQuery("SELECT COUNT(*) AS fCol FROM pragma_table_info('ENCUESTA_MODULO3') WHERE name='P11'")
		c.Position = 0
		If c.GetString("fCol") = 0 Then 'Si no esta la columna FECHA la agregamos
			skmt.ExecNonQuery("ALTER TABLE ENCUESTA_MODULO3 ADD COLUMN P11 TEXT")
		End If
	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
		Try
			skmt.ExecNonQuery("ALTER TABLE ENCUESTA_MODULO3 ADD COLUMN P11 TEXT")
		Catch
			Log(LastException)
		End Try
	End Try
	c=skmt.ExecQuery("select  COUNT(*) AS CUANTOS from HIST_STAY_OUT ")
	C.Position = 0
	If c.GetString("CUANTOS")  = 0 Then
		skmt.ExecNonQuery("INSERT INTO HIST_STAY_OUT(HSO_INI, HSO_FIN) VALUES (0,0)")
	End If
	C.Close
'	server = "http://keymon.com.mx:1782"
	'server = "http://201.99.139.28:1783"
'	reqManager.Initialize(Me, server)
	l_version.Text = Application.VersionName
	'este codigo es para lo del menu
	PopupMenu.Initialize("PopupMenu", b_menu)
	PopupMenu.AddMenuItem(0, 0, "View")
	PopupMenu.AddMenuItem(1, 1, "Edit")
	PopupMenu.AddMenuItem(2, 2, "Details")
	PopupMenu.AddMenuItem(3, 3, "Remove")
	' menu fin
	montoActual  = 0
	clientesTotal = 0
	clientesVenta =  0
	clientesVisitados = 0
	almacen = 0
	rutaPreventa =  0
	p_appUpdate.Visible = False
	'Revisamos si se disparo el intent de cargar la base de datos desde WhatApp.
	If Subs.traeUsarIntentBDWA Then
		Subs.importaBDDesdeWhatsApp
	End If
End Sub

Sub B4XPage_Appear
'	Log("buscandoActualizacion-" & buscandoActualizacion)
'	Log("actualizacionRevisada-" & actualizacionRevisada)
	'Buscamos actualización de app (appUpdater)
'	If Not(versionRevisadaHoy) And Not(actualizacionRevisada) And Starter.muestraProgreso = 0 Then
'		buscandoActualizacion = True
'		Entrar.Enabled = False
'		revisaActualizacion
'	End If
	cb_importarBDWA.Checked = Subs.traeUsarIntentBDWA
	If user.Text.Trim = "KMTS1" Then
		p_importarBDWA.Visible = True
	Else
		p_importarBDWA.Visible = False
	End If
	reqManager.Initialize(Me, Starter.server)
	If Starter.muestraProgreso = 1 Then
		muestraProgreso("Descargando nueva versión, un momento por favor.")
		Starter.muestraProgreso = 0
	End If
	Dim ph As Phone 'Get Id Device
	Dim DeviceID As String = ph.GetSettings("android_id").ToUpperCase
'	LogColor($"//////////////////   DeviceID: ${DeviceID} ////////////////// "$, Colors.Blue)
	LogColor("Revisa permisos Phone_State", Colors.Green)
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		IMEN.Text =""
		IMEI = ""
'		LogColor($"//////////////////  IMEI: ${IMEI} ////////////////// "$, Colors.Blue)
		IMEI=""  'Pruebas
	End If
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		StartService(Tracker)
		Log("Start Tracker")
	Else
		ToastMessageShow("Sin permisos de ubicacion", True)
	End If
	server = Starter.server
	tgl.Initialize()
	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		Sleep(500)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	c=skmt.ExecQuery2("select count(*) as CUANTOS from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
	c.Position = 0
	If c.GetString("CUANTOS") = 0 Then
		LogColor($"No hay fecha: ${c.GetString("CUANTOS")}"$, Colors.Red)
		cmd.Initialize
		cmd.Name = "select_fecha"
		reqManager.ExecuteQuery(cmd , 0, "fecha")
		Msgbox("AJUSTAR FECHA","AVISO") 'Ignore
		B4XPage_Appear
	Else
		LogColor($"Si hay fecha: ${c.GetString("CUANTOS")}"$, Colors.Green)
		c=skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("FECHA"))
		c.Position =0
		Dim sDate, sTime As String
		DateTime.DateFormat = "yyyyMMdd"
		sDate=DateTime.Date(DateTime.Now)
'		If sDate > "20220701" Then
'			Msgbox("INSTALAR NUEVO APK" ,"AVISO") 'Ignore
'			B4XPage_Appear
'		End If
		If c.GetString("CAT_VA_VALOR") > sDate Then
			Msgbox("AJUSTAR LA FECHA YA QUE ES MENOR AL SISTEMA" ,"AVISO") 'Ignore
			B4XPage_Appear
		End If
	End If
	bu.Initialize
	batterystatus = bu.BatteryInformation
	'Obtenemos el usuario registrado
	CallSubDelayed(FirebaseMessaging, "SubscribeToTopics")
	dameUsuario
	c = skmt.ExecQuery("SELECT HABILITADA FROM IMPRESORA")
	If c.RowCount >  0 Then
		c.Position = 0
		If c.GetString("HABILITADA") = 1 Then
			B4XSwitch1.Value = True
		Else If c.GetString("HABILITADA") = 0 Then
			B4XSwitch1.Value = False
		End If
	Else
		B4XSwitch1.Value = False
	End If
	c = skmt.ExecQuery("SELECT HABILITADO FROM GPS")
	If c.RowCount = 0 Then
		skmt.ExecNonQuery2("INSERT INTO GPS VALUES (?)", Array As Object(0))
	End If
	c = skmt.ExecQuery("SELECT HABILITADO FROM GPS")
	If c.RowCount >  0 Then
		c.Position = 0
		If c.GetString("HABILITADO") = 1 Then
			B4XSwitch2.Value = True
		Else If c.GetString("HABILITADO") = 0 Then
			B4XSwitch2.Value = False
		End If
	Else
		B4XSwitch2.Value = False
	End If
	Subs.guardaAppInfo
	
'	If Subs.traeAlmacen <> "NA" Then
'		Dim cmd As DBCommand
'		cmd.Initialize
'		cmd.Name = "selectVersionAppGuna" 'Antes select_usuario_guna_GV2_1
'		cmd.Parameters = Array As Object(almacen)
'		reqManager.ExecuteQuery(cmd , 0, "versionApp")
'	End If
End Sub
'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub Entrar_Click
	Dim r As Reflector
	Dim Api As Int
	Dim PP As Phone
	user.Text = user.Text.trim
	LogColor(Starter.server, Colors.Blue)
	Api = r.GetStaticField("android.os.Build$VERSION", "SDK_INT")
	If Api < 9 Then
		'Old device
		If File.Exists(File.DirInternal, "__id") Then
			IMEI =  File.ReadString(File.DirInternal, "__id")
			Log(1&"-"&IMEI)
		Else
			Dim id As Int
			id = Rnd(0x10000000, 0x7FFFFFFF)
			File.WriteString(File.DirInternal, "__id", id)
			IMEI =  id
			Log(2&"-"&IMEI)
		End If
	Else
		'New device
		IMEI =  r.GetStaticField("android.os.Build", "SERIAL")
		Log(3&"-"&IMEI)
	End If
	If IMEI.ToLowerCase = "unknown" Then
		IMEI = PP.GetSettings("android_id")
	End If
	Log("IMEI = " &  IMEI)
	If user.Text = "ALTERNO" Then
		c=skmt.ExecQuery2("select CAT_CO_CONFIGURACION, CAT_CO_RESULTADO from CAT_CODIGOS where CAT_CO_PONDERACION =1 AND CAT_CO_ACCION = ?", Array As String("SERVER"))
		c.Position =0
		server = c.GetString("CAT_CO_CONFIGURACION")
		alterno = c.GetString("CAT_CO_RESULTADO")
		c.Close
		If alterno = 1 Then
			skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 1 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 2", Array As String ("SERVER"))
			skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 0 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 1", Array As String ("SERVER"))
		Else if alterno = 2 Then
			skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 1 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 1", Array As String ("SERVER"))
			skmt.ExecNonQuery2("UPDATE CAT_CODIGOS SET CAT_CO_PONDERACION = 0 WHERE CAT_CO_ACCION = ? AND CAT_CO_RESULTADO = 2", Array As String ("SERVER"))
		End If
		c=skmt.ExecQuery2("select CAT_CO_CONFIGURACION, CAT_CO_RESULTADO from CAT_CODIGOS where CAT_CO_PONDERACION =1 AND CAT_CO_ACCION = ?", Array As String("SERVER"))
		c.Position =0
		server = c.GetString("CAT_CO_CONFIGURACION")
		user.Text = server
		c.Close
'		reqManager.Initialize(Me, server)
	else if user.Text = "KMTS1" Then
		skmt.ExecNonQuery("delete from usuarioa")
		skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, pass.Text))
		skmt.ExecNonQuery("delete from cat_almacen")
		skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (pass.Text))
		skmt.ExecNonQuery("delete from VERSION")
		skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.1"))
		B4XPages.ShowPage("Principal")
	else if user.Text = "BERNA1" Then
		skmt.ExecNonQuery("delete from usuarioa")
		skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, "1"))
		skmt.ExecNonQuery("delete from cat_almacen")
		skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object ("1"))
		skmt.ExecNonQuery("delete from VERSION")
		skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object ("2.1"))
		B4XPages.ShowPage("Principal")
	else if user.Text = "IMEI" Then
		user.Text = IMEI
	End If
	c=skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
	c.Position=0
	existe = c.GetString("EXISTE1")
	If Subs.traeAlmacen <> "NA" Then
		cmd.Initialize
		cmd.Name = "selectVersionAppGuna"
		cmd.Parameters = Array As Object(Subs.traeAlmacen)
		reqManager.ExecuteQuery(cmd , 0, "traeVersion")
	End If
	If existe = 0 Then
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_usuario_guna_GV2_10" 'Antes select_usuario_guna_GV2_1
		cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.Trim)
		reqManager.ExecuteQuery(cmd , 0, "usuario_10")
'		If IMEI = "" Then
'			Dim cmd As DBCommand
'			cmd.Initialize
'			cmd.Name = "select_usuario_guna_GV2_10" 'Antes select_usuario_guna_GV2_1
'			cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.Trim)
'			reqManager.ExecuteQuery(cmd , 0, "usuario_10")
'		Else
'			If IMEI = "" Then
'				Dim cmd As DBCommand
'				cmd.Initialize
'				cmd.Name = "select_usuario_guna_GV2_10"
'				cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.Trim)
'				reqManager.ExecuteQuery(cmd , 0, "usuario_10")
'			Else
'				Dim cmd As DBCommand
'				cmd.Initialize
'				cmd.Name = "select_usuario_guna_GV2_10" 'Antes select_usuario_guna_GV2
'				cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.trim)
'				Log("Mandamos: "&user.Text&"|"& pass.Text)
'				reqManager.ExecuteQuery(cmd , 0, "usuario_10")
'			End If
'		End If
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_version_GV2"
		reqManager.ExecuteQuery(cmd , 0, "version")
	Else
		usuario = user.Text
		B4XPages.ShowPage("Principal")
	End If
End Sub

Sub Entrar_LongClick
'	dim a as int = "a"
End Sub

Private Sub user_EnterPressed
	If user.text = "KMTS1" Then Entrar.Enabled = True
End Sub

Sub JobDone(Job As HttpJob)
	Log("JOBDONE MAINPAGE")
	Log(Job.Success)
	If Job.Success = False Then
		LogColor("Error: " & Job.tag & " : " & Subs.parseHTTPError(Job.ErrorMessage), Colors.red)
'		ToastMessageShow("Error: " & Job.ErrorMessage, True)
	Else
		LogColor("JobDone: '" & reqManager.HandleJob(Job).tag & "' - Registros: " & reqManager.HandleJob(Job).Rows.Size, Colors.Green)  'Mod por CHV - 211027
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "version" Then 'query tag
				For Each records() As Object In result.Rows
					skmt.ExecNonQuery("delete from VERSION")
					Dim CAT_VE_VERSION As String = records(result.Columns.Get("CAT_VE_VERSION"))
					skmt.ExecNonQuery2("INSERT INTO VERSION(NOVERSION) VALUES (?)", Array As Object (CAT_VE_VERSION))
				Next
			End If

			If result.Tag = "select_fechat" Then 'query tag
				For Each records() As Object In result.Rows
					For Each k As String In result.Columns.Keys
						Log("select_fechat: " & k & ": " & records(result.Columns.Get(k)))
					Next
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "agencia" Then 'query tag
				For Each records() As Object In result.Rows
					Dim ID_ALMACEN As String = records(result.Columns.Get("ID_ALMACEN"))
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result1 As DBResult = B4XPages.MainPage.reqManager.HandleJob(Job)
			If result1.Tag = "CHECAENCUESTA" Then 'query tag
				For Each records() As Object In result1.Rows
					Dim CUANTOSENCUESTA As String = records(result1.Columns.Get("CUANTOS"))
					Log(CUANTOSENCUESTA)
				Next
				Dim sDate,sTime As String
				DateTime.DateFormat = "MM/dd/yyyy"
				sDate=DateTime.Date(DateTime.Now)
				sTime=DateTime.Time(DateTime.Now)
				If CUANTOSENCUESTA = "0" Then
					cmd.Initialize
					cmd.Name ="insert_drop_GV2_4"
					cmd.Parameters = Array As Object(usuario,Subs.traeRuta,sDate,"",sTime,"","","","","ENCUESTA",almacen,Application.VersionName,Starter.encuesta)
					B4XPages.MainPage.reqManager.ExecuteCommand(cmd , "inst_drop")
				End If
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "fecha" Then 'query tag
				For Each records() As Object In result.Rows
					Dim FECHA_HOY As String = records(result.Columns.Get("FECHA"))
					skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA"))
					skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA",FECHA_HOY))
				Next
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "usuario" Then 'query tag
				For Each records() As Object In result.Rows
					Dim name As String = records(result.Columns.Get("USUARIO"))
					Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
					Dim IMEI_BASE As String = records(result.Columns.Get("CAT_LO_IDTELEFONO"))
					Log(records(result.Columns.Get("CAT_LO_IDTELEFONO")) )
				Next
				paso1 = 1
				ToastMessageShow(name, False)
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "usuario_10" Then 'query tag
				For Each records() As Object In result.Rows
					Dim name As String = records(result.Columns.Get("USUARIO"))
					Dim ID_ALMACEN As String = records(result.Columns.Get("CAT_LO_AGENCIA"))
					Dim IMEI_BASE As String = records(result.Columns.Get("CAT_LO_IDTELEFONO"))
					Private version As String =  records(result.Columns.Get("CAT_AL_VERSION"))
					Private versionador As String =  records(result.Columns.Get("CAT_AL_VERSIONADOR"))
					Private actualizarAplicacion As String =  records(result.Columns.Get("CAT_AL_ACTUALIZACION"))
				Next
				skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("VERSION_NUEVA"))
				skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("VERSION_NUEVA", version))
				skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FORZAR_ACTUALIZACION"))
				skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FORZAR_ACTUALIZACION", actualizarAplicacion))
'				skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("VERSION_NUEVA"))
'				skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("VERSION_NUEVA", version))
				Log("|"&name&"|")
				Log($">>>>  GUARDAMOS NUEVA VERSION: ${version}, ${actualizarAplicacion}"$)
				paso1 = 1
				IMEI_BASE = ""
				IMEI = ""
			End If

			If result.Tag = "traeVersion" Then 'query tag
				For Each records() As Object In result.Rows
					Private version As String =  records(result.Columns.Get("CAT_AL_VERSION"))
					Private actualizarAplicacion As String =  records(result.Columns.Get("CAT_AL_ACTUALIZACION"))
				Next
				skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("VERSION_NUEVA"))
				skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("VERSION_NUEVA", version))
				skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FORZAR_ACTUALIZACION"))
				skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FORZAR_ACTUALIZACION", actualizarAplicacion))
				Log($">>>>  GUARDAMOS NUEVA VERSION: ${version}, ${actualizarAplicacion}"$)
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "geopass" Then 'query tag
				For Each records() As Object In result.Rows
					Dim cuenta As String = records(result.Columns.Get("CUENTA"))
				Next
				If cuenta = "1" Then
					p_validacion.Visible = False
					B4XSwitch2.Value = True
					skmt.ExecNonQuery2("UPDATE GPS SET HABILITADO = (?)",Array As Object(1))
					et_codigo.Text = ""
					Private c2 As Cursor = skmt.ExecQuery("select distinct CAT_CL_RUTA from kmt_info3 where CAT_CL_RUTA not in (select * from ruta_suplencia)")
					c2.Position = 0
					Private rutades As String = c2.GetString("CAT_CL_RUTA")
					c2.Close
					Private c2 As Cursor = skmt.ExecQuery("SELECT ID_ALMACEN FROM CAT_ALMACEN")
					c2.Position = 0
					Private almacendes As String = c2.GetString("ID_ALMACEN")
					c2.Close
					Dim cmd As DBCommand
					cmd.Initialize
					cmd.Name = "delete_geoPass_GUNA"
'					Log(Subs.traeAlmacen&", "& Subs.traeRuta)
					cmd.Parameters = Array As Object( almacendes,rutades)
					reqManager.ExecuteCommand(cmd , "traeGeoPass")
				Else If cuenta = "0" Then
					MsgboxAsync("Codigo incorrecto","Atención")
					p_validacion.Visible = False
					B4XSwitch2.Value = False
					skmt.ExecNonQuery2("UPDATE GPS SET HABILITADO = (?)",Array As Object(0))
					et_codigo.Text = ""
				End If
			End If
		End If

		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "carga_encuesta" Then 'query tag
				For Each records() As Object In result.Rows
					Dim CAT_EP_ID As String = records(result.COLUMNS.GET("CAT_EP_ID"))
					Dim CAT_EP_IDTIPOPREGUNTA As String = records(result.COLUMNS.GET("CAT_EP_IDTIPOPREGUNTA"))
					Dim CAT_CE_DESCRIPCION As String = records(result.COLUMNS.GET("CAT_CE_DESCRIPCION"))
					Dim CAT_EP_PREGUNTA As String = records(result.COLUMNS.GET("CAT_EP_PREGUNTA"))
					Dim CAT_EP_RES1_PRED As String = records(result.COLUMNS.GET("CAT_EP_RES1_PRED"))
					Dim CAT_EP_RES2_PRED As String = records(result.COLUMNS.GET("CAT_EP_RES2_PRED"))
					Dim CAT_EP_RES3_PRED As String = records(result.COLUMNS.GET("CAT_EP_RES3_PRED"))
					Dim CAT_EP_ORDEN_PREGUNTA As String = records(result.COLUMNS.GET("CAT_EP_ORDEN_PREGUNTA"))
					skmt.ExecNonQuery2("INSERT INTO CAT_ENCUESTA_PREGUNTA (CAT_EP_ID ,CAT_EP_IDTIPOPREGUNTA ,CAT_CE_DESCRIPCION ,CAT_EP_PREGUNTA ,CAT_EP_RES1_PRED ,CAT_EP_RES2_PRED ,CAT_EP_RES3_PRED ,CAT_EP_ORDEN_PREGUNTA ) VALUES (?,?,?,?,?,?,?,?)", Array As Object (CAT_EP_ID ,CAT_EP_IDTIPOPREGUNTA ,CAT_CE_DESCRIPCION ,CAT_EP_PREGUNTA ,CAT_EP_RES1_PRED ,CAT_EP_RES2_PRED ,CAT_EP_RES3_PRED ,CAT_EP_ORDEN_PREGUNTA))
				Next
			End If
		End If
		Job.Release
	End If

	Log($"Paso1 = ${paso1} - Name: ${name} - IMEI: ${IMEI} - IMEI_BASE: ${IMEI_BASE}"$)
	If paso1 = 1 Then
		If IMEI = "" Then
			If user.Text = "KMTS1" Then name = "OKActivo"
			If name = "OKActivo"  Then
				skmt.ExecNonQuery("delete from usuarioa")
				skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, pass.Text))
				skmt.ExecNonQuery("delete from cat_almacen")
				skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
				usuario = user.Text
				B4XPages.ShowPage("Principal")
			Else If name  = "OKExpirado" Then
				Msgbox("Usuario Expirado llamar al administrador","") 'Ignore
			Else If name = "OKCancelado" Then
				Msgbox("Usuario Cancelado llamar al administrador","") 'Ignore
			Else
				Msgbox("Usuario o password No validos","") 'Ignore
			End If
			paso1 = 0
		Else
			If name = "OKActivo" & IMEI And  IMEI = IMEI_BASE Then
				If name = "OKActivo" & IMEI Then
					skmt.ExecNonQuery("delete from usuarioa")
					skmt.ExecNonQuery2("INSERT INTO USUARIOA VALUES (?,?)", Array As Object(user.Text, pass.Text))
					skmt.ExecNonQuery("delete from cat_almacen")
					skmt.ExecNonQuery2("INSERT INTO CAT_ALMACEN(ID_ALMACEN) VALUES (?)", Array As Object (ID_ALMACEN))
					usuario = user.Text
					B4XPages.ShowPage("Principal")
				Else If name  = "OKExpirado"& IMEI Then
					Msgbox("Usuario Expirado llamar al administrador","") 'ignore
				Else If name = "OKCancelado"& IMEI Then
					Msgbox("Usuario Cancelado llamar al administrador","") 'ignore
				Else
					Msgbox("Usuario o password No validos","") 'ignore
				End If
				paso1 = 0
			Else IF  name = "OKActivo" Then
				Msgbox("Telefono no VALIDO!","") 'ignore
			Else
				Msgbox("Usuario o password No validos","") 'ignore
			End If
		End If
	End If
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	Log("closreq")
	Sleep(0)
	If p_appUpdate.IsInitialized And p_appUpdate.Visible Then
		p_appUpdate.Visible = False
		Return False
	End If
	If Not(p_appUpdate.Visible) Then
		Log("ExitApplication")
		ExitApplication
	End If
	Return True
End Sub

Sub GPS_LocationChanged (Location1 As Location)
	If user.text = "GPS" Then
		user.Text=Location1.Latitude
		pass.text=Location1.Longitude
	End If
End Sub

Sub PopupMenu_Dismiss
	ToastMessageShow("PopupMenu dismissed", False)
End Sub

Sub PopupMenu_MenuItemClick (ItemId As Int) As Boolean
	ToastMessageShow("Item " & ItemId & " clicked.", False)
	Return False
End Sub

Sub b_menu_Click
	PopupMenu.Show
End Sub

Sub PDF_Click

End Sub

Sub dameUsuario
	c=skmt.ExecQuery2("select count(*) as EXISTE1 from usuarioa where usuario = ?", Array As String(user.Text))
	c.Position=0
	existe = c.GetString("EXISTE1")
	c.Close
	If existe > 0 Then
		c=skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		usuario = c.GetString("USUARIO")
	Else
		usuario = "SINUSUARIO"
	End If
End Sub

'#if Java
'import java.util.concurrent.Callable;
'import com.google.android.gms.ads.identifier.AdvertisingIdClient;
'import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
'
'public static void GetAdvertisingId() {
'   BA.runAsync(processBA, mostCurrent, "advertisingid_ready", new Object[] {false, ""}
'       , new Callable<Object[]>() {
'                   @Override
'                   public Object[] call() throws Exception {
'                       String id = AdvertisingIdClient.getAdvertisingIdInfo(mostCurrent).getId();
'                       return new Object[] {true, id};
'                   }
'               }); }
'#End If

Sub copiaDB
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	Dim theDir As String = ""
	If Result Then
		Dim theDir As String
		Try
			File.MakeDir(File.DirRootExternal,"kmts")
			theDir = "/kmts"
		Catch
			theDir = ""
		End Try
		rutaBDBackup = File.DirRootExternal&theDir
		Try
			File.Copy(File.DirInternal,"kmt.db",File.DirRootExternal&theDir,"cedex_kmt.db")
			ToastMessageShow("Listo", False)
		Catch
			ToastMessageShow("No se pudo hacer la copia: "&LastException, True)
		End Try
	Else
		ToastMessageShow("Sin permisos", False)
	End If
	Log(rutaBDBackup)
End Sub

Sub b_apk_Click
	StartService(appUpdater)
End Sub

'appUpdater - Mostramos el anuncio de que se esta descargando el nuevo apk
Sub muestraProgreso(mensaje As String)
	ProgressDialogShow(mensaje)
End Sub

'appUpdater - Ocultamos el anuncio de que se esta descargando el nuevo apk
Sub ocultaProgreso
	ProgressDialogHide
End Sub

Sub i_engrane_Click
	p_appUpdate.Left = (Root.Width/2) - (p_appUpdate.Width/2)
	lv_server.Clear
	lv_server.AddSingleLine("http://keymon.net:1782")
	If user.Text = "KMTS1" Then lv_server.AddSingleLine("http://10.0.0.205:1782")
	l_server.Text = Starter.server
	et_server.Text = Starter.server
	Subs.panelVisible(p_appUpdate,0,0)
	p_appUpdate.Height = Root.Height
	p_appUpdate.Width = Root.Width
	c = skmt.ExecQuery("SELECT HABILITADA FROM IMPRESORA")
	If c.RowCount = 0 Then
		skmt.ExecNonQuery2("INSERT INTO IMPRESORA VALUES (?)", Array As Object(0))
	End If
	c = skmt.ExecQuery("SELECT HABILITADO FROM GPS")
	If c.RowCount = 0 Then
		skmt.ExecNonQuery2("INSERT INTO GPS VALUES (?)", Array As Object(0))
	End If
	If user.Text.Trim = "KMTS1" Then
		p_importarBDWA.Visible = True
	Else
		p_importarBDWA.Visible = False
	End If
End Sub

Sub b_regesar_Click
'	Subs.panelVisible(p_Main,0,0)
	p_appUpdate.Visible = False
	skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DBReqServer"))
	skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DBReqServer", et_server.Text))
	Starter.server =  et_server.Text
	Starter.reqManager.Initialize(Me, et_server.Text)
End Sub

'Sub i_engrane_LongClick
'	copiaDB
'End Sub

Private Sub lv_server_ItemClick (Position As Int, Value As Object)
	Starter.server = Value
	l_server.Text = Value
	et_server.Text = Value
	skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DBReqServer"))
	skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DBReqServer", Value))
	Starter.reqManager.Initialize(Me, Value)
	ToastMessageShow("Servidor modificado", False)
End Sub

'Enviamos la base de datos por correo
Private Sub b_envioBD_Click
'	copiaDB
'	Sleep(1000)
	Dim FileName As String = "kmt.db"
	'copy the shared file to the shared folder
	Log("xxxxxx:"&Provider.SharedFolder)
	Sleep(1000)
	File.Copy(File.DirInternal, FileName, Provider.SharedFolder, FileName)
	Dim email As Email
	email.To.Add("cheveguerra@gmail.com")
	email.Subject = "subject"
	email.Attachments.Add(Provider.GetFileUri(FileName))
'	email.Attachments.Add(Provider.GetFileUri(FileName)) 'second attachment
	Dim in As Intent = email.GetIntent
	in.Flags = 1 'FLAG_GRANT_READ_URI_PERMISSION
	StartActivity(in)
End Sub

Private Sub B4XSwitch1_ValueChanged (Value As Boolean)
	If Value Then
		Log("1")
		skmt.ExecNonQuery2("UPDATE IMPRESORA SET HABILITADA = (?)",Array As Object(1))
	Else
		Log("desactivado")
		skmt.ExecNonQuery2("UPDATE IMPRESORA SET HABILITADA = (?)",Array As Object(0))
	End If
End Sub

Private Sub B4XSwitch2_ValueChanged (Value2 As Boolean)
	c = skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String("CARGA_DIA"))
	If c.RowCount > 0 Then
		c.Position = 0
		If c.GetString("CAT_VA_VALOR") = 1 Then
			If Value2  Then
				p_validacion.Visible = True
				p_validacion.Left = (Root.Width/2) - (p_appUpdate.Width/2)
				Subs.panelVisible(p_validacion,0,0)
				p_validacion.Height = Root.Height
				p_validacion.Width = Root.Width
			Else
				skmt.ExecNonQuery2("UPDATE GPS SET HABILITADO = (?)",Array As Object(0))
			End If
		Else
			MsgboxAsync("Por favor primero haz carga de día","Atención")
			B4XSwitch2.Value = False
		End If
	Else
		MsgboxAsync("Por favor primero haz carga de día","Atención")
		B4XSwitch2.Value = False
	End If
End Sub

Private Sub p_validacion_Click
End Sub

Private Sub b_cancelarcodigo_Click
	p_validacion.Visible = False
	et_codigo.Text = ""
	B4XSwitch2.Value = False
End Sub

Private Sub b_aceptar_Click
	If et_codigo.Text <> "" Then
		Private c2 As Cursor = skmt.ExecQuery("select distinct CAT_CL_RUTA from kmt_info3 where CAT_CL_RUTA not in (select * from ruta_suplencia)")
		c2.Position = 0
		Private rutades As String = c2.GetString("CAT_CL_RUTA")
		c2.Close
		Private c2 As Cursor = skmt.ExecQuery("SELECT ID_ALMACEN FROM CAT_ALMACEN")
		c2.Position = 0
		Private almacendes As String = c2.GetString("ID_ALMACEN")
		c2.Close
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_geoPass_GUNA"
		cmd.Parameters = Array As Object(et_codigo.Text, almacendes, rutades)
		reqManager.ExecuteQuery(cmd , 0, "geopass")
	Else If et_codigo.Text = "" Then
		MsgboxAsync("Ingresa un codigo","Atención")
		p_validacion.Visible = False
		B4XSwitch2.Value = False
		skmt.ExecNonQuery2("UPDATE GPS SET HABILITADO = (?)",Array As Object(0))
		et_codigo.Text = ""
	End If
	
'	c = skmt.ExecQuery2("SELECT CAT_VA_VALOR FROM CAT_VARIABLES WHERE CAT_VA_DESCRIPCION =? ", Array As String("pasword"))
'	Log(c.RowCount)
'	If c.RowCount > 0 Then
'		c.Position = 0
'		Log(c.GetString("CAT_VA_VALOR"))
'		If c.GetString("CAT_VA_VALOR") = et_codigo.Text Then
'			
'			p_validacion.Visible = False
'	
'			B4XSwitch2.Value = True
'			skmt.ExecNonQuery2("UPDATE GPS SET HABILITADO = (?)",Array As Object(1))
'			et_codigo.Text = ""
'		Else If c.GetString("CAT_VA_VALOR") <> et_codigo.Text Then
'			MsgboxAsync("Codigo incorrecto","Atención")
'			p_validacion.Visible = False
'			B4XSwitch2.Value = False
'			skmt.ExecNonQuery2("UPDATE GPS SET HABILITADO = (?)",Array As Object(0))
'			et_codigo.Text = ""
'		End If
'	Else If c.RowCount = 0 Then
'		MsgboxAsync("Codigo incorrecto","Atención")
'		p_validacion.Visible = False
'		B4XSwitch2.Value = False
'		skmt.ExecNonQuery2("UPDATE GPS SET HABILITADO = (?)",Array As Object(0))
'	End If
End Sub

Sub revisaActualizacion 'Parte de la funcionalidad "appUpdater"
	'################################################
	'##   Hay que subir el nuevo APK al servidor.                                  ##
	'##   La ruta en el servidor es: \\10.0.0.205\e$\Cargas\MOVIL\Guna  ##
	'##   Hay que actualizar la version en el archivo "gunaPreventa.ver"  ##
	'################################################
	LogColor("Buscarmos archivo Ver", Colors.red)
	Private link As String = "https://keymon.net/movil/guna/gunaPreventa.ver"
	Wait For (traeArchivoVer(Me, link)) JobDone (j As HttpJob)
	If j.Success Then
		LogColor("Archivo .VER encontrado.", Colors.red)
		Try
			Dim app() As String = Regex.Split(Chr(9),j.GetString)
			' // Set the data
			Starter.newApp.appLink = app(3)   'Liga a nuevo apk
			Starter.newApp.newMsg = app(1)  'Texto de que hay actualizacion
			Starter.newApp.okMsg = app(2)    'Texto de app al corriente
			Starter.newApp.version = app(0)   'Version actual
			Log($"Application.VersionName=${Application.VersionName}, newApp=${Starter.newApp}"$)
			'Guardamos la fecha de la última revisión en CAT_VARIABLES.
			DateTime.DateFormat = "yyyyMMdd"
			skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("REVISION_APK"))
			skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("REVISION_APK", DateTime.Date(DateTime.Now)))
			' // App version check
			If Starter.newApp.version = Application.VersionName  Then
				Starter.newApp.update = False
				LogColor("No hay nuevo APK", Colors.red)
				B4XPages.MainPage.Entrar.Enabled = True
			End If
			If Starter.newApp.version <> Application.VersionName  Then
				Starter.newApp.update = True
				LogColor("Hay nuevo APK", Colors.red)
				b_actualizacion.Visible = True
				CallSubDelayed(appUpdater, "download_newApk")
			End If
		Catch
			LogColor("appUpdater(), Job Failed, error  " & LastException.Message, Colors.red)
			If Msgbox2("Hubo un error: " & LastException.Message, "FALLO LA ACTUALIZACIÓN", "OK", "", "", Null) = DialogResponse.POSITIVE Then 'Ignore
				ExitApplication
			End If
		End Try
	Else
'		LogColor("appUpdater(), Job Failed " & link & CRLF & LastException.Message, Colors.Red)
		If Msgbox2("Es necesaria una conexión a internet, por favor revise su conexión y vuelva a intentar", "ATENCIÓN", "OK", "", "", Null) = DialogResponse.POSITIVE Then 'Ignore
			ExitApplication
		End If
	End If
	j.Release
End Sub

'En el servidor se necesita un archivo de texto (.ver) que tenga los siguientes
'datos separados por un tabulador:
' Campo 0 = 4.10.10	<-- Esta es la version de la aplicación disponible.
' Campo 1 = Hay una nueva actualizacion disponible.  <-- Mensaje para cuando hay actualización.
' Campo 2 = Tu version es la ultima.	<--- Mensaje para cuando no hay actualización.
' Campo 3 = https://keymon.lat/movil/guna/Guna_Preventa.apk	<--- Liga al apk de la actualización.
Sub traeArchivoVer (Callback As Object, link As String) As HttpJob 'Parte de la funcionalidad "appUpdater"
	Dim j As HttpJob
	j.Initialize("", Callback)
	j.GetRequest.Timeout = 5000
	j.Download(link)
	Return j
End Sub

'Regresa verdadero si ya se reviso la version del apk el dia de hoy.
Sub versionRevisadaHoy As Boolean
	Private revisada As Boolean = False
	c = skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("REVISION_APK"))
	If c.RowCount > 0 Then
		c.Position = 0
		DateTime.DateFormat = "yyyyMMdd"
		If DateTime.Date(DateTime.Now) = c.GetString("CAT_VA_VALOR") Then
			revisada = True
			LogColor("La versión ya se revisó el día de hoy.", Colors.Red)
		End If
	End If
	' #######################################
	' ###  REGRESAMOS FALSE PARA QUE SIEMPRE REVISE ###
	' #######################################
	Return False
'	Return revisada
End Sub

Private Sub b_actualizacion_Click
	CallSubDelayed(appUpdater, "download_newApk")
End Sub

Private Sub cb_importarBDWA_CheckedChange(Checked As Boolean)
'	LogColor($"cb_importarBDWA_CheckedChange = ${Checked}"$, Colors.Red)
	Starter.skmt.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'IMPORTAR_BD_WA'")
	Starter.skmt.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('IMPORTAR_BD_WA', '${Checked}')"$)
End Sub


'Private Sub i_engrane_LongClick
''	Dim Intent1 As Intent
''	Intent1.Initialize(Intent1.ACTION_VIEW, "guna://tienda360/config?clienteId=12&almacen=45&ruta=143")
''	Try
''		StartActivity(Intent1)
''	Catch
'''		Log(LastException)
''		ToastMessageShow("La aplicación Tienda 360 no está instalada o no puede manejar la URL.", True)
''	End Try
'End Sub
