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
	Dim reqManager As DBRequestManager
	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

	'nuevocliente -> NuevoCliente
	'buscar -> ticketsDia
	'colonia -> clientes
	'nopago -> noVenta
	'tarjeta -> Nota
	'fila -> Cliente
	'colonia2 -> Productos
	
	'xxxxxxxxxxxxxxxxxxxxxxxxx

	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
	Private Entrar As Button
	Dim tipo_venta As String
	Dim bTerminarClicked As Boolean = False
	Private lv_server As ListView
	Private l_server As Label
	Private et_server As EditText
	Private b_server As Button
	Private b_envioBD As Button
	Public Provider As FileProvider
	Public rutaBDBackup As String = ""
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)
	B4XPages.GetManager.LogEvents = True
	Root = Root1
	Root.LoadLayout("login")
	B4XPages.SetTitle(Me, "Medicomed 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)
	ruta = Starter.ruta
	
	Provider.Initialize
'	Subs.borraArribaDe100Errores 	' Para Websockets
'	Subs.borraArribaDe600RenglonesBitacora 	' Para Websockets
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
		Log(File.DirAssets)
		LogColor("copiamos kmt.db de "&File.DirAssets & " a " & ruta,Colors.Green)
	End If
	Log(ruta)
	skmt.Initialize(ruta,"kmt.db", True)
	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 ABONOS (a_usuario TEXT, a_ruta TEXT, a_cliente TEXT, a_abono TEXT, a_fecha TEXT, a_enviado TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS BITACORAGPS(fechab TEXT, usuariob TEXT, almacenb TEXT, rutab TEXT, eventob TEXT, clienteb TEXT, iniciob TEXT, finb TEXT, latitudb TEXT, longitudb TEXT, precision TEXT, motivonoventa TEXT, motivonovisita TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS VENTA_No_VENTA(usuariov TEXT, almacenv TEXT, rutav TEXT, eventov TEXT, clientev TEXT, iniciov TEXT, latitudv TEXT, longitudv TEXT)")
'	skmt.ExecNonQuery("drop table kmt_info")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS kmt_info (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, CAT_CL_DIASEMANA TEXT, CAT_CL_SECUENCIA INT)")
	
	Subs.agregaColumna("VENTA_No_VENTA", "montoVentav", "TEXT")
	
	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna "CAT_CL_DIASEMANA" en la tabla
		c=skmt.ExecQuery("SELECT COUNT(*) AS fCol FROM pragma_table_info('kmt_info') WHERE name='CAT_CL_DIASEMANA'")
		c.Position = 0
		If c.GetString("fCol") = 0 Then 'Si no esta la columna FECHA la agregamos
			skmt.ExecNonQuery("ALTER TABLE kmt_info ADD COLUMN CAT_CL_DIASEMANA TEXT")
		End If
	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
		Try
			skmt.ExecNonQuery("ALTER TABLE kmt_info ADD COLUMN CAT_CL_DIASEMANA TEXT")
		Catch
			Log(LastException)
		End Try
	End Try
	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna "CAT_GP_TIPOPROD2" en la tabla
		c=skmt.ExecQuery("SELECT COUNT(*) AS fCol FROM pragma_table_info('CAT_GUNAPROD') WHERE name='CAT_GP_TIPOPROD2'")
		c.Position = 0
		If c.GetString("fCol") = 0 Then 'Si no esta la columna FECHA la agregamos
			skmt.ExecNonQuery("ALTER TABLE CAT_GUNAPROD ADD COLUMN CAT_GP_TIPOPROD2 TEXT")
		End If
	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
		Try
			skmt.ExecNonQuery("ALTER TABLE CAT_GUNAPROD ADD COLUMN CAT_GP_TIPOPROD2 TEXT")
		Catch
			Log(LastException)
		End Try
	End Try
	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna "CAT_CL_SECUENCIA" en la tabla
		c=skmt.ExecQuery("SELECT COUNT(*) AS fCol FROM pragma_table_info('kmt_info') WHERE name='CAT_CL_SECUENCIA'")
		c.Position = 0
		If c.GetString("fCol") = 0 Then 'Si no esta la columna FECHA la agregamos
			skmt.ExecNonQuery("ALTER TABLE kmt_info ADD COLUMN CAT_CL_SECUENCIA INT")
		End If
	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
		Try
			skmt.ExecNonQuery("ALTER TABLE kmt_info ADD COLUMN CAT_CL_SECUENCIA INT")
		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
	
	
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
'	Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		StartService(Tracker)
	''		Log("Start Tracker")
'	Else
'		ToastMessageShow("No permission", True)
'	End If
	p_appUpdate.Visible = False
End Sub

Sub B4XPage_Appear	
	If Starter.muestraProgreso = 1 Then
		muestraProgreso("Descargando actualización")
		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)
	server = Starter.server
	reqManager.Initialize(Me, 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
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
	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("Clientes")
	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("Clientes")
	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 existe = 0 Then
		If IMEI = "" Then
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_usuario_MEDI_10" 'Antes select_usuario_guna_GV2_1
			cmd.Parameters = Array As Object(user.Text.Trim, pass.Text.Trim)
			reqManager.ExecuteQuery(cmd , 0, "usuario_10") 'Antes usuario
		Else
			If IMEI = "" Then
				Dim cmd As DBCommand
				cmd.Initialize
				cmd.Name = "select_usuario_MEDI_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_MEDI_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") 'Antes usuario
			End If
		End If
		Dim cmd As DBCommand
		cmd.Initialize
		cmd.Name = "select_version_MEDI"
		reqManager.ExecuteQuery(cmd , 0, "version")
	Else
		usuario = user.Text
		B4XPages.ShowPage("Principal")
	End If
End Sub

Sub JobDone(Job As HttpJob)
	Log(Job.Success)
	If Job.Success = False Then
		ToastMessageShow("Error - MainPage: " & Job.ErrorMessage, True)
	Else
		LogColor("JobDone - MainPage: '" & 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 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)
				Log("//////////////////////////  "&name)
			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"))
				Next
				Log("|"&name&"|")
				paso1 = 1
				IMEI_BASE = ""
				IMEI = ""
			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.Trim, pass.Text.Trim))
				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.Trim, pass.Text.Trim))
					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("Clientes")
				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.Visible Then
		Log("update visible")
		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

'Private Sub GetAdvertisingId As ResumableSub
'	Dim jo As JavaObject = Me
'	jo.RunMethod("GetAdvertisingId", Null)
'	Wait For AdvertisingId_Ready (Success As Boolean, Id As String)
'	Return Id
'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
'		Private x As String
'		If File.ExternalWritable Then
'			x = File.DirRootExternal
'		Else
'			x = File.DirInternal
'		End If
		Dim theDir As String
		Try
			File.MakeDir(File.DirRootExternal,"kmts")
			theDir = "/kmts"
		Catch
			theDir = ""
		End Try
		Try
			File.Copy(File.DirInternal,"kmt.db",File.DirRootExternal&theDir, "medicomed_kmt.db")
			ToastMessageShow("Listo, copiado a " & File.DirRootExternal&theDir & "/medicomed_kmt_kmt.db", False)
		Catch
			ToastMessageShow("No se pudo hacer la copia: "&LastException, True)
		End Try
	Else
		ToastMessageShow("Sin permisos", False)
	End If
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
	lv_server.Clear
	lv_server.AddSingleLine("http://keymon.lat:1781")
	If user.Text = "KMTS1" Then lv_server.AddSingleLine("http://10.0.0.205:1781")
'	l_server.Text = Starter.server
	et_server.Text = Starter.server
	Subs.panelVisible(p_appUpdate,0,0)
End Sub

Sub b_regesar_Click
	p_appUpdate.Visible = False
	Subs.panelVisible(p_Main,0,0)
End Sub

Sub i_engrane_LongClick
	copiaDB
End Sub

Sub B_SERVER_Click
	skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("SERVER"))
	skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("SERVER",et_server.text))
	Starter.server = et_server.text
	If Logger Then Log("Inicializamos reqManager con " & Starter.server)
	reqManager.Initialize(Me, Starter.server)
	CallSubDelayed(Starter, "reinicializaReqManager")
	Subs.panelVisible(p_Main,0,0)
	p_appUpdate.Visible = False
'	Entrar.Visible = True
End Sub

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

Private Sub lv_server_ItemClick (Position As Int, Value As Object)
	Starter.server = Value
'	l_server.Text = Value
	et_server.Text = Value
	Starter.reqManager.Initialize(Me, Value)
	ToastMessageShow("Servidor modificado", False)
End Sub

'Enviamos la base de datos por correo o Whatsapp
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