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
	'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip
	'###########################################################################################################
	'######################           PULL         #############################################################
	'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=git&Args=pull
	'###########################################################################################################
	'######################        PULL FORZADO    #############################################################
	'Ctrl + click Respaldar y Pull: ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=start&Args=powershell.exe&Args=-ExecutionPolicy&Args=Bypass&Args=-File&Args=..\..\_sync_project.ps1
	'###########################################################################################################
	'######################           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
	'###########################################################################################################
	'######################      PUSH TORTOISE GIT CON TAG    ##################################################
	'Ctrl + clic para Git: ide://run?file=%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe&Args=-ExecutionPolicy&Args=Bypass&Args=-File&Args=..\_git_tag.ps1&Args=%22%PROJECT%%22&Args=%22%PROJECT_NAME%%22
	'###########################################################################################################
#End Region

'Ctrl + click ide://run?file=%WINDIR%\System32\cmd.exe&Args=/c&Args=github&Args=..\..\

Sub Class_Globals
	Dim c2 As Cursor
	Dim sDate,sTime As String
	Private Root As B4XView
	Private xui As XUI
	Dim s As C_Subs
	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 Provider As FileProvider
 
	'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 DBReqServer, fechaRuta As String
	Dim Logger As Boolean
	Dim mac_impresora As String
	Dim Phn As PhoneId
	
	Dim user As EditText
	Dim pass As EditText
	Public tabulador As C_tabulador
	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 b_enviarbd As Button
	Private b_importarBD As Button
	Dim ime As IME
	Dim MES1 As ManageExternalStorage
	Dim device As Phone
	Private et_server As EditText
	Private b_guardar As Button
	Private Panel11 As Panel
	Private CLV_PICK_CIEGO As CustomListView
	Private P_PICK_CIEGO As Panel
	Dim ET_PICK_CIEGO As EditText
	Private L_PICK_CIEGO As Label
	Private P_CIEGO As Panel
	Dim Panel4 As Panel
	Dim q_buscar As String
	Private et_buspc As EditText
	Dim d As Cursor
	Dim a As Cursor
	Dim f As Cursor
	Dim idenviar As String
	Private et_codigo As EditText
	Private b_cancelarcodigo As Button
	Private b_aceptar As Button
	Private p_validacion As Panel
	Private b_recarga As Button
	Dim recarga As String = "0"
	Private p_add_monto As Panel
	Private B_Can_Monto As Button
	Private B_Aceptar_Monto As Button
	Private ET_Add_Monto As EditText
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")
	s.Initialize(Me, "Subs")
	B4XPages.SetTitle(Me, "SHARK2")
	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)
	tabulador.Initialize
	B4XPages.AddPage("tabulador", tabulador)
'	respaldoDiario.Initialize
'	B4XPages.AddPageAndCreate("respaldoDiario", respaldoDiario)
	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")
		LogColor("copiamos kmt.db de "&File.DirAssets & " a " & ruta,Colors.Green)
	End If
	
'	Log(ruta)
	skmt.Initialize(ruta,"kmt.db", True)
	Subs.guardaAppInfo(skmt)
	
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TABULADOR_MONEDAS(VEINTE TEXT, DIEZ TEXT, CINCO TEXT, DOS TEXT, PESO TEXT, CENTAVO TEXT, TOTAL TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS COORDENADAS(LAT TEXT, LONG TEXT, CLIENTE TEXT, CANTIDAD INT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ATIENDE(ATIENDE TEXT, CLIENTE TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS GIROS_ACTUAL(GIRO TEXT, CLIENTE TEXT)")
	Starter.skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS TABULADOR_BILLETES(MIL TEXT, QUINIENTOS TEXT, DOCIENTOS TEXT, CIEN TEXT, CINCUENTA TEXT, VEINTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CLIENTES_NUEVOS(CN_ID TEXT, CN_FECHA TEXT, CN_USER TEXT, CN_LAT TEXT, CN_LON TEXT, CN_NOMBRE TEXT, CN_DIRECCION TEXT, CN_FOTO TEXT, CN_ALMACEN TEXT, CN_RUTA TEXT,CN_GIRO TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS RUTAA (RUTAA TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS POLIGONO (LAT TEXT, LONG TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS GEOCERCA (ACTIVA TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS COORDS_ALMACEN (LAT TEXT, LONG 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 CAT_GIRO(GIRO TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PICKCIEGO_HECHO(HECHO TEXT)")
'	skmt.ExecNonQuery("drop table CAT_GUNAPROD2") 'Bitacora
'	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD (CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD TEXT, CAT_GP_DEV TEXT, CAT_GP_ALMACEN NUMERIC, 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 BLOB, CAT_DP_CONVERSION1 TEXT, CAT_DP_PRECIO4 TEXT, CAT_DP_PRECIO2 TEXT, CAT_DP_PRECIO1 TEXT)")
'	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD (CAT_DP_ID TEXT, CAT_DP_NOMBRE TEXT, CAT_DP_IMP1 TEXT, CAT_DP_IMP2 TEXT, CAT_DP_CLASIF TEXT, CAT_DP_STS INT, CAT_DP_TIPO TEXT, CAT_DP_SUBTIPO TEXT, CAT_DP_IMG BLOB, CAT_DP_ALMACEN INT, CAT_DP_DEV INT, CAT_DP_TIPOPROD TEXT, CAT_DP_INICIATIVA TEXT, CAT_DP_TIPOPROD2 TEXT, CAT_DP_PRECIO1 TEXT, CAT_DP_PRECIO2 TEXT, CAT_DP_PRECIO3 TEXT, CAT_DP_PRECIO4 TEXT, CAT_DP_PRECIO5 TEXT, CAT_DP_PRECIO6 TEXT, CAT_DP_PRECIO7 TEXT, CAT_DP_PRECIO8 TEXT, CAT_DP_PRECIO9 TEXT, CAT_DP_PRECIO10 TEXT, CAT_DP_PRECIO11 TEXT, CAT_DP_PRESENTACION1 TEXT, CAT_DP_PRESENTACION2 TEXT, CAT_DP_PRESENTACION3 TEXT, CAT_DP_PRESENTACION4 TEXT, CAT_DP_PRESENTACION5 TEXT, CAT_DP_PRESENTACION6 TEXT, CAT_DP_PRESENTACION7 TEXT, CAT_DP_PRESENTACION8 TEXT, CAT_DP_PRESENTACION9 TEXT, CAT_DP_PRESENTACION10 TEXT, CAT_DP_PRESENTACION11 TEXT, CAT_DP_UMV1 TEXT, CAT_DP_UMV2 TEXT, CAT_DP_UMV3 TEXT, CAT_DP_UMV4 TEXT, CAT_DP_UMV5 TEXT, CAT_DP_UMV6 TEXT, CAT_DP_UMV7 TEXT, CAT_DP_UMV8 TEXT, CAT_DP_UMV9 TEXT, CAT_DP_UMV10 TEXT, CAT_DP_UMV11 TEXT, CAT_DP_DIRIGIDA1 TEXT, CAT_DP_DIRIGIDA2 TEXT, CAT_DP_DIRIGIDA3 TEXT, CAT_DP_DIRIGIDA4 TEXT, CAT_DP_DIRIGIDA5 TEXT, CAT_DP_DIRIGIDA6 TEXT, CAT_DP_DIRIGIDA7 TEXT, CAT_DP_DIRIGIDA8 TEXT, CAT_DP_DIRIGIDA9 TEXT, CAT_DP_DIRIGIDA10 TEXT, CAT_DP_DIRIGIDA11 TEXT)")
	
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD (CAT_GP_ID TEXT, CAT_GP_NOMBRE TEXT, CAT_GP_IMP1 TEXT, CAT_GP_IMP2 TEXT, CAT_GP_CLASIF TEXT, CAT_GP_STS INT, CAT_GP_TIPO TEXT, CAT_GP_SUBTIPO TEXT, CAT_GP_IMG BLOB, CAT_GP_ALMACEN INT, CAT_GP_DEV INT, CAT_GP_TIPOPROD TEXT, CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD2 TEXT, CAT_GP_PRECIO1 TEXT, CAT_GP_PRECIO2 TEXT, CAT_GP_PRECIO3 TEXT, CAT_GP_PRECIO4 TEXT, CAT_GP_PRECIO5 TEXT, CAT_GP_PRECIO6 TEXT, CAT_GP_PRECIO7 TEXT, CAT_GP_PRECIO8 TEXT, CAT_GP_PRECIO9 TEXT, CAT_GP_PRECIO10 TEXT, CAT_GP_PRECIO11 TEXT, CAT_GP_PRESENTACION1 TEXT, CAT_GP_PRESENTACION2 TEXT, CAT_GP_PRESENTACION3 TEXT, CAT_GP_PRESENTACION4 TEXT, CAT_GP_PRESENTACION5 TEXT, CAT_GP_PRESENTACION6 TEXT, CAT_GP_PRESENTACION7 TEXT, CAT_GP_PRESENTACION8 TEXT, CAT_GP_PRESENTACION9 TEXT, CAT_GP_PRESENTACION10 TEXT, CAT_GP_PRESENTACION11 TEXT, CAT_GP_UMV1 TEXT, CAT_GP_UMV2 TEXT, CAT_GP_UMV3 TEXT, CAT_GP_UMV4 TEXT, CAT_GP_UMV5 TEXT, CAT_GP_UMV6 TEXT, CAT_GP_UMV7 TEXT, CAT_GP_UMV8 TEXT, CAT_GP_UMV9 TEXT, CAT_GP_UMV10 TEXT, CAT_GP_UMV11 TEXT, CAT_GP_DIRIGIDA1 TEXT, CAT_GP_DIRIGIDA2 TEXT, CAT_GP_DIRIGIDA3 TEXT, CAT_GP_DIRIGIDA4 TEXT, CAT_GP_DIRIGIDA5 TEXT, CAT_GP_DIRIGIDA6 TEXT, CAT_GP_DIRIGIDA7 TEXT, CAT_GP_DIRIGIDA8 TEXT, CAT_GP_DIRIGIDA9 TEXT, CAT_GP_DIRIGIDA10 TEXT, CAT_GP_DIRIGIDA11 TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD2 (CAT_GP_ID TEXT, CAT_GP_NOMBRE TEXT, CAT_GP_IMP1 TEXT, CAT_GP_IMP2 TEXT, CAT_GP_CLASIF TEXT, CAT_GP_STS INT, CAT_GP_TIPO TEXT, CAT_GP_SUBTIPO TEXT, CAT_GP_IMG BLOB, CAT_GP_ALMACEN INT, CAT_GP_DEV INT, CAT_GP_TIPOPROD TEXT, CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD2 TEXT, CAT_GP_PRECIO1 TEXT, CAT_GP_PRECIO2 TEXT, CAT_GP_PRECIO3 TEXT, CAT_GP_PRECIO4 TEXT, CAT_GP_PRECIO5 TEXT, CAT_GP_PRECIO6 TEXT, CAT_GP_PRECIO7 TEXT, CAT_GP_PRECIO8 TEXT, CAT_GP_PRECIO9 TEXT, CAT_GP_PRECIO10 TEXT, CAT_GP_PRECIO11 TEXT, CAT_GP_PRESENTACION1 TEXT, CAT_GP_PRESENTACION2 TEXT, CAT_GP_PRESENTACION3 TEXT, CAT_GP_PRESENTACION4 TEXT, CAT_GP_PRESENTACION5 TEXT, CAT_GP_PRESENTACION6 TEXT, CAT_GP_PRESENTACION7 TEXT, CAT_GP_PRESENTACION8 TEXT, CAT_GP_PRESENTACION9 TEXT, CAT_GP_PRESENTACION10 TEXT, CAT_GP_PRESENTACION11 TEXT, CAT_GP_UMV1 TEXT, CAT_GP_UMV2 TEXT, CAT_GP_UMV3 TEXT, CAT_GP_UMV4 TEXT, CAT_GP_UMV5 TEXT, CAT_GP_UMV6 TEXT, CAT_GP_UMV7 TEXT, CAT_GP_UMV8 TEXT, CAT_GP_UMV9 TEXT, CAT_GP_UMV10 TEXT, CAT_GP_UMV11 TEXT, CAT_GP_DIRIGIDA1 TEXT, CAT_GP_DIRIGIDA2 TEXT, CAT_GP_DIRIGIDA3 TEXT, CAT_GP_DIRIGIDA4 TEXT, CAT_GP_DIRIGIDA5 TEXT, CAT_GP_DIRIGIDA6 TEXT, CAT_GP_DIRIGIDA7 TEXT, CAT_GP_DIRIGIDA8 TEXT, CAT_GP_DIRIGIDA9 TEXT, CAT_GP_DIRIGIDA10 TEXT, CAT_GP_DIRIGIDA11 TEXT)")
	
	
	
'	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD2 (CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD TEXT, CAT_GP_DEV TEXT, CAT_GP_ALMACEN NUMERIC, 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 BLOB)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD3 (CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD TEXT, CAT_GP_DEV TEXT, CAT_GP_ALMACEN NUMERIC, 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 BLOB)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS CAT_GUNAPROD4 (CAT_GP_INICIATIVA TEXT, CAT_GP_TIPOPROD TEXT, CAT_GP_DEV TEXT, CAT_GP_ALMACEN NUMERIC, 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 BLOB, CAT_DP_CONVERSION1 TEXT, CAT_DP_PRECIO4 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 COORDENADAS_GPS (tienda_id TEXT, ruta TEXT, almacen TEXT, latitud TEXT, longitud TEXT, fecha TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS HIST_CUESTIONARIO (HC_CLIENTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PAGARES (PA_ALMACEN TEXT, PA_RUTA TEXT, PA_FECHA TEXT, PA_CAPTURA TEXT, PA_MONTO TEXT, PA_USUARIO TEXT, PA_CLIENTE TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS NOVENTA (NV_CLIENTE TEXT, NV_FECHA TEXT, NV_USER TEXT, NV_MOTIVO TEXT, NV_COMM TEXT, NV_LAT TEXT, NV_LON TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS PICK_CIEGO (PC_ID_PROD TEXT, PC_NOM_PROD TEXT, PC_CANT TEXT, PC_ALMACEN TEXT, PC_RUTA TEXT, PC_FECHA TEXT)")
	skmt.ExecNonQuery("CREATE TABLE IF NOT EXISTS ENV_MONTO_LIQ (EML_MONTO TEXT, EML_ALMACEN TEXT, EML_RUTA TEXT, EML_USUARIO TEXT, EML_FECHA_PED TEXT)")
	Subs.agregaColumna("PEDIDO", "PE_ENVIO_OK", "INT")
	Subs.agregaColumna("PEDIDO", "PE_CANTC", "TEXT")
	
	Subs.agregaColumna("PEDIDO", "PE_DIRIGIDA", "TEXT")
	Subs.agregaColumna("PEDIDO", "PE_UVM", "TEXT")
	Subs.agregaColumna("PEDIDO", "PE_PRESENTACION", "TEXT")
	
	Subs.agregaColumna("PEDIDO", "PE_BCAJAS", "TEXT")
	Subs.agregaColumna("NOVENTA", "NV_ENVIO_OK", "INT")
	Subs.agregaColumna("kmt_info", "CAT_CL_BCREDITO", "TEXT")
	Subs.agregaColumna("kmt_info", "CAT_CL_TIPOCLIENTE", "TEXT")
	Subs.agregaColumna("kmt_info", "CAT_CL_BCOORDENADAS", "TEXT")
	Subs.agregaColumna("kmt_info", "CAT_CL_LIMITECREDITO", "TEXT")
	Subs.agregaColumna("kmt_info", "CAT_CL_LISTA_PRECIO", "TEXT")
	Subs.agregaColumna("kmt_info2", "CAT_CL_LISTA_PRECIO", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_TIPOPROD2", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_CONVERSION1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA11", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA10", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA9", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA8", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA7", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA6", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA5", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA4", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA3", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA2", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_DIRIGIDA1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV11", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV10", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV9", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV8", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV7", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV6", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV5", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV4", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV3", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV2", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_UMV1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION11", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION10", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION9", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION8", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION7", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION6", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION5", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION4", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION3", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION2", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRESENTACION1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO11", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO10", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO9", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO8", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO7", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO6", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO5", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO4", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO3", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO2", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD", "CAT_GP_PRECIO1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD3", "CAT_DP_CONVERSION1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD3", "CAT_DP_PRECIO4", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_DP_CONVERSION1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_DP_PRECIO4", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_DP_PRECIO1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD2", "CAT_DP_PRECIO2", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD4", "CAT_DP_PRECIO1", "TEXT")
	Subs.agregaColumna("CAT_GUNAPROD4", "CAT_DP_PRECIO2", "TEXT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_SOLICITA", "TEXT")
	Subs.agregaColumna("ABONOSP", "DIA_VENCIMIENTO", "TEXT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_COLONIA", "TEXT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_TELEFONO", "TEXT")
	Subs.agregaColumna("CLIENTES_NUEVOS", "CN_CP", "TEXT")
	c=skmt.ExecQuery("select  COUNT(*) AS CUANTOS from HIST_STAY_OUT ")
'	
'	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.534596, -99.148633))
'	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.532618, -99.147368))
'	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.530434, -99.143527))
	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.481683012377815, -99.14063876529508))
	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.480080935096886, -99.15459780214643))
'	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.52212245552407, -99.14288326892365))
'	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.52414485532313, -99.1441707292143))
'	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.525681862241495, -99.14623066567934))
'	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.52794689841748, -99.14923473969085))
'	skmt.ExecNonQuery2("INSERT INTO POLIGONO(LAT,LONG) VALUES(?,?) ", Array As Object(19.52950409236695, -99.15127321848439))
	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, DBReqServer)
	l_version.Text = Application.VersionName
	l_version.Visible = True
	l_version.BringToFront
	'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
	
	LogColor("Revisa permisos Phone_State", Colors.Green)
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_FINE_LOCATION)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Log("Con permisos de ubicacion")
	Else
		Log("SIN permisos de ubicacion")
	End If
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_ACCESS_COARSE_LOCATION)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Log("Con permisos de ubicacion")
	Else
		Log("SIN permisos de ubicacion")
	End If
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_PHONE_STATE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
'		IMEN.Text = Phn.GetDeviceId
'		IMEI = Phn.GetDeviceId
'		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("No permission", True)
'	End If
	MES1.Initialize(Me, "MES1")
	' get the device SDK version
	Dim SdkVersion As Int = device.SdkVersion
	' Choose which permission to request in order to access external storgage
	If SdkVersion < 30 Then
'		Log("SDK = " & SdkVersion & " : Requesting WRITE_EXTERNAL_STORAGE permission")
		Dim rp As RuntimePermissions
		rp.CheckAndRequest(rp.PERMISSION_WRITE_EXTERNAL_STORAGE) ' Implicit read capability if granted
		Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
'		Log($"PERMISSION_WRITE_EXTERNAL_STORAGE = ${Result}"$)
	Else
'		Log("SDK = " & SdkVersion & " : Requesting MANAGE_EXTERNAL_STORAGE permission")
'		Log("On Entry MANAGE_EXTERNAL_STORAGE = " & MES1.HasPermission)
		If Not(MES1.HasPermission) Then
			MsgboxAsync("This app requires access to all files, please enable the option", "Manage All Files")
			Wait For Msgbox_Result(Res As Int)
'			Log("Getting permission")
			MES1.GetPermission
			Wait For MES_StorageAvailable
		End If
	End If
	P_CIEGO.Height = Root.Height
	P_CIEGO.Width = Root.Width
	p_validacion.Height = Root.Height
	p_validacion.Width = Root.Width
	p_add_monto.Height = Root.Height
	p_add_monto.Width = Root.Width

	
End Sub

Sub B4XPage_Appear
	Log(recarga)
	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)
	DBReqServer = Starter.DBReqServer
	reqManager.Initialize(Me, Starter.DBReqServer)
	Log("|"&Starter.DBReqServer&"|")
	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
'	If Not(s.CheckNotificationAccess) Then
'		Msgbox2Async($"Se necesita acceso a las notificaciones, haga clic en "Aceptar" y en la siguiente pantalla permita el acceso a la aplicación "${Application.LabelName}"."$, "Permisos necesarios", "Aceptar", "Cancelar", "", Null, True)
'		Wait For Msgbox_Result (resultado As Int)
'		If resultado = DialogResponse.POSITIVE Then
'			Dim In As Intent
'			In.Initialize("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS", "")
'			StartActivity(In)
'		End If
''		Private cd1 As ColorDrawable
''		cd1.Initialize(Colors.red, 10dip)
''		b_notifAccess.Background = cd1
''		b_notifAccess.TextColor = Colors.White
''		b_notifAccess.Text = "Activar Permisos"
'	Else
''		Private cd1 As ColorDrawable
''		cd1.Initialize(Colors.RGB(109, 221, 101), 10dip)
''		b_notifAccess.Background = cd1
''		b_notifAccess.TextColor = Colors.White
''		b_notifAccess.Text = "Permisos Activos"
'	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
	Log("|" & Starter.DBReqServer)
	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
		DBReqServer = 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
		DBReqServer = c.GetString("CAT_CO_CONFIGURACION")
		user.Text = DBReqServer
		c.Close
'		reqManager.Initialize(Me, DBReqServer)
	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_SHARK2 " '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_SHARK2"
				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_SHARK2" '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_SHARK2"
		reqManager.ExecuteQuery(cmd , 0, "version")
	Else
		usuario = user.Text
		B4XPages.ShowPage("Principal")
	End If
End Sub

Sub JobDone(Job As HttpJob)
	Log("JOBDONE MAINPAGE")
	If B4XPages.MainPage.reqManager.reqsList.IsInitialized Then 'Si tenemos lista de requests, la procesamos.
		If B4XPages.MainPage.reqManager.reqsList.IndexOf(Job.tag) <> -1 Then
			B4XPages.MainPage.reqManager.reqsList.RemoveAt(B4XPages.MainPage.reqManager.reqsList.IndexOf(Job.tag))
			LogColor($">>>>>> Quitamos ${Job.tag}"$, Colors.Blue)
		End If
		LogColor(">>>>>> " & B4XPages.MainPage.reqManager.reqsList.Size & " - " & B4XPages.MainPage.reqManager.reqsList, Colors.Blue)
	End If
	If Job.Success = False Then
		LogColor("Error: " & Job.tag & " : " & Job.ErrorMessage, Colors.red)
	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 result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "SelectMontoLiq" Then
				For Each records() As Object In result.Rows
					Dim CUENTA As String = records(result.Columns.Get("CUENTA"))
					
					DateTime.DateFormat = "MM/dd/yyyy"
					sDate=DateTime.Date(DateTime.Now)
					sTime=DateTime.Time(DateTime.Now)
					f=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
					f.Position = 0
					a=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
					a.Position = 0
					
					Private c2 As Cursor
					c2=skmt.ExecQuery("select USUARIO from usuarioa")
					c2.Position=0
					If c2.RowCount > 0 Then c2.GetString("USUARIO")
					
					Log(CUENTA & "----------------------!!")
					If CUENTA = "0" Then
						
						c = Starter.skmt.ExecQuery2("SELECT * FROM ENV_MONTO_LIQ WHERE EML_USUARIO = ? AND EML_ALMACEN = ? AND EML_RUTA = ?", Array As String (c2.GetString("USUARIO"), a.GetString("ID_ALMACEN"), f.GetString("CAT_CL_RUTA")))
						If c.RowCount > 0 Then
'							For i=0 To c.RowCount -1
							c.Position=0
							Dim cmd As DBCommand
							cmd.Initialize
							cmd.Name = "insert_Monto_Liq_SHARK2"
							cmd.Parameters = Array As Object(c.GetString("EML_MONTO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"), c.GetString("EML_USUARIO"), "VENTA", c.GetString("EML_FECHA_PED"))
							reqManager.ExecuteCommand(cmd , "ins_Mon_Liq")
							MsgboxAsync("Monto Enviado", "Atención")
'							Next
						End If
						c.Close
					Else if CUENTA > "0" Then
						
						c = Starter.skmt.ExecQuery2("SELECT * FROM ENV_MONTO_LIQ WHERE EML_USUARIO = ? AND EML_ALMACEN = ? AND EML_RUTA = ?", Array As String (c2.GetString("USUARIO"), a.GetString("ID_ALMACEN"), f.GetString("CAT_CL_RUTA")))
						If c.RowCount > 0 Then
'							For i=0 To c.RowCount -1
							c.Position = 0
							cmd.Initialize
							cmd.Name = "update_MontoCuenta_SHARK2"
							cmd.Parameters = Array As Object(c.GetString("EML_MONTO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"), c.GetString("EML_USUARIO"))
							
							Log(c.GetString("EML_MONTO")& " " & c.GetString("EML_ALMACEN")& " " & c.GetString("EML_RUTA")& " " & c.GetString("EML_USUARIO"))
							reqManager.ExecuteCommand(cmd, "update_MC")
							MsgboxAsync("Se sobre escribio el Monto", "Atención")
'							Next
						End If
						c2.Close
						c.Close
					End If
					f.Close
					a.Close
				Next
			End If
		End If
		
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag.As(String).IndexOf("PICK_C_") > -1 Then 'query tag
'				Subs.logJobDoneResultados(result)
				Private id As String= result.Tag
				id = id.SubString(id.IndexOf("_")+3)
				For Each records() As Object In result.Rows
					Dim CUENTA As String = records(result.Columns.Get("CUENTA"))
					Log(CUENTA)
					Log(id)
					If CUENTA = 0 Then
						c = Starter.skmt.ExecQuery2("SELECT * FROM PICK_CIEGO WHERE PC_ID_PROD = ?", Array As String (id))
						If c.RowCount > 0 Then
'							For i=0 To c.RowCount -1
							c.Position=0
							Dim cmd As DBCommand
							cmd.Initialize
							cmd.Name = "insert_PICKCIEGO_SHARK2"
							cmd.Parameters = Array As Object(c.GetString("PC_ID_PROD"), c.GetString("PC_NOM_PROD"), c.GetString("PC_CANT"), c.GetString("PC_ALMACEN"), c.GetString("PC_RUTA"), c.GetString("PC_FECHA"),"VENTA")
							reqManager.ExecuteCommand(cmd , "ins_PC")
'							Next
						End If
						c.Close
					Else if CUENTA > 0 Then
						c = Starter.skmt.ExecQuery2("SELECT * FROM PICK_CIEGO WHERE PC_ID_PROD= ?", Array As String (id))
						If c.RowCount > 0 Then
'							For i=0 To c.RowCount -1
							c.Position = 0
							Dim cmd As DBCommand
							cmd.Initialize
							cmd.Name = "update_PICKCIEGO_SHARK2"
							Log("FECHA" & c.GetString("PC_FECHA"))
							cmd.Parameters = Array As Object(c.GetString("PC_CANT"), c.GetString("PC_ID_PROD"), c.GetString("PC_ALMACEN"), c.GetString("PC_RUTA"), c.GetString("PC_FECHA"),"VENTA")
							reqManager.ExecuteCommand(cmd, "update_PC")
'							Next
						End If
						c.Close
					End If

				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
		
		If Job.JobName = "DBRequest" Then
			Dim result As DBResult = reqManager.HandleJob(Job)
			If result.Tag = "contrasena" Then 'query tag
				For Each records() As Object In result.Rows
					Dim CAT_PA_PASS As String = records(result.Columns.Get("CAT_PA_PASS"))
					If CAT_PA_PASS = et_codigo.Text Then
						Log(CAT_PA_PASS)
						p_validacion.Visible = False
						et_codigo.Text = ""
						If recarga = "0" Then
							Subs.panelVisible(P_CIEGO,0,0)
						Else If recarga = "1" Then
							Starter.skmt.ExecNonQuery("delete from CUENTAA")
							Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("1"))
							B4XPages.MainPage.tipo_venta = "RECARGA"
							B4XPages.ShowPage("Productos")
							
						End If
					Else 
						MsgboxAsync("Contraseña incorrecta","Atención")
					End If
				Next
			End If
		End If
		
		If result.Tag = "ruta" Then 'query tag
			Log("JOBDONE PRINCIPAL MAINPAGE")
			For Each records() As Object In result.Rows
				Dim VALIDO As String = records(result.Columns.Get("VALIDO"))
				If VALIDO = "OK" Then
					Log(VALIDO)
				End If
			Next
		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_add_monto.IsInitialized And p_add_monto.Visible Then
		p_add_monto.Visible = False
		Return False
	Else If p_validacion.IsInitialized And p_validacion.Visible Then
		p_validacion.Visible = False
		Return False
	Else If P_CIEGO.IsInitialized And P_CIEGO.Visible Then
		MsgboxAsync("Debes de terminar el proceso para regresar a la pantalla principal","Atención")
		Return False
	Else 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

'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.DirInternal
'		Else
'			x = File.DirInternal
'		End If
		Dim theDir As String
		Try
			File.MakeDir(File.DirInternal,"kmts")
			theDir = "/kmts"
		Catch
			theDir = ""
		End Try
		Try
			File.Copy(File.DirInternal,"kmt.db",File.DirInternal&theDir, "SHARK2_kmt.db")
			ToastMessageShow("Listo, copiado a " & File.DirInternal&theDir & "/SHARK2_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
	ime.HideKeyboard
	lv_server.AddSingleLine("http://keymon.net:1781")
'	lv_server.AddSingleLine("http://keymon.lat:1781")
	If user.Text = "KMTS1" Then lv_server.AddSingleLine("http://10.0.0.205:1781")
'	lv_server.AddSingleLine("http://40.123.36.38:1782")
	Log($"|${Starter.DBReqServer}|"$)
'	l_server.Text = Starter.DBReqServer
	et_server.Text = Starter.DBReqServer
	Subs.panelVisible(p_appUpdate,0,0)
	If user.Text.trim = "KMTS1" Then b_importarBD.Visible = True Else b_importarBD.Visible = False
End Sub

Sub b_regesar_Click
	Subs.panelVisible(p_Main,0,0)
End Sub

Sub i_engrane_LongClick
	copiaDB
End Sub

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

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

Private Sub b_enviarbd_Click

End Sub

Private Sub b_importarBD_Click
	Private FH As FileHandler
	FH.Initialize
	Wait For (FH.Load) Complete (Result As LoadResult) 'Abre un fileManager para seleccionar la base de datos a importar.
	File.Copy(Result.Dir, Result.FileName, File.DirInternal, "kmt.db") 'Copia la base de datos seleccionada al directorio interno.
	B4XPages.MainPage.skmt.Initialize(Starter.ruta,"kmt.db", True) 'Reiniciliza la base de datos con la recien importada.
	ToastMessageShow("¡BD importada!", False)
End Sub

Private Sub b_guardar_Click
	Starter.reinicializaReqManager(et_server.Text.Trim)
	p_appUpdate.Visible = False
End Sub

Private Sub b_arqueocieego_Click
	c = skmt.ExecQuery("SELECT * FROM CAT_GUNAPROD3")
	If c.RowCount > 0 Then
		Subs.panelVisible(p_validacion,0,0)
		recarga = "0"
	Else
		MsgboxAsync("No hay ruta cargada, favor de cargar día","Atención")
	End If
End Sub

Private Sub et_buspc_TextChanged (Old As String, New As String)
	If New = "" Then
		CLV_PICK_CIEGO.Clear
	Else If New.Length >= 3 Then
		CLV_PICK_CIEGO.Clear
	
		q_buscar = "%" & et_buspc.Text & "%"
		Log(q_buscar)
		c=B4XPages.MainPage.skmt.ExecQuery2($"select CAT_GP_NOMBRE, CAT_GP_ID , ifnull(PC_CANT,0) AS PC_CANT FROM CAT_GUNAPROD3 INNER JOIN PICK_CIEGO ON PC_ID_PROD = CAT_GP_ID AND PC_NOM_PROD = CAT_GP_NOMBRE WHERE (CAT_GP_NOMBRE LIKE ? OR  CAT_GP_ID  LIKE ? ) and CAT_GP_CLASIF <> 'PROMOS'"$, Array As String(q_buscar,q_buscar))
		If c.RowCount > 0 Then

		
			For i = 0 To c.RowCount - 1
				c.Position = i
				CLV_PICK_CIEGO.Add(CreateListItem(c.GetString("CAT_GP_ID"), c.GetString("CAT_GP_NOMBRE"), c.GetString("PC_CANT")),i)
'				Log(c.GetString("CAT_GP_ID") & ", " & c.GetString("CAT_GP_NOMBRE") & " ," & c.GetString("PC_CANT"))
			Next
			c.Close
		
			d=B4XPages.MainPage.skmt.ExecQuery2($"select CAT_GP_NOMBRE, CAT_GP_ID FROM CAT_GUNAPROD3 WHERE (CAT_GP_NOMBRE LIKE ? OR  CAT_GP_ID  LIKE ? ) and CAT_GP_CLASIF <> 'PROMOS'AND CAT_GP_ID NOT IN (SELECT PC_ID_PROD FROM PICK_CIEGO)"$, Array As String(q_buscar,q_buscar))
		
			For i = 0 To d.RowCount - 1
				d.Position = i
				CLV_PICK_CIEGO.Add(CreateListItem2(d.GetString("CAT_GP_ID"), d.GetString("CAT_GP_NOMBRE")),i)
'				Log(d.GetString("CAT_GP_ID") & ", " & d.GetString("CAT_GP_NOMBRE"))
			Next
			d.Close
		
		Else If c.RowCount = 0 Then
			d=B4XPages.MainPage.skmt.ExecQuery2($"select CAT_GP_NOMBRE, CAT_GP_ID FROM CAT_GUNAPROD3 WHERE (CAT_GP_NOMBRE LIKE ? OR  CAT_GP_ID  LIKE ? ) and CAT_GP_CLASIF <> 'PROMOS'"$, Array As String(q_buscar,q_buscar))
		
			For i = 0 To d.RowCount - 1
				d.Position = i
				CLV_PICK_CIEGO.Add(CreateListItem2(d.GetString("CAT_GP_ID"), d.GetString("CAT_GP_NOMBRE")),i)
'				Log(d.GetString("CAT_GP_ID") & ", " & d.GetString("CAT_GP_NOMBRE"))
			Next
			d.Close
		End If
	End If
End Sub

Sub CreateListItem(Id_prod As String, Prod As String,cant As String) As Panel
	Dim pa As B4XView = xui.CreatePanel("")
	pa.SetLayoutAnimated(0, 0, 0, 1, 10)
	pa.LoadLayout("PANEL_PICK_CIEGO")
	pa.Height = 55dip
	pa.Width = 298dip
	'pa.Width = clv_orden.GetBase.Width
	L_PICK_CIEGO.Text = Id_prod &  CRLF & Prod
	L_PICK_CIEGO.TextSize = 12
	L_PICK_CIEGO.Gravity = Bit.Or(Gravity.CENTER_VERTICAL, Gravity.CENTER_HORIZONTAL)
	ET_PICK_CIEGO.Text = cant
	'cxc.Id_prod = mostrar3
	'Log(pa.Width)
	Return pa
End Sub

Sub CreateListItem2(Id_prod As String, Prod As String) As Panel
	Dim pa As B4XView = xui.CreatePanel("")
	pa.SetLayoutAnimated(0, 0, 0, 1, 10)
	pa.LoadLayout("PANEL_PICK_CIEGO")
	pa.Height = 55dip
	pa.Width = 298dip
	'pa.Width = clv_orden.GetBase.Width
	L_PICK_CIEGO.Text = Id_prod &  CRLF & Prod
	L_PICK_CIEGO.TextSize = 12
	L_PICK_CIEGO.Gravity = Bit.Or(Gravity.CENTER_VERTICAL, Gravity.CENTER_HORIZONTAL)
	'cxc.Id_prod = mostrar3
	'Log(pa.Width)
	Return pa
End Sub

Sub ET_PICK_CIEGO_TextChanged (Old As String, New As String)
	Dim et As EditText = Sender
	If New.Length > 4 Then
		et.Text = Old
	End If
End Sub

Private Sub B_PC_ENV_Click
		
	Dim sDate, sTime As String
	DateTime.DateFormat = "dd/MM/yyyy"
	DateTime.TimeFormat = "HH:mm:ss"
	sDate = DateTime.Date(DateTime.Now)
	sTime = DateTime.Time(DateTime.Now)
	
	
	For i = 0 To CLV_PICK_CIEGO.Size - 1
		' Retrieve the panel and child views for the current item
		Dim itemPanel As B4XView = CLV_PICK_CIEGO.GetPanel(i)
		Dim innerPanel As B4XView = itemPanel.GetView(0)
		Dim editText As B4XView = innerPanel.GetView(1)
		Dim inputText As String = editText.As(EditText).Text

		' Check if the input text matches the regex pattern for zeros or if it's empty
		If Regex.IsMatch("^[0]+$", inputText) Or inputText = "" Then
			inputText = "0"
		End If

		' Retrieve and process the ID label
		Dim idLabel As B4XView = innerPanel.GetView(0)
		Dim idText As String = idLabel.As(Label).Text
		Dim idParts() As String = Regex.Split(CRLF, idText)
'		Log(idParts(1))
		f=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
		f.Position=0

		a=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
		If a.RowCount>0 Then
			a.Position=0
		End If
'		Log(a.GetString("ID_ALMACEN"))
'		Log(f.GetString("CAT_CL_RUTA"))
				
		If inputText <> "" Then
			c = Starter.skmt.ExecQuery2("SELECT * FROM PICK_CIEGO where PC_ID_PROD = ?", Array As String (idParts(0)))
			If c.RowCount = 0 Then
				' Insert data into the database
				skmt.ExecNonQuery2("INSERT INTO PICK_CIEGO(PC_ID_PROD, PC_NOM_PROD, PC_CANT, PC_ALMACEN, PC_RUTA, PC_FECHA) VALUES(?,?,?,?,?,?)", Array As String(idParts(0), idParts(1), inputText, a.GetString("ID_ALMACEN"), f.GetString("CAT_CL_RUTA"), sDate&" "&sTime))
			Else
				B4XPages.MainPage.skmt.ExecNonQuery2("Update PICK_CIEGO set PC_CANT = ?  WHERE PC_ID_PROD = ?" , Array As String(inputText ,idParts(0)))
			End If
		End If
		f.Close
		a.Close
'		Log("Processed item " & i)
	Next
	et_buspc.Text = ""
	CLV_PICK_CIEGO.Clear
	
End Sub

Private Sub b_terpc_Click
	Msgbox2Async("Una vez enviada la información no podras hacer modificaciones","Atención","SI","", "",LoadBitmap(File.DirAssets,"alert2.png"), False)
	Wait For Msgbox_Result (resultado As Int)
	If resultado = DialogResponse.POSITIVE Then
		Msgbox2Async("Estas seguro de enviar la información?","Atención","SI","", "NO",LoadBitmap(File.DirAssets,"alert2.png"), False)
		Wait For Msgbox_Result (resultado As Int)
		If resultado = DialogResponse.POSITIVE Then
		
			Dim sDate, sTime As String
			DateTime.DateFormat = "dd/MM/yyyy"
			DateTime.TimeFormat = "HH:mm:ss"
			sDate = DateTime.Date(DateTime.Now)
			sTime = DateTime.Time(DateTime.Now)
	
			For i = 0 To CLV_PICK_CIEGO.Size - 1
				' Retrieve the panel and child views for the current item
				Dim itemPanel As B4XView = CLV_PICK_CIEGO.GetPanel(i)
				Dim innerPanel As B4XView = itemPanel.GetView(0)
				Dim editText As B4XView = innerPanel.GetView(1)
				Dim inputText As String = editText.As(EditText).Text
	
				' Check if the input text matches the regex pattern for zeros or if it's empty
				If Regex.IsMatch("^[0]+$", inputText) Or inputText = "" Then
					inputText = "0"
				End If
	
				' Retrieve and process the ID label
				Dim idLabel As B4XView = innerPanel.GetView(0)
				Dim idText As String = idLabel.As(Label).Text
				Dim idParts() As String = Regex.Split(CRLF, idText)
'				Log(idParts(1))
				f=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
				f.Position=0

				a=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
				If a.RowCount>0 Then
					a.Position=0
				End If
				Log(a.GetString("ID_ALMACEN"))
				Log(f.GetString("CAT_CL_RUTA"))
				If inputText <> "" Then
					c = Starter.skmt.ExecQuery2("SELECT * FROM PICK_CIEGO where PC_ID_PROD = ?", Array As String (idParts(0)))
					If c.RowCount = 0 Then
						' Insert data into the database
						skmt.ExecNonQuery2("INSERT INTO PICK_CIEGO(PC_ID_PROD, PC_NOM_PROD, PC_CANT, PC_ALMACEN, PC_RUTA, PC_FECHA) VALUES(?,?,?,?,?,?)", Array As String(idParts(0), idParts(1), inputText, a.GetString("ID_ALMACEN"), f.GetString("CAT_CL_RUTA"), sDate&" "&sTime))
					Else
						B4XPages.MainPage.skmt.ExecNonQuery2("Update PICK_CIEGO set PC_CANT = ?  WHERE PC_ID_PROD = ?" , Array As String(inputText ,idParts(0)))
					End If
				End If
				f.Close
				a.Close
				Log("Processed item " & i)
			Next
			Log("Finished processing all items")
			P_CIEGO.Visible = False
			et_buspc.Text = ""
			CLV_PICK_CIEGO.Clear
			c = Starter.skmt.ExecQuery("SELECT PC_ID_PROD, PC_ALMACEN, PC_RUTA, PC_FECHA FROM PICK_CIEGO")
			If c.RowCount > 0 Then
				For i = 0 To c.RowCount - 1
					c.Position = i
					Dim cmd As DBCommand
					cmd.Initialize
					cmd.Name = "select_HIST_PICKCIEGO_SHARK2" '
					cmd.Parameters = Array As Object(c.GetString("PC_ID_PROD"), c.GetString("PC_ALMACEN"), c.GetString("PC_RUTA"), c.GetString("PC_FECHA"), "VENTA")
					reqManager.ExecuteQuery(cmd , 0, $"PICK_C_${c.GetString("PC_ID_PROD")}"$)					
				Next
			End If
			c.close
		Else
		
		End If
	End If
End Sub

Private Sub b_aceptar_Click
	f=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
	f.Position=0

	a=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	If a.RowCount>0 Then
		a.Position=0
	End If
	Log(a.GetString("ID_ALMACEN"))
	Log(f.GetString("CAT_CL_RUTA"))
	
	Dim cmd As DBCommand
	cmd.Initialize
	cmd.Name = "select_CAT_PASS_ARQUEO_SHARK2"
	cmd.Parameters = Array As Object(f.GetString("CAT_CL_RUTA"),a.GetString("ID_ALMACEN"),"PREVENTA")
	reqManager.ExecuteQuery(cmd , 0, "contrasena")
	f.Close
	a.Close
End Sub

Private Sub B_Aceptar_Monto_Click
'	Try
	DateTime.DateFormat = "MM/dd/yyyy"
	sDate=DateTime.Date(DateTime.Now)
	sTime=DateTime.Time(DateTime.Now)
	
	f=B4XPages.MainPage.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info")
	f.Position=0

	a=B4XPages.MainPage.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	If a.RowCount>0 Then
		a.Position=0
	End If
	
	Private cI As Cursor
	Private u As String = "SinUsuario"
	cI=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
	cI.Position=0
	If cI.RowCount > 0 Then u = cI.GetString("USUARIO")
	Private g As Cursor = B4XPages.MainPage.skmt.ExecQuery("select * from ENV_MONTO_LIQ")
	If g.RowCount = 0 Then
	B4XPages.MainPage.skmt.ExecNonQuery2("INSERT INTO ENV_MONTO_LIQ VALUES (?,?,?,?,?)", Array As Object(ET_Add_Monto.Text, a.GetString("ID_ALMACEN"), f.GetString("CAT_CL_RUTA"), u, sDate & " " & sTime))
	f.Close
	a.Close
	
	c = Starter.skmt.ExecQuery("SELECT * FROM ENV_MONTO_LIQ")
	If c.RowCount > 0 Then
		c.Position = 0
		Dim cmd As DBCommand
		cmd.Initialize
			cmd.Name = "select_MontoCuenta_SHARK2"
'		 	LogColor("------------" & c.GetString("EML_USUARIO" & c.GetString("EML_ALMACEN") & c.GetString("EML_RUTA")),Colors.Red)
		cmd.Parameters = Array As Object(c.GetString("EML_USUARIO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"))
		reqManager.ExecuteQuery(cmd , 0, "SelectMontoLiq")
'			cmd.Name = "insert_Monto_Liq_SHARK2"
'			cmd.Parameters = Array As Object(c.GetString("EML_MONTO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"), c.GetString("EML_USUARIO"), "VENTA", c.GetString("EML_FECHA_PED"))
	End If
		c.Close
	Else
		Starter.skmt.ExecNonQuery2("UPDATE ENV_MONTO_LIQ SET EML_MONTO = ? WHERE EML_ALMACEN = ? AND EML_RUTA = ? AND EML_USUARIO = ?", Array As String (ET_Add_Monto.Text ,a.GetString("ID_ALMACEN"), f.GetString("CAT_CL_RUTA"), cI.GetString("USUARIO")))
		f.Close
		a.Close
	
		c = Starter.skmt.ExecQuery("SELECT * FROM ENV_MONTO_LIQ")
		If c.RowCount > 0 Then
			c.Position = 0
			Dim cmd As DBCommand
			cmd.Initialize
			cmd.Name = "select_MontoCuenta_SHARK2"
'		 	LogColor("------------" & c.GetString("EML_USUARIO" & c.GetString("EML_ALMACEN") & c.GetString("EML_RUTA")),Colors.Red)
			cmd.Parameters = Array As Object(c.GetString("EML_USUARIO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"))
			reqManager.ExecuteQuery(cmd , 0, "SelectMontoLiq")
'			cmd.Name = "insert_Monto_Liq_SHARK2"
'			cmd.Parameters = Array As Object(c.GetString("EML_MONTO"), c.GetString("EML_ALMACEN"), c.GetString("EML_RUTA"), c.GetString("EML_USUARIO"), "VENTA", c.GetString("EML_FECHA_PED"))
		End If
		c.Close
	End If

'	MsgboxAsync("Monto Enviado, Si Vuelve a Mandar se sobre escribirá dicho Monto", "Atención")
	p_add_monto.Visible = False
'	Catch
'		Log(LastException.Message)
'		MsgboxAsync("Error al enviar el monto", "Error")
'	End Try
End Sub

Private Sub b_cancelarcodigo_Click
	p_validacion.Visible = False
End Sub

Private Sub B_Can_Monto_Click
	p_add_monto.Visible = False
End Sub

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("soporte@keymonsoft.com")
	email.Subject = "Envio Base de datos SHARK2"
	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 b_recarga_Click
	c = skmt.ExecQuery("SELECT * FROM CAT_GUNAPROD")
	If c.RowCount > 0 Then
'		Subs.panelVisible(p_validacion,0,0)
		recarga = "1"
		
		Starter.skmt.ExecNonQuery("delete from CUENTAA")
		Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object("1"))
		B4XPages.MainPage.tipo_venta = "RECARGA"
		B4XPages.ShowPage("Productos")
	Else
		MsgboxAsync("No hay ruta cargada, favor de cargar día","Atención")
	End If
	c.Close
End Sub

Private Sub b_CargarMonto_Click
	c = skmt.ExecQuery("SELECT *  FROM kmt_info")
	c.Position = 0
	If c.RowCount < 0 Or c.RowCount = 0 Then
		MsgboxAsync("No hay ruta cargada, favor de cargar día","Atención")
	Else 
		Subs.panelVisible(p_add_monto,0,0)
	End If
	c.Close
End Sub

Private Sub P_CIEGO_Click
	
End Sub

Private Sub p_validacion_Click
	
End Sub

Private Sub p_add_monto_Click
	
End Sub
