B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=12.2
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Dim skmt, rkmt As SQL
	Private EventName As String 'ignore
	Private CallBack As Object 'ignore
	Dim rp As RuntimePermissions
	Dim safePath As String
	Dim fechaHoy As String
'	Dim fechaAnt As String
	Dim skmtAttached As Boolean = False
	Dim rkmtAttached As Boolean = False
	'#######  MES Vars  ######
	Private ion As Object
'	Dim device As Phone
'	Private mesCallback As Object
'	Private mesEventName As String
	Dim RD_Init_IsInitialized As Boolean = False
	Dim btAdmin As BluetoothAdmin
	Dim RD_fechaRestauracion As String = ""
	Private fechaRestauracion As String = ""
	Private khdb As SQL
	Dim in As Intent
	Dim intentUsado As Boolean = False
End Sub

'Inicializa la clase "kms_helperSubs", el tercer parametro es la base de datos que se va a usar.
'Ej. kh.Initialize(Me, "kh", skmt)
Public Sub Initialize (vCallback As Object, vEventName As String, db As SQL) As Object
	EventName = vEventName
	CallBack = vCallback
	khdb = db
	Return Me
End Sub

'This event will be called once, before the page becomes visible.
'Private Sub B4XPage_Created (Root1 As B4XView)
'	Root = Root1
'	'load the layout to Root
'End Sub

'RD - Inicializa Respaldo Diario
Sub RD_Init
	Dim Dirp As String = File.DirInternal
	Dim Dir As String
'	Dim Dir2 As String
'	File.MakeDir(File.DirRootExternal,"/Android/kmts")
'	File.MakeDir(rp.GetSafeDirDefaultExternal("/"), "kmts")
	Try
		File.MakeDir(Dirp,"/kmts")
		Dir = "/kmts"
		Log("Creado kmts " & Dirp & Dir)
	Catch
		Dir = ""
		Log("Creado en raiz")
	End Try
'	Log(File.IsDirectory(Dirp, Dir))
	safePath = Dirp & Dir
	'Si no existe el directorio "kmts" en el raiz de la tarjeta de memoria, nos cambiamos al directorio seguro (sdcard/Android/data/kelloggs...)
	If Not(File.IsDirectory(Dirp, Dir)) Then safePath = rp.GetSafeDirDefaultExternal("kmts")
	Log($"Hay directorio: ${Dirp} ${Dir} - ${File.IsDirectory(Dirp, Dir)}"$)
	If Starter.Logger Then Log($"Safepath:${safePath}"$)
	Private name() As String = Regex.split(" ", Application.LabelName) 'Obtenemos el nombre de la app para ponerselo a la BD.	
	rkmt.Initialize(safePath, $"${name(0)}.rkmt.km"$, True)
	Log("TAMAÑO DE ARCHIVO RESPALDO " &File.size(File.DirInternal&"/kmts", $"${name(0)}.rkmt.km"$))
	skmt.Initialize(File.DirInternal,"kmt.db", False)
	If chkIfTableExists(skmt, "PEDIDO") Then rkmt.ExecNonQuery($"create table if not exists PEDIDO (${getTableColumnList(skmt, "PEDIDO")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "CAT_DETALLES_PAQ") Then rkmt.ExecNonQuery($"create table if not exists CAT_DETALLES_PAQ (${getTableColumnList(skmt, "CAT_DETALLES_PAQ")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "CAT_GUNAPROD") Then rkmt.ExecNonQuery($"create table if not exists CAT_GUNAPROD (${getTableColumnList(skmt, "CAT_GUNAPROD")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "CAT_GUNAPROD2") Then rkmt.ExecNonQuery($"create table if not exists CAT_GUNAPROD2 (${getTableColumnList(skmt, "CAT_GUNAPROD2")}, FECHA TEXT)"$)
	agregaColumna(rkmt,"CAT_GUNAPROD", "CAT_GP_TIPOPROD2", "TEXT")
	agregaColumna(rkmt,"CAT_GUNAPROD2", "CAT_GP_TIPOPROD2", "TEXT")
	agregaColumna(rkmt, "kmt_info", "CAT_CL_LIMITECREDITO", "TEXT")
	If chkIfTableExists(skmt, "kmt_info") Then rkmt.ExecNonQuery($"create table if not exists kmt_info (${getTableColumnList(skmt, "kmt_info")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "PROMOS_COMP") Then rkmt.ExecNonQuery($"create table if not exists PROMOS_COMP (${getTableColumnList(skmt, "PROMOS_COMP")}, FECHA TEXT)"$)
	If chkIfTableExists(skmt, "CAT_RMI") Then rkmt.ExecNonQuery($"create table if not exists CAT_RMI (${getTableColumnList(skmt, "CAT_RMI")}, FECHA TEXT)"$)
	DateTime.DateFormat = "yyyyMMdd"
	fechaHoy = DateTime.Date(DateTime.Now)
	If Starter.Logger Then Log("RKMTS: " & rkmt.IsInitialized)
	If revisaSkmtAttached And rkmt.IsInitialized Then RD_Init_IsInitialized = True Else RD_Init_IsInitialized = False
'	revisaRkmtAttached
End Sub

Sub revisaSiExisteRespaldo
	Private extDir As String = ""
	Private name() As String = Regex.split(" ", Application.LabelName) 'Obtenemos el nombre de la app para ponerselo a la BD.
	If File.IsDirectory(File.DirRootExternal, "kmts") Then extDir = "/kmts"
	If File.size(File.DirInternal&"/kmts", $"${name(0)}.rkmt.km"$) < 37000 And File.Exists(File.DirRootExternal & extDir, $"${name(0)}.rkmt.km"$) Then
		LogColor("Copiamos el respaldo desde la tarjeta!!", Colors.red)
		File.Copy(File.DirRootExternal & extDir, $"${name(0)}.rkmt.km"$, File.DirInternal&"/kmts", $"${name(0)}.rkmt.km"$)
	End If
	Sleep(300)
End Sub

'RD - Revisa si esta montada "kmt.db" como "skmt1" y si no, la monta
'Para que "rkmt" vea a "skmt", es necesario montarla (attach). 
Sub revisaSkmtAttached As Boolean
	skmtAttached = False
	Dim rs As ResultSet = rkmt.ExecQuery("SELECT * FROM pragma_database_list")
	Do While rs.NextRow 'Revisamos si esta montada "kmt.db" como "skmt1" y si no, la montamos.
		If rs.GetString("name") = "skmt1" Then skmtAttached = True
	Loop
	If Not(skmtAttached) Then
		rkmt.ExecNonQuery($"attach database '${File.Combine(File.DirInternal, "kmt.db")}' as skmt1;"$)
		skmtAttached = True
	End If
	Return skmtAttached
End Sub

'RD - Revisa si esta montada "kmt.db" como "rkmt1" y si no, la monta
'Para que "skmt" vea a "rkmt", es necesario montarla (attach). 
Sub revisaRkmtAttached As Boolean
	rkmtAttached = False
	Dim rs As ResultSet = skmt.ExecQuery("SELECT * FROM pragma_database_list")
	Do While rs.NextRow 'Revisamos si esta montada "kmt.db" como "rkmt1" y si no, la montamos.
		If rs.GetString("name") = "rkmt1" Then rkmtAttached = True
		Log(rs.GetString("name"))
	Loop
	If Not(rkmtAttached) Then
		
		Private name() As String = Regex.split(" ", Application.LabelName)
		skmt.ExecNonQuery($"attach database '${File.Combine(safePath,$"${name(0)}.rkmt.km"$)}' as rkmt1;"$)
		rkmtAttached = True
	End If
	Return rkmtAttached
End Sub

'Inicializa la BD con "kmt.db" en "File.DirInternal", si el archivo no existe, lo copia desde "File.DirAssets".
'Ej: dim skmt as sql = dbInit
Sub dbInit As SQL 'ignore
	Private db As SQL
	If File.Exists(File.DirInternal, "kmt.db") = False Then File.Copy(File.DirAssets, "kmt.db", File.DirInternal, "kmt.db")
	db.Initialize(File.DirInternal,"kmt.db", True)
'	dbOk(True)
'	Log(db.IsInitialized)
	Return db
End Sub

'RD - Copia la tabla PEDIDO a rkmt.db en la tarjeta del celular.
Sub RD_respalda_pedido
	Private inicio As String = DateTime.Now
	DateTime.DateFormat = "MM/dd/yyyy"
	Private fechaHoy2 As String = DateTime.Date(DateTime.Now)
'	Log("Copiando PEDIDO ...")
	Private x As Cursor = skmt.ExecQuery("select * from PEDIDO")
'	Log(x.RowCount)
	If x.RowCount > 0 Then
		Private lasCols As String = getTableColumnListName(skmt, "PEDIDO")
'		rkmt.BeginTransaction
		rkmt.ExecNonQuery($"delete from PEDIDO where FECHA = '${fechaHoy}'"$)
		rkmt.ExecNonQuery($"insert into PEDIDO (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.PEDIDO where substr(pe_fecha, 1, 10) = '${fechaHoy2}'"$)

'		Private f As Cursor = rkmt.ExecQuery($"Select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.PEDIDO where substr(pe_fecha, 1, 10) = '${fechaHoy2}'"$)
'		Log($">>>>>> registros pedido : ${f.RowCount} - ${fechaHoy}"$)
'		Private d As Cursor = skmt1.ExecQuery($"select ${lasCols}, '${fechaHoy}' as FECHA from PEDIDO where substr(pe_fecha, 1, 10) = '${fechaHoy}'"$)
'		Log(d.RowCount)
'		rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
'		rkmt.EndTransaction
	End If
	x.Close
	LogColor("P: " & ((DateTime.Now - inicio)/1000) & " segs", Colors.RGB(166,37,0))
End Sub

'RD - Copia la tabla CAT_GUNAPRODS a rkmt.db en la tarjeta del celular.
Sub RD_respalda_cat_gunaprod
	Private inicio As String = DateTime.Now
'	Log("Copiando CAT_GUNAPROD ...")

	Private x As Cursor = skmt.ExecQuery("select * from CAT_GUNAPROD")
	If x.RowCount > 0 Then
		Private lasCols As String = getTableColumnListName(skmt, "CAT_GUNAPROD")
		lasCols = lasCols.Replace(", CAT_GP_IMG", "") 'Quitamos la imagen del respaldo.
		rkmt.BeginTransaction
		rkmt.ExecNonQuery($"delete from CAT_GUNAPROD where FECHA = '${fechaHoy}'"$)
		rkmt.ExecNonQuery($"insert into CAT_GUNAPROD (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_GUNAPROD"$)
		rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
		rkmt.EndTransaction
	End If
	x.Close
	LogColor("GP: " & ((DateTime.Now - inicio)/1000) & " segs", Colors.RGB(166,37,0))
End Sub

'RD - Copia la tabla CAT_GUNAPROD de rkmt.db al celular.
Sub RD_restaura_cat_gunaprod
	Private inicio As String = DateTime.Now
'	Log("Restaurando CAT_GUNAPROD ...")
	Log($"FECHA RESTAURACION: ${RD_fechaRestauracion}"$)
	fechaRestauracion = RD_fechaRestauracionSQL(RD_fechaRestauracion)
	Private lasCols As String = getTableColumnListName(rkmt, "CAT_GUNAPROD")
	Log(fechaRestauracion)
	lasCols = lasCols.Replace(", FECHA", "") 'Quitamos la imagen del respaldo.
	Private c As Cursor = rkmt.ExecQuery($"select distinct fecha from CAT_GUNAPROD ${fechaRestauracion} order by fecha desc"$) 'where fecha <> '${fechaHoy}' 'Traemos la ultima fecha antes de hoy.
'	Log(c.RowCount)
	If c.RowCount > 0 Then
		c.Position = 0
'		Log(c.GetString("FECHA"))
		skmt.ExecNonQuery("delete from CAT_GUNAPROD")
		skmt.ExecNonQuery($"insert into CAT_GUNAPROD (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD where fecha = '${c.GetString("FECHA")}'"$)
		Log($"insert into CAT_GUNAPROD (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD where fecha = '${c.GetString("FECHA")}'"$)
	Else
		If fechaRestauracion.Length > 0 Then
			ToastMessageShow($"No hay respaldo GP para la fecha ${fechaRestauracion.SubString(fechaRestauracion.Length - 10)}"$, True)
		Else
			ToastMessageShow($"No hay respaldo GP para la fecha"$, True)
		End If
	End If
	c.Close
	Log("R-GP: " & ((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Copia la tabla CAT_GUNAPROD2 a rkmt.db en la tarjeta del celular.
Sub RD_respalda_cat_gunaprod2
	Private inicio As String = DateTime.Now
'	Log("Copiando CAT_GUNAPROD2 ...")
	Private x As Cursor = skmt.ExecQuery("select * from CAT_GUNAPROD2")
	If x.RowCount > 0 Then
		Private lasCols As String = getTableColumnListName(skmt, "CAT_GUNAPROD2")
		lasCols = lasCols.Replace(", CAT_GP_IMG", "") 'Quitamos la fecha del respaldo.
		rkmt.BeginTransaction
		rkmt.ExecNonQuery($"delete from CAT_GUNAPROD2 where FECHA = '${fechaHoy}'"$)
		rkmt.ExecNonQuery($"insert into CAT_GUNAPROD2 (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_GUNAPROD2"$)
		rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
		rkmt.EndTransaction
	End If
	x.Close
	LogColor("GP2: " & ((DateTime.Now - inicio)/1000) & " segs", Colors.RGB(166,37,0))
End Sub

'RD - Copia la tabla CAT_GUNAPROD2 de rkmt.db al celular.
Sub RD_restaura_cat_gunaprod2
	Private inicio As String = DateTime.Now
'	Log("Restaurando CAT_GUNAPROD2 ...")
	fechaRestauracion = RD_fechaRestauracionSQL(RD_fechaRestauracion)
	Private lasCols As String = getTableColumnListName(rkmt, "CAT_GUNAPROD2")
	lasCols = lasCols.Replace(", FECHA", "") 'Quitamos la fecha del respaldo.
	Private c As Cursor = rkmt.ExecQuery($"select distinct fecha from CAT_GUNAPROD2 ${fechaRestauracion} order by fecha desc"$) 'where fecha <> '${fechaHoy}' 'Traemos la ultima fecha antes de hoy.
'	Log(c.RowCount)
	If c.RowCount > 0 Then
		c.Position = 0
		Log(c.GetString("FECHA"))
		skmt.ExecNonQuery("delete from CAT_GUNAPROD2")
		skmt.ExecNonQuery($"insert into CAT_GUNAPROD2 (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD2 where fecha = '${c.GetString("FECHA")}'"$)
		Log($"insert into CAT_GUNAPROD2 (${lasCols}) select ${lasCols} from rkmt1.CAT_GUNAPROD2 where fecha = '${c.GetString("FECHA")}'"$)
	Else
		If fechaRestauracion.Length > 0 Then
			ToastMessageShow($"No hay respaldo GP2 para la fecha ${fechaRestauracion.SubString(fechaRestauracion.Length - 10)}"$, True)
		Else
			ToastMessageShow($"No hay respaldo GP2 para la fecha"$, True)
		End If
	End If
	c.Close
	'Agregamos al inventario las cantidades del abordo
	Private sqlAbordo As String = ""
	Private sqlfechaAbordo As String = ""
	If fechaRestauracion = "" Then
		sqlAbordo = "where PE_TIPO = 'ABORDO'"
		sqlfechaAbordo = $"And fecha = '${fechaHoy}'"$
	Else
		sqlAbordo = "and PE_TIPO = 'ABORDO'"
		sqlfechaAbordo = ""
	End If
'	Private a As Cursor = rkmt.ExecQuery($"select * from PEDIDO ${fechaRestauracion} ${sqlAbordo} ${sqlfechaAbordo} order by fecha desc"$) 'where fecha <> '${fechaHoy}' 'Traemos la ultima fecha antes de hoy.
'	Log($"select * from PEDIDO ${fechaRestauracion} ${sqlAbordo} ${sqlfechaAbordo} order by fecha desc"$)
'	Log(">>>>>>>>  PEDIDOS " & a.RowCount)
'	If a.RowCount > 0 Then
'		For i = 0 To a.RowCount - 1
'			a.Position = i
'			skmt.ExecNonQuery($"update CAT_GUNAPROD2 set CAT_GP_ALMACEN = CAT_GP_ALMACEN + ${a.GetString("PE_CANT")} where CAT_GP_ID = '${a.GetString("PE_PROID")}'"$)
'			Log($"update CAT_GUNAPROD2 set CAT_GP_ALMACEN = CAT_GP_ALMACEN + ${a.GetString("PE_CANT")}' where CAT_GP_ID = '${a.GetString("PE_PROID")}'"$)
'		Next
'	Else
'		Log("|"&fechaRestauracion&"|")
'		ToastMessageShow($"No hay respaldo PEDIDO para la fecha ${fechaRestauracion.SubString(fechaRestauracion.Length - 10)}"$, True)
'	End If
	Log("R-GP2: " & ((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Copia la tabla CAT_DETALLE_PAQ a rkmt.db en la tarjeta del celular.
Sub RD_respalda_cat_detalle_paq
	Private inicio As String = DateTime.Now
'	Log("Copiando CAT_DETALLES_PAQ ...")
	Private x As Cursor = skmt.ExecQuery("select * from CAT_DETALLES_PAQ")
	If x.RowCount > 0 Then
		Private lasCols As String = getTableColumnListName(skmt, "CAT_DETALLES_PAQ")
		rkmt.BeginTransaction
		rkmt.ExecNonQuery($"delete from CAT_DETALLES_PAQ where fecha = '${fechaHoy}'"$)
		rkmt.ExecNonQuery($"insert into CAT_DETALLES_PAQ (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_DETALLES_PAQ"$)
		rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
		rkmt.EndTransaction
		LogColor("DP: " & ((DateTime.Now - inicio)/1000) & " segs", Colors.RGB(166,37,0))
	End If
	x.Close
End Sub

'RD - Copia la tabla CAT_DETALLES_PAQ de rkmt.db al celular.
Sub RD_restaura_cat_detalle_paq
	Private inicio As String = DateTime.Now
'	Log("Restaurando CAT_DETALLES_PAQ ...")
	fechaRestauracion = RD_fechaRestauracionSQL(RD_fechaRestauracion)
	Private lasCols As String = getTableColumnListName(rkmt, "CAT_DETALLES_PAQ")
	lasCols = lasCols.Replace(", FECHA", "") 'Quitamos la fecha del respaldo.
	Private c As Cursor = rkmt.ExecQuery($"select distinct fecha from CAT_DETALLES_PAQ ${fechaRestauracion} order by fecha desc"$) 'where fecha <> '${fechaHoy}' 'Traemos la ultima fecha antes de hoy.
'	Log(c.RowCount)
	If c.RowCount > 0 Then
		c.Position = 0
'		Log(c.GetString("FECHA"))
		skmt.ExecNonQuery("delete from CAT_DETALLES_PAQ")
		skmt.ExecNonQuery($"insert into CAT_DETALLES_PAQ (${lasCols}) select ${lasCols} from rkmt1.CAT_DETALLES_PAQ where fecha = '${c.GetString("FECHA")}'"$)
		Log($"insert into CAT_DETALLES_PAQ (${lasCols}) select ${lasCols} from rkmt1.CAT_DETALLES_PAQ where fecha = '${c.GetString("FECHA")}'"$)
	Else
		If fechaRestauracion.Length > 0 Then
			ToastMessageShow($"No hay respaldo DP para la fecha ${fechaRestauracion.SubString(fechaRestauracion.Length - 10)}"$, True)
		Else
			ToastMessageShow($"No hay respaldo DP para la fecha"$, True)
		End If
	End If
	c.Close
	Log("R-DP: " & ((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Copia la tabla kmt_info a rkmt.db en la tarjeta del celular.
Sub RD_respalda_kmt_info
	Private inicio As String = DateTime.Now
'	Log("Copiando kmt_info ...")
	Private x As Cursor = skmt.ExecQuery("select * from kmt_info")
	If x.RowCount > 0 Then
		Private lasCols As String = getTableColumnListName(skmt, "kmt_info")
		rkmt.BeginTransaction
		rkmt.ExecNonQuery($"delete from kmt_info where fecha = '${fechaHoy}'"$)
		rkmt.ExecNonQuery($"insert into kmt_info (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.kmt_info"$)
		rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
		rkmt.EndTransaction
	End If
	x.Close
	LogColor("KMT: " & ((DateTime.Now - inicio)/1000) & " segs", Colors.RGB(166,37,0))
End Sub

'RD - Copia la tabla kmt_info de rkmt.db al celular.
Sub RD_restaura_kmt_info
	Private inicio As String = DateTime.Now
'	Log("Restaurando KMT_INFO ...")
	fechaRestauracion = RD_fechaRestauracionSQL(RD_fechaRestauracion)
	Private lasCols As String = getTableColumnListName(rkmt, "kmt_info")
	lasCols = lasCols.Replace(", FECHA", "") 'Quitamos la fecha del respaldo.
	Log($"Restauramos ${fechaRestauracion}"$)
	Log($"select distinct fecha from kmt_info ${fechaRestauracion} order by fecha desc"$)
	Private c As Cursor = rkmt.ExecQuery($"select distinct fecha from kmt_info ${fechaRestauracion} order by fecha desc"$) 'where fecha <> '${fechaHoy}' 'Traemos la ultima fecha antes de hoy.
'	Log(c.RowCount)
	If c.RowCount > 0 Then
		c.Position = 0
		Log(c.GetString("FECHA"))
		skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("DIA_VISITA"))' Ponemos el dia de hoy para visita.
		skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("DIA_VISITA", Subs.traeDiaSemana))
		skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FINDIA_FECHA"))' Borramos fecha de FIN DIA.
		skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FINDIA_PASS"))' Ponemos la contraseña del FIN DIA en "CL"
		skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FINDIA_PASS", "CL"))
		Starter.skmt.ExecNonQuery2("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = ?", Array As Object ("FECHA")) 'Ponemos la fecha de hoy en CAT_VARIABLES para que nos deje ingresar con el usuario guardado.
		Starter.skmt.ExecNonQuery2("INSERT INTO CAT_VARIABLES(CAT_VA_DESCRIPCION, CAT_VA_VALOR) VALUES (?,?)", Array As Object ("FECHA", fechaHoy))
		skmt.ExecNonQuery("delete from kmt_info")
		skmt.ExecNonQuery($"insert into kmt_info (${lasCols}) select ${lasCols} from rkmt1.kmt_info where fecha = '${c.GetString("FECHA")}'"$)
		Log($"insert into kmt_info (${lasCols}) select ${lasCols} from rkmt1.kmt_info where fecha = '${c.GetString("FECHA")}'"$)
	Else
		If fechaRestauracion.Length > 0 Then
			ToastMessageShow($"No hay respaldo KMTI para la fecha ${fechaRestauracion.SubString(fechaRestauracion.Length - 10)}"$, True)
		Else
			ToastMessageShow($"No hay respaldo KMTI para la fecha"$, True)
		End If
	End If
	c.Close
	Log("R-KMT: " & ((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Copia la tabla promos_comp a rkmt.db en la tarjeta del celular.
Sub RD_respalda_promos_comp
	Private inicio As String = DateTime.Now
'	Log("Copiando kmt_info ...")
	Private x As Cursor = skmt.ExecQuery("select * from PROMOS_COMP")
	If x.RowCount > 0 Then
		Private lasCols As String = getTableColumnListName(skmt, "PROMOS_COMP")
		rkmt.BeginTransaction
		rkmt.ExecNonQuery($"delete from PROMOS_COMP where fecha = '${fechaHoy}'"$)
		rkmt.ExecNonQuery($"insert into PROMOS_COMP (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.PROMOS_COMP"$)
		rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
		rkmt.EndTransaction
	End If
	x.Close
	LogColor("KMT: " & ((DateTime.Now - inicio)/1000) & " segs", Colors.RGB(166,37,0))
End Sub

'RD - Copia la tabla promos_comp de rkmt.db al celular.
Sub RD_restaura_promos_comp
	Private inicio As String = DateTime.Now
'	Log("Restaurando KMT_INFO ...")
	fechaRestauracion = RD_fechaRestauracionSQL(RD_fechaRestauracion)
	Private lasCols As String = getTableColumnListName(rkmt, "PROMOS_COMP")
	lasCols = lasCols.Replace(", FECHA", "") 'Quitamos la fecha del respaldo.
	Private c As Cursor = rkmt.ExecQuery($"select distinct fecha from PROMOS_COMP ${fechaRestauracion} order by fecha desc"$) 'where fecha <> '${fechaHoy}' 'Traemos la ultima fecha antes de hoy.
'	Log(c.RowCount)
	If c.RowCount > 0 Then
		c.Position = 0
'		Log(c.GetString("FECHA"))
		skmt.ExecNonQuery("delete from PROMOS_COMP")
		skmt.ExecNonQuery($"insert into PROMOS_COMP (${lasCols}) select ${lasCols} from rkmt1.PROMOS_COMP where fecha = '${c.GetString("FECHA")}'"$)
		Log($"insert into PROMOS_COMP (${lasCols}) select ${lasCols} from rkmt1.PROMOS_COMP where fecha = '${c.GetString("FECHA")}'"$)
	Else
		If fechaRestauracion.Length > 0 Then
			ToastMessageShow($"No hay respaldo PC para la fecha ${fechaRestauracion.SubString(fechaRestauracion.Length - 10)}"$, True)
		Else
			ToastMessageShow($"No hay respaldo PC para la fecha"$, True)
		End If
	End If
	c.Close
	Log("R-KMT: " & ((DateTime.Now - inicio)/1000) & " segs")
End Sub

'RD - Copia la tabla cat_rmi a rkmt.db en la tarjeta del celular.
Sub RD_respalda_cat_rmi
	Private inicio As String = DateTime.Now
'	Log("Copiando cat_rmi ...")
	Private x As Cursor = skmt.ExecQuery("select * from CAT_RMI")
	If x.RowCount > 0 Then
		Private lasCols As String = getTableColumnListName(skmt, "CAT_RMI")
		rkmt.BeginTransaction
		rkmt.ExecNonQuery($"delete from CAT_RMI where fecha = '${fechaHoy}'"$)
		rkmt.ExecNonQuery($"insert into CAT_RMI (${lasCols}, FECHA) select ${lasCols}, '${fechaHoy}' as FECHA from skmt1.CAT_RMI"$)
		rkmt.TransactionSuccessful 'Si no se pone TransactionSuccessful no se escribe NADA!!
		rkmt.EndTransaction
	End If
	x.Close
	LogColor("RMI: " & ((DateTime.Now - inicio)/1000) & " segs", Colors.RGB(166,37,0))
End Sub

'RD - Copia la tabla cat_rmi de rkmt.db al celular.
Sub RD_restaura_cat_rmi
	Private inicio As String = DateTime.Now
'	Log("Restaurando CAT_RMI ...")
	fechaRestauracion = RD_fechaRestauracionSQL(RD_fechaRestauracion)
	Private lasCols As String = getTableColumnListName(rkmt, "CAT_RMI")
	lasCols = lasCols.Replace(", FECHA", "") 'Quitamos la fecha del respaldo.
	Private c As Cursor = rkmt.ExecQuery($"select distinct fecha from CAT_RMI ${fechaRestauracion} order by fecha desc"$) 'where fecha <> '${fechaHoy}' 'Traemos la ultima fecha antes de hoy.
'	Log(c.RowCount)
	If c.RowCount > 0 Then
		c.Position = 0
'		Log(c.GetString("FECHA"))
		skmt.ExecNonQuery("delete from CAT_RMI")
		skmt.ExecNonQuery($"insert into CAT_RMI (${lasCols}) select ${lasCols} from rkmt1.CAT_RMI where fecha = '${c.GetString("FECHA")}'"$)
		Log($"insert into CAT_RMI (${lasCols}) select ${lasCols} from rkmt1.CAT_RMI where fecha = '${c.GetString("FECHA")}'"$)
	Else
		If fechaRestauracion.Length > 0 Then
			ToastMessageShow($"No hay respaldo RMI para la fecha ${fechaRestauracion.SubString(fechaRestauracion.Length - 10)}"$, True)
		Else
			ToastMessageShow($"No hay respaldo RMI para la fecha"$, True)
		End If
	End If
	c.Close
	Log("R-RMI: " & ((DateTime.Now - inicio)/1000) & " segs")
End Sub

'Los subs del los respaldos diarios independientes en una sola llamada.
Sub RD_respaldoBatch 'ignore
	If RD_Init_IsInitialized Then
		RD_respalda_cat_detalle_paq
		RD_respalda_cat_gunaprod
		RD_respalda_cat_gunaprod2
		RD_respalda_kmt_info
		RD_respalda_pedido
		RD_respalda_promos_comp
		RD_respalda_cat_rmi
		RD_copiaRespaldoDiario
	Else
		Log("******   RD NO INICIALIZADO   ********")
	End If
End Sub

'RD - Copia la base de datos del respaldo diario a la memoria externa.
Sub RD_copiaRespaldoDiario 'ignore
	Try
		File.MakeDir(File.DirRootExternal, "kmts")
	Catch
		Log(LastException)
	End Try
	Private extDir As String = ""
	If File.IsDirectory(File.DirRootExternal, "kmts") Then extDir = "/kmts"
	Try
		Private name() As String = Regex.split(" ", Application.LabelName) 'Obtenemos el nombre de la app para ponerselo a la BD.
'		Log($"------  COPIAMOS A SDCARD - ${name(0)}.rkmt.km"$)
		File.Copy(File.DirInternal&"/kmts", $"${name(0)}.rkmt.km"$, File.DirRootExternal & extDir, $"${name(0)}.rkmt.km"$)
	Catch
		Log(LastException)
	End Try
End Sub

'RD - Realiza un "vacuum" de la base de datos "rkmt".
Sub RD_vacuum 'ignore
	Log("Vacuum")
	rkmt.ExecNonQuery("vacuum;")
End Sub

'Regresa el SQL para la especificar la fecha de restauracion.
Sub RD_fechaRestauracionSQL(fecha As String) As String
	Private fechaSQL As String = ""
	If fecha <> "" And IsNumber(fecha) Then fechaSQL = $"where fecha = '${ticksAformatoFecha(fecha, "yyyyMMdd")}'"$
	Return fechaSQL
End Sub

'Agrega una columna a la tabla especificada.
'Hay que indicar el "tipo"  de la columna (TEXT, INTEGER, ETC)
'Ej. agregaColumna(DB, "TABLA", "COLUMNA", "TIPO")
Sub agregaColumna(db As SQL, tabla As String, columna As String, tipo As String) 'ignore
	Try 'Intentamos usar "pragma_table_info" para revisar si existe la columna en la tabla
		Private c As Cursor = db.ExecQuery($"SELECT COUNT(*) AS fCol FROM pragma_table_info('${tabla}') WHERE name='${columna}'"$)
		c.Position = 0
		If c.GetString("fCol") = 0 Then 'Si no esta la columna la agregamos
			db.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
			Log($"Columna "${columna} ${tipo}", agregada a "${tabla}"."$)
		End If
		c.Close
	Catch 'Si no funciona "pragma_table_info" lo hacemos con try/catch
		Try
			db.ExecNonQuery($"ALTER TABLE ${tabla} ADD COLUMN ${columna} ${tipo}"$)
			Log($"Columna "${columna} ${tipo}", agregada a "${tabla}".."$)
		Catch
			Log(LastException)
		End Try
	End Try
End Sub

'Regresa los nombres y tipos de las columnas de una tabla dada.
Sub getTableColumnList(db As SQL, table As String) As String 'ignore
	Private l As String = ""
	If chkIfTableExists(db, table) Then
		Private c As Cursor = skmt.ExecQuery($"pragma table_info(${table})"$)
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				If l.Length = 0 Then
					l = $"${c.GetString("name")} ${c.GetString("type")}"$
				Else
					l = $"${l}, ${c.GetString("name")} ${c.GetString("type")}"$
				End If
			Next
		End If
		c.Close
	Else
		Return "No existe la tabla."
	End If
	Return l
End Sub

'Regresa solo los nombres de las columnas de una tabla dada.
Sub getTableColumnListName(db As SQL, table As String) As String 'ignore
	Private l As String = ""
	If chkIfTableExists(db, table) Then
		Private c As Cursor = skmt.ExecQuery($"pragma table_info(${table})"$)
		If c.RowCount > 0 Then
			For i = 0 To c.RowCount - 1
				c.Position = i
				If l.Length = 0 Then
					l = $"${c.GetString("name")}"$
				Else
					l = $"${l}, ${c.GetString("name")}"$
				End If
			Next
		End If
		c.Close
	Else
		Return "No existe la tabla."
	End If
	Return l
End Sub

'Revisa si una tabla dada existe en una base de datos dada, regresa true o false.
Sub chkIfTableExists(db As SQL, table As String) As Boolean 'ignore
	Private t As Boolean = False 'ignore
	If db.IsInitialized Then
		Private c As Cursor = skmt.ExecQuery($"SELECT name FROM sqlite_master WHERE type='table' AND name='${table}'"$)
		If c.RowCount > 0 Then t = True
		c.Close
	End If
	Return t
End Sub

'Hace visible y trae al frente el panel con los parametros "Top" y "Left" dados
Sub panelVisible(panel As Panel, top As Int, left As Int) 'ignore
	panel.BringToFront
	panel.Visible = True
	panel.Top = top
	panel.Left = left
End Sub

'Centra una etiqueta dentro de un elemento superior
Sub centraEtiqueta(elemento As Label, anchoElementoSuperior As Int) 'ignore
	elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
	etiquetaCentrada(True)
End Sub

Sub etiquetaCentrada(Success As Boolean)
	If SubExists(CallBack, EventName & "_etiquetaCentrada") Then
		CallSub2(CallBack, EventName & "_etiquetaCentrada", Success)
	End If
End Sub

'Centra un panel horizontalmente dentro de un elemento superior
Sub centraPanel(elemento As Panel, anchoElementoSuperior As Int) 'ignore
	elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
End Sub

'Centra un boton horizontalmente dentro de un elemento superior
Sub centraBoton(elemento As Button, anchoElementoSuperior As Int) 'ignore
	elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
End Sub

'Centra un panel verticalmente dentro de un elemento superior
Sub centraPanelV(elemento As Panel, altoElementoSuperior As Int) 'ignore
	elemento.Top = Round(altoElementoSuperior/2)-(elemento.Height/2)
End Sub

'Centra una barra de progreso dentro de un elemento superior
Sub centraProgressBar(elemento As ProgressBar, anchoElementoSuperior As Int) 'ignore
	elemento.Left = Round(anchoElementoSuperior/2)-(elemento.Width/2)
End Sub

'Regresa el usuario de la tabla USUARIOA, si no lo encuentra regresa "SinUsuario"
Sub traeUsuarioDeDB As String 'ignore
	Private c As Cursor
	Private u As String = "SinUsuario"
	c = khdb.ExecQuery("select USUARIO from usuarioa")
	c.Position=0
	If c.RowCount > 0 Then u = c.GetString("USUARIO")
	c.Close
	Return u
End Sub

'Regresa el almacen actual de la base de datos.
Sub traeAlmacen As String 'ignore
	Private c As Cursor
	Private a As String
	c = khdb.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
	c.Position = 0
	a = c.GetString("ID_ALMACEN")
	c.Close
	Return a
End Sub

'Regresa el nombre del producto desde CAT_GUNAPROD.
Sub traeProdNombre(id As String) As String 'ignore
	Private h As Cursor
	Private n As String
	h = khdb.ExecQuery2("select CAT_GP_NOMBRE from CAT_GUNAPROD where CAT_GP_ID = ? ", Array As String(id.Trim))
	If h.RowCount > 0 Then
		h.Position = 0
		n = h.GetString("CAT_GP_NOMBRE")
'		Log(h.RowCount&"|"&id&"|"&n&"|")
	End If
	h.Close
	If n = Null Or n="" Then n = "N/A"
'	Log(h.RowCount&"|"&id&"|"&n&"|")
	Return n
End Sub

'Regresa la ruta actual de la base de datos.
Sub traeRuta As String 'ignore
	Private c As Cursor
	Private r As String
	c = khdb.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
	r = "0"
	If c.RowCount > 0 Then
		c.Position=0
		r = c.GetString("CAT_CL_RUTA")
	End If
	c.Close
	Return r
End Sub

'Regresa el cliente actual de la base de datos (CUENTAA).
Sub traeCliente As String 'ignore
	Private c As Cursor
	Private cl As String
	c = khdb.ExecQuery("Select CUENTA from cuentaa")
	c.Position=0
	cl = c.GetString("CUENTA")
	c.Close
	Return cl
End Sub

'Regresa en un mapa el total de productos y monto del pedido del cliente actual
'resultado = {"productos":"cantidad_de_productos", "monto":"costo_total"}
Sub traeTotalesClienteActual As Map 'ignore
	Private m As Map
	m.Initialize
	Private c_prodsX As Cursor = khdb.ExecQuery("select ifnull(sum(PE_CANT), 0) as cantProds, ifnull(sum(PE_COSTO_TOT), 0) as costoTotal FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) order by PE_PRONOMBRE asc")
	c_prodsX.Position = 0
'	LogColor($"Productos de la orden: ${c_prodsX.GetString("cantProds")}, Total: ${c_prodsX.GetString("costoTotal")}"$, Colors.red)
	m = CreateMap("productos": c_prodsX.GetString("cantProds"), "monto" : c_prodsX.GetString("costoTotal"))
	Return m
End Sub

'Regresa el TOTAL de la venta del cliente
Sub traeTotalCliente As Double
	Private sumaTotal As Double
	Private cursorprueba As Cursor = khdb.ExecQuery2("select PE_COSTO_TOT from pedido where PE_CEDIS <> PE_PROID and pe_cliente in (Select CUENTA from cuentaa) AND PE_CEDIS <> ?", Array As String("DOE"))
	For i= 0 To cursorprueba.RowCount -1
		cursorprueba.Position = i
'		LogColor(cursorprueba.GetString("PE_COSTO_TOT"),Colors.Red)
		sumaTotal =  sumaTotal +  cursorprueba.GetString("PE_COSTO_TOT")
		sumaTotal = NumberFormat2(sumaTotal, 0, 2, 2, False)
'		Log(NumberFormat2(sumaTotal, 0, 2, 2, False))
	Next
	cursorprueba.Close
	Return sumaTotal
End Sub

'Regresa el TOTAL de la venta del cliente DOE.
Sub traeTotalClienteDOE As Double
	Private sumaTotal As Double = 0
	Private cursorprueba As Cursor = khdb.ExecQuery2("select PE_COSTO_TOT from pedido where PE_CEDIS <> PE_PROID and pe_cliente in (Select CUENTA from cuentaa) AND PE_CEDIS = ?", Array As String("DOE"))
	For i= 0 To cursorprueba.RowCount -1
		cursorprueba.Position = i
'		LogColor(cursorprueba.GetString("PE_COSTO_TOT"),Colors.Red)
		sumaTotal =  sumaTotal +  cursorprueba.GetString("PE_COSTO_TOT")
		sumaTotal = NumberFormat2(sumaTotal, 0, 2, 2, False)
'		Log(NumberFormat2(sumaTotal, 0, 2, 2, False))
	Next
	cursorprueba.Close
	Return sumaTotal
End Sub

'Regresa la venta de la ruta desde pedido.
Sub traeVenta As Double 'ignore
	Private sumatotal As Double = 0
	Private cursorprueba As Cursor = khdb.ExecQuery2("select PE_COSTO_TOT from pedido where PE_CEDIS <> PE_PROID and PE_CLIENTE <> 0 and PE_CEDIS <> ?", Array As String("DOE"))
	For i = 0 To cursorprueba.RowCount - 1
		cursorprueba.Position = i
		sumatotal =  sumatotal +  cursorprueba.GetDouble("PE_COSTO_TOT")
'		Log("Total venta: " & NumberFormat2(sumatotal, 0, 2, 2, False))
	Next
	cursorprueba.Close
	Return NumberFormat2(sumatotal, 0, 2, 2, False)
End Sub

'Borra el pedido del cliente actual.
'Borra los registros de la tabla "PEDIDO" y "PEDIDO_CLIENTE"
'Actualiza las tablas "cat_gunaprod" y "kmt_info".
Sub borraPedidoClienteActual As String 'ignore
	Private thisC As Cursor
	thisC = khdb.ExecQuery("select PE_PROID,PE_CANT FROM PEDIDO where pe_cliente in (Select CUENTA from cuentaa) ")
	If thisC.RowCount>0 Then
		For i=0 To thisC.RowCount -1
			thisC.Position=i
			khdb.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_id = ?", Array As Object(thisC.GetString("PE_CANT"),thisC.GetString("PE_PROID")))
			khdb.ExecNonQuery2("INSERT INTO INVENT_X_ENVIAR (ALMACEN , PROID , CANTIDAD ) VALUES(?,?,?) ", Array As Object (traeAlmacen, thisC.GetString("PE_PROID"),thisC.GetString("PE_CANT")* -1))
		Next
	End If
	khdb.ExecNonQuery("delete from pedido_cliente where pc_cliente in (Select CUENTA from cuentaa)")
	khdb.ExecNonQuery("delete from pedido where pe_cliente in (Select CUENTA from cuentaa)")
	khdb.ExecNonQuery("UPDATE kmt_info set gestion = 0 where CAT_CL_CODIGO In (select cuenta from cuentaa)")
	Return 1
End Sub

'Regresa verdadero si la columna gestion en la tabla "kmt_info" tene valor 2.
'si no, entonces regresa falso.
Sub pedidoGuardado As Boolean 'ignore
	Private guardado As Boolean = False
	Private g As Cursor = khdb.ExecQuery("select gestion from kmt_info where CAT_CL_CODIGO in (Select CUENTA from cuentaa)")
	If g.RowCount > 0 Then
		g.Position=0
		If g.GetString("gestion") = "2" Then guardado = True
	End If
	Log($"Guardado=${guardado}"$)
	Return guardado
End Sub

'Regresa verdadero si hay pedido en la tabla "PEDIDO" del cliente actual.
Sub hayPedido As Boolean 'ignore
	Private thisC As Cursor = khdb.ExecQuery($"select count(PE_CLIENTE) as hayPedido from PEDIDO where PE_CLIENTE = '${traeCliente}'"$)
	thisC.Position = 0
	Private hay As Boolean = False
	If thisC.GetInt("hayPedido") > 0 Then hay = True
'	Log($"Cliente actual=${traeCliente}, hayPedido=${hay}"$)
	Return hay
End Sub

'Regresa el limite de abordo especificado en web.
Sub traeLimiteAbordoWeb As Double 'ignore
	Private limite As Int = 0
	Private c As Cursor = khdb.ExecQuery("select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'LIMITE'")
	If c.RowCount > 0 Then
		c.Position = 0
		limite = c.GetString("CAT_VA_VALOR")
	End If
	c.Close
	Return limite
End Sub

'Regresa el limite de abordo de acuerdo al inventario actual.
'Se calcula multiplicando el inventario por el precio del inventario
Sub traeLimiteAbordoXInventario As Double 'ignore
	Private limiteInicial As Double = 0
	Private c As Cursor = khdb.ExecQuery2("select sum(cat_gp_precio * cat_gp_almacen) as limiteInicial from cat_gunaprod2 where cat_gp_almacen > 0 and cat_gp_clasif <> ? ", Array As String("PROMOS"))
	If c.RowCount > 0 Then
		c.Position = 0
		limiteInicial = c.GetDouble("limiteInicial")
	End If
	c.Close
	Return limiteInicial
End Sub

'Regresa el total de la venta de abordo en la tabla pedido.
Sub traeVentaAbordo As Double
'	Log("Venta abordo")
	Private va As Double = 0
	Private c As Cursor = khdb.ExecQuery("select sum(PE_COSTO_TOT) as ventaAbordo from pedido where PE_TIPO = 'ABORDO'")
	If c.RowCount > 0 Then
		c.Position = 0
		va = c.GetDouble("ventaAbordo")
	End If
'	Log("VENTA ABORDO: " & va)
	Return va
End Sub

Sub TraeVentaSinImprimir As Double
	' Buscamos los clientes que tienen pedido y NO estan impresos.
	Private t As Cursor = Starter.skmt.ExecQuery("Select cat_cl_codigo from kmt_info where impresion = 0 and cat_cl_codigo not in (select ci_cuenta from cliente_impreso) and cat_cl_codigo in (select distinct pe_cliente from pedido) and CAT_CL_CODIGO <> '0'")
	If t.RowCount > 0 Then
		Private resta As Double = 0 
		For i = 0 To t.RowCount - 1
			t.Position = i  
			
			Private m As Cursor = Starter.skmt.ExecQuery($"Select SUM(PE_COSTO_TOT) AS RESTA from PEDIDO where PE_CLIENTE = '${t.GetString("CAT_CL_CODIGO")}' "$)
			m.Position = 0 
			resta = resta + m.GetString("RESTA")
			m.Close
			
		Next
	End If
	Return resta
End Sub

'Regresa el monto disponible para el abordo.
Sub traeDisponibleAbordo As Double
'	Log("Venta abordo")
	Private disp As Double = 0
'	Log($"${traeLimiteAbordoWeb} - ${traeLimiteAbordoXInventario} - ${traeVentaAbordo}"$)
	disp = NumberFormat2(((traeLimiteAbordoWeb - traeLimiteAbordoXInventario) - (traeVentaAbordo + TraeVentaSinImprimir)), 0, 2, 2, False)
	Return disp
End Sub

Sub string2date(fecha As String) 'ignore
	Log(fecha)
	DateTime.DateFormat = "MM/dd/yyyy"
	Dim t As Long = DateTime.DateTimeParse(fecha, "00:00:00")
	DateTime.DateFormat = "yy/MM/dd"
	Log($"${t} - ${Subs.fechaKMT(t)}"$)
End Sub

'Guarda el nombre y version de la app en CAT_VARIABLES.
Sub guardaAppInfo 'ignore
	khdb.ExecNonQuery("delete from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'EMPRESA' or CAT_VA_DESCRIPCION = 'APP_NAME' or CAT_VA_DESCRIPCION = 'APP_VERSION'")
	khdb.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_NAME', '${Application.LabelName}')"$)
	khdb.ExecNonQuery($"insert into CAT_VARIABLES (CAT_VA_DESCRIPCION, CAT_VA_VALOR) values ('APP_VERSION', '${Application.VersionName}')"$)
End Sub

'Muestra en el Log los campos y valores que regresan en el JobDone.
Sub logJobDoneResultados(resultado As DBResult) 'ignore
	For Each records() As Object In resultado.Rows
		LogColor($"====== ${resultado.Tag} - REGISTROS = ${resultado.Rows.Size}"$, Colors.RGB(215,37,0))
		For Each k As String In resultado.Columns.Keys
			LogColor(k & " = " & records(resultado.Columns.Get(k)), Colors.RGB(215,37,0))
		Next
	Next
End Sub

'Regresa los tick en el formato de fecha especificado.
'Ej. ticksAformatoFecha(dateTime.now, "yyyymmdd")
'Regresa 20231018
Sub ticksAformatoFecha(fecha As Long, formato As String) As String 'ignore
'	Log(fecha)
	Private OrigFormat As String = DateTime.DateFormat  'save orig date format
	DateTime.DateFormat = formato
	Private nuevaFecha As String=DateTime.Date(fecha)
	DateTime.DateFormat = OrigFormat  'return to orig date format
'	Log(nuevaFecha)
	Return nuevaFecha
End Sub

'Revisa si la aplicación tiene permiso para acceder a las notificaciones.
Sub CheckNotificationAccess As Boolean 'ignore
	Dim ph As Phone
	Dim nstr, pstr As String
	Dim r As Reflector
	pstr = r.GetStaticField("anywheresoftware.b4a.BA", "packageName")
	nstr = ph.GetSettings("enabled_notification_listeners")
	Return nstr.Contains(pstr)
End Sub

'Change CheckBox colors
Sub SetButtonTintList(View As View, Disabled As Int, Enabled As Int) 'ignore
	Dim States(2,1) As Int
	Dim sd As StateListDrawable 'ignore
	States(0, 0) = sd.State_Enabled
	States(1, 0) = sd.State_Disabled
	Dim Color(2) As Int = Array As Int(Enabled, Disabled)
	Dim CSL As JavaObject
	CSL.InitializeNewInstance("android.content.res.ColorStateList",Array(States,Color))
	Dim jo As JavaObject
	jo.InitializeStatic("android.support.v4.widget.CompoundButtonCompat")
	jo.RunMethod("setButtonTintList", Array(View, CSL))
End Sub

'Regresa si la geocerca se DEBE o NO de tomar en cuenta para la venta. 
Sub traeUsarGeocerca As Boolean 'ignore
	Private GC As Boolean = True
	Private x As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'GEOCERCA'"$)
	If x.RowCount > 0 Then
		x.Position = 0
		If x.GetString("CAT_VA_VALOR") = "false" Then GC = False
	End If
	Return GC
End Sub

'Regresa si la carta porte se DEBE o NO de tomar en cuenta para cargar día. 
Sub traeUsarCartaPorte As Boolean 'ignore
	Private CP As Boolean = True
	Private x As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'CARTAPORTE'"$)
	If x.RowCount > 0 Then
		x.Position = 0
		If x.GetString("CAT_VA_VALOR") = "false" Then CP = False
	End If
	Return CP
End Sub

'Regresa si se debe de usar el intent de importar la base d datos desde Whatsapp. 
Sub traeUsarIntentBDWA As Boolean 'ignore
	Private BDWA As Boolean = False
	Private x As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'IMPORTAR_BD_WA'"$)
	If x.RowCount > 0 Then
		x.Position = 0
		If x.GetString("CAT_VA_VALOR") = "true" Then BDWA = True
	End If
'	Log($"cb_importarBDWA = ${BDWA}"$)
	Return BDWA
End Sub

'Regresa los clientes nuevos maximos.
'Si no está especificado, el default es 2.
Sub traeMaxClientesNuevos As Int 'ignore
	Private CN As Int = 2
	Private x As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'MAXCTESNUEVOS'"$)
	If x.RowCount > 0 Then
		x.Position = 0
		CN = x.GetString("CAT_VA_VALOR")
	End If
	Return CN
End Sub

'Regresa verdadero o falso dependiendo si el cliente lleva pedido DOE.
Sub clienteConDOE As Boolean 'ignore
	Private c As Cursor = Starter.skmt.ExecQuery2("select count(*) as CUANTOS FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) AND PE_CEDIS = ?", Array As String("DOE"))
	Private b As Cursor = Starter.skmt.ExecQuery("select COUNT(*) AS CLIENTE_DOE from PEDIDO_DOE WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) ")
	c.Position = 0
	b.Position = 0
	If c.GetString("CUANTOS") > 0 Or b.GetString("CLIENTE_DOE") > 0 Then Return True Else Return False
End Sub

'Regresa verdadero si el usuario actual ya imprimio la venta.
Sub revisaImpresa As Boolean
	Dim imp As Boolean = False
'	Dim i As Cursor = Starter.skmt.ExecQuery("select count(*) as CUANTOS from CLIENTE_IMPRESO where CI_CUENTA in (Select CUENTA from cuentaa)")
	Dim i As Cursor = Starter.skmt.ExecQuery("select count(*) as CUANTOS from kmt_info where (impresion = 1 or cat_cl_codigo in (select ci_cuenta from cliente_impreso)) and CAT_CL_CODIGO in (Select CUENTA from cuentaa)")
	i.Position = 0
	If i.GetString("CUANTOS") > 0 Then imp = True Else imp = False
	Return imp
End Sub

' Se revisa si hay una intención (intent) de abrir una base de datos y si es así, entonces se importa esa base de datos.
Sub importaBDDesdeWhatsApp
	Private tmpBDWA As Boolean = traeUsarIntentBDWA
	If Not(in.IsInitialized) Then in = B4XPages.GetNativeParent(B4XPages.MainPage).GetStartingIntent ' Si se usa esta funcion en Mainpage, se pone "Me" en lugar de B4XPages.MainPage.
	If Not(intentUsado) And in <> Null Then
'		Log(in)
		intentUsado = True
'			Log(in.As(String))
		If in.GetData <> Null Then
			Dim XmlData As String
			XmlData = in.GetData
			Try
				Dim OutStr As OutputStream = File.OpenOutput(File.DirInternal,"kmt.db",False)
				Dim InStr As InputStream = File.OpenInput("ContentDir",XmlData)
				File.Copy2(InStr,OutStr)
				LogColor("BD copiada a interna.", Colors.Blue)
				OutStr.Close
				If in.As(String).Contains("whatsapp") Then ToastMessageShow("BD cargada desde Whatsapp", False)
			Catch
				Log(LastException)
			End Try
'				ExitApplication
			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', '${tmpBDWA}')"$)
			Private a As Cursor = Starter.skmt.ExecQuery($"select CAT_VA_VALOR from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'APP_NAME'"$)
			If a.RowCount > 0 Then
				a.Position = 0
				ToastMessageShow($"BD de "${a.GetString("CAT_VA_VALOR")}" cargada."$, True)
			End If
			a = Starter.skmt.ExecQuery($"select * from usuarioa"$)
			If a.RowCount > 0 Then
				a.Position = 0
				B4XPages.MainPage.user.Text = a.GetString("USUARIO")
				B4XPages.MainPage.pass.Text = a.GetString("PASS")
			End If
		End If
	End If
End Sub

'################  Manage External Storage (MES)   #########################
'
''Inicializa "Manage External Storage" (MES), que nos da acceso a la tarjeta de memoria en Android 11+
'Public Sub MES_Init (mCallBack As Object, mEventName As String)
'	mesCallback = mCallBack
'	mesEventName = mEventName
'End Sub
'
'Sub MES_checkPermission 'ignore
''	' 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.CheckAndRequestPermission(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(MES_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")
''			MES_GetPermission
''			Wait For MES_StorageAvailable
''		End If
''	End If
'End Sub
'
'' Determine if the app already has MANAGE_EXTERNAL_STORAGE call Environment.isExternalStorageManager()
'' Return True if this app already has MANAGE_EXTERNAL_STORAGE permission
'Public Sub MES_HasPermission As Boolean
'	Dim has As Boolean	
'	Dim jo As JavaObject
'	jo.InitializeStatic("android.os.Environment")
'	has = jo.RunMethod("isExternalStorageManager", Null)	
'	Return has
'End Sub
'
'' Check whether this app has MANAGE_EXTERNAL_STORAGE permission
'' If not show the user a dialog to enable MANAGE_EXTERNAL_STORAGE permission for this app
'' Raises the StorageAvailable event in the calling activity when complete
'Public Sub MES_GetPermission
'	If MES_HasPermission Then
'		RaiseEvent
'		Return
'	End If
'	Dim in As Intent
'	' Be sure to reference your app package name in "pakageg:xxx"
'	in.Initialize("android.settings.MANAGE_APP_ALL_FILES_ACCESS_PERMISSION", $"package:${Application.PackageName}"$)
'	StartActivityForResult(in)
'End Sub
'
'Private Sub RaiseEvent
'	Log("Calling : " &  mesEventName & "_StorageAvailable")
'	CallSubDelayed(mesCallback, mesEventName & "_StorageAvailable")
'End Sub
'
'Private Sub ion_Event (MethodName As String, Args() As Object) As Object
'	RaiseEvent
'	Return Null
'End Sub
'
'Private Sub StartActivityForResult(i As Intent)
'	Dim jo As JavaObject = MES_GetBA
'	ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
'	jo.RunMethod("startActivityForResult", Array As Object(ion, i))
'End Sub
'
'Private Sub MES_GetBA As Object
'	Dim jo As JavaObject = Me
'	Return jo.RunMethod("getBA", Null)
'End Sub
'################  TERMINA Manage External Storage (MES)   #########################


'################  INICIA ENABLE BLUETOOTH   #########################
Sub StartBluetooth 'ignore
	btAdmin.Initialize("btAdmin")
	Log("btAdmin: " & btAdmin.IsEnabled)
	If btAdmin.IsEnabled = False Then
		Wait For (EnableBluetooth) Complete (Success As Boolean)
		If Success = False Then
			ToastMessageShow("Failed to enable bluetooth", True)
		End If
		Log(Success)
	End If
	Log($"BTADMIN: ${btAdmin.IsEnabled}"$)
End Sub

Sub EnableBluetooth As ResumableSub
	ToastMessageShow("Enabling Bluetooth adapter...", False)
	Private ph As Phone
	If ph.SdkVersion >= 31 Then
		rp.CheckAndRequest("android.permission.BLUETOOTH_CONNECT")
		Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
		If Result = False Then Return False
		Log($"BTCONNECT: ${Result}"$)
		If ph.SdkVersion >= 33 Then
			Dim in As Intent
			in.Initialize("android.bluetooth.adapter.action.REQUEST_ENABLE", "")
			StartActivityForResult(in)
			Wait For ion_Event (MethodName As String, Args() As Object)
			Return btAdmin.IsEnabled
		End If
	End If
	Return btAdmin.Enable
End Sub

Private Sub GetBA As Object
	Dim jo As JavaObject = Me
	Return jo.RunMethod("getBA", Null)
End Sub

Private Sub StartActivityForResult(i As Intent)
	Dim jo As JavaObject = GetBA
	ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
	jo.RunMethod("startActivityForResult", Array As Object(ion, i))
End Sub
'################  TERMINA ENABLE BLUETOOTH   #########################

'Regresa el descuento de condiciones comerciales por TIPO.
Sub traeDescXTipo(clienteId As String, tipo As String) As String 'ignore
	Private desc As String = "0"
	Private c As Cursor = khdb.ExecQuery($"Select * from DESC_CLIENTES where DC_CL_CLIENTE = '${clienteId}'"$)
	If c.RowCount > 0 Then
		c.Position = 0
		If tipo = "PING" Then desc = c.GetString("CAT_CL_DESCUENTO_PING")
		If tipo = "RTEC" Then desc = c.GetString("CAT_CL_DESCUENTO_RTEC")
		If tipo = "SALTY SNACKS" Then desc = c.GetString("CAT_CL_DESCUENTO_SS")
	End If
	c.Close
	Return desc
End Sub

'Regresa el descuento de condiciones comerciales por SKU.
Sub traeDescXSku(clienteId As String, prodId As String) As String 'ignore
	Private desc As String = "0"
	Private c As Cursor = khdb.ExecQuery($"Select * from CAT_DESCUENTOS_SKU where CAT_DS_CLIENTE = '${clienteId}' and CAT_DS_PRODID = '${prodId}'"$)
	If c.RowCount > 0 Then
		c.Position = 0
		desc = c.GetString("CAT_DS_PORCENTAJE")
	End If
	Return desc
End Sub

Sub ping As ResumableSub
	Private ph As Phone
	Wait For (ph.ShellAsync("ping", Array As String("-c 1","-W 5", "8.8.8.8"))) Complete (Success As Boolean, ExitValue As Int, StdOut As String, StdErr As String)
	If Success Then
'		Log("ExitValue:" & ExitValue)
'		Log("StdError:" & StdErr)
		Private res() As String = Regex.Split(",", StdOut)
		For i = 0 To res.Length - 1
			If res(i).Contains("1 received") Then
				If Starter.logger Then LogColor(">>> HAY CONEXION", Colors.Green)
				Starter.pingShell = True
			Else If res(i).Contains("0 received") Then
				If Starter.logger Then LogColor(">>> NO HAY CONEXION", Colors.Red)
				Starter.pingShell = False
			End If
'			Log(res(i))
		Next
'		LogColor("StdOut: " & res, Colors.Blue)
'		If B4XPages.IsInitialized Then B4XPages.MainPage.cb_internet.Checked = Starter.ping
		If Not(Starter.pingShell) Then
			If Starter.logger Then Log("Sin conexión a Google!!!")
'			notiLowReturn("SIN INTERNET     ❌", "NO hay conexion a Google.", Monitor.nid)
'			If B4XPages.IsInitialized Then B4XPages.MainPage.l_status.Text = "NO hay conexión a Google!!"
		End If
	Else
		Log("Error: " & LastException)
	End If
End Sub

'Trae el limite de credito para el cliente especificado.
Sub traeLimiteCredito(idCliente As String) As Double
	Private limite As Double = 10000000
	Private c As ResultSet = khdb.ExecQuery($"select ifnull(CAT_CL_BFACTURA,10000000) as CAT_CL_BFACTURA from kmt_info where CAT_CL_CODIGO = '${idCliente}' and CAT_CL_BCREDITO = 0"$)
	Do While c.NextRow
'		Log($"-${c.GetDouble("CAT_CL_BFACTURA")}-"$)
		limite = c.GetDouble("CAT_CL_BFACTURA")
	Loop
'	Log($"Limite: ${NumberFormat2(limite, 1, 0, 0, True)}"$)
	Return limite
End Sub

'Regresa el total del pedido en la tabla "PEDIDO" del cliente actual.
'Utiliza la columna PE_COSTO_TOT para hacer la suma.
Sub totalPedido As Long 'ignore
	Private cT As Cursor = Starter.skmt.ExecQuery($"select sum(PE_COSTO_TOT) as total from PEDIDO where PE_CLIENTE = '${traeCliente}'"$)
'	Log($"select sum(PE_COSTO_TOT) as total from PEDIDO where PE_CLIENTE = '${traeCliente}'"$)
	Private pTotal As Long = 0
	If cT.RowCount > 0 Then
		cT.Position = 0
'		Log("|"&cT.GetLong("total")&"|"&pTotal)
		Private tempT As String = cT.GetLong("total")
		If tempT <> "null" And tempT <> Null Then
'			Log("|"&cT.GetLong("total")&"|")
			pTotal = tempT
		End If
'		Log($"Cliente actual=${traeCliente}, hayPedido=${hay}"$)
	End If
	cT.Close
	Return pTotal
End Sub

'Revisa si esta activo el MOTIVO NO VISITA y regresa verdadero o falso
Sub motivoNoVisitaActivo As Boolean
	Private rnv As Boolean = False
	Private nv As Cursor = khdb.ExecQuery($"select ifnull(CAT_VA_VALOR, 0) as valor from CAT_VARIABLES where CAT_VA_DESCRIPCION = 'NOVISITA_ACTIVA'"$)
'	Log(nv.RowCount)
	If nv.RowCount > 0 Then
		nv.Position = 0
		Log(nv.GetString("valor"))
		If nv.GetString("valor") = "1" Then rnv = True
	End If
	Return rnv
End Sub