B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=11.5
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	
	Dim g As GPS
	Dim ruta As String
	Dim c As Cursor
	
	Dim CANCELA As Button
	Dim GUARDA As Button
	Dim cuenta As String
	Dim usuario As String
	Dim sDate,sTime As String
	Dim sDate2,sTime2 As String
	Dim no_cliente As String
	Dim no_ruta As String
	
	Dim r_4 As RadioButton
	Dim E_NOMBRE As EditText
	Dim tgl As Toggle
	Private l_sinUbicacion As Label
	Private p_nuevoCliente As Panel
	Private Label1 As Label
	Private p_botones As Panel
	Private p_cam As Panel
	Private p_camara As Panel
	Private b_foto_inci As Button
'	Private camEx2 As CameraExClass2
	Dim frontCamera As Boolean = False
	Dim fototomada As String = "0"
	Dim ALMACEN As String
	Private et_direccion As EditText
	Private Label2 As Label
	Dim lat As Double = 0
	Dim lon As Double = 0
	Private b_ubicacion As Label
	Private Label3 As Label
	Private cb_giro As B4XComboBox
	Dim giros As String
	Private L_Atiende As Label
	Private ET_Atiende As EditText
End Sub

'You can add more parameters here.
Public Sub Initialize As Object
	Return Me
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
'	B4XPages.SetTitle(Me, $"${Subs.capitalizar(B4XPages.GetPageId(Me))} - ${Application.VersionName}"$)
	Root = Root1
	'load the layout to Root
	Root.LoadLayout("nuevocliente")
	ruta = File.DirInternal
	If File.Exists(ruta, "kmt.db") = False Then
		File.Copy(File.DirAssets, "kmt.db", ruta, "kmt.db")
	End If
'	skmt.Initialize(ruta,"kmt.db", True)
'	p_camara.Height = Root.Height
'	p_camara.Width = Root.Width
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
	''		camEx2.Initialize(p_cam, frontCamera, Me, "Camera1")
	''		frontCamera = camEx2.Front
'		Log("inicializamos Camara")
'	Else
'		ToastMessageShow("Sin permisos de camara!!!", True)
'	End If
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Log("Con permisos para escritura")
	Else
		ToastMessageShow("Sin permisos de escritura!!!", True)
	End If
	
	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_EXTERNAL_STORAGE)
	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
	If Result Then
		Log("Con permisos para escritura")
	Else
		ToastMessageShow("Sin permisos de lectura!!!", True)
	End If
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub B4XPage_Appear
	et_direccion.Text = ""
	E_NOMBRE.Text =  ""
	ET_Atiende.Text = ""
	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	GUARDA.Visible = False
	Subs.panelVisible(p_nuevoCliente, 0, 0)
	p_nuevoCliente.Height = Root.Height
	p_nuevoCliente.Width = Root.Width
	Subs.centraEtiqueta(Label1, Root.Width)
	Subs.centraEtiqueta(Label2, Root.Width)
	Subs.centraEtiqueta(Label3, Root.Width)
	Subs.centraEtiqueta(l_sinUbicacion, Root.Width)
	Subs.centraEtiqueta(b_ubicacion, Root.Width)
	Subs.centraPanel(p_botones, Root.Width)
	E_NOMBRE.Left = Round(Root.Width/2)-(E_NOMBRE.Width/2)
	et_direccion.Left = Round(Root.Width/2)-(E_NOMBRE.Width/2)
	If B4XPages.MainPage.lat_gps <> "0.0" Then
		GUARDA.Visible = True 'Si hay ubicaccion, mostramos el boton de guardar.
		l_sinUbicacion.Visible = True
	End If
	
	If Not(Starter.GPS.GPSEnabled) Then
		ToastMessageShow("Debe Activar el GPS del Equipo.", True)
		StartActivity(Starter.GPS.LocationSettingsIntent)
	Else
		Starter.GPS.Start(0, 0)
'		If Starter.ubicacionActual.Latitude <> 0 Then GPS_LocationChanged(Starter.ubicacionActual)
	End If
	CallSubDelayed(Tracker, "StartFLPSmall")
	
	c = Starter.skmt.ExecQuery("SELECT GIRO FROM CAT_GIRO order by 1")
	Dim Items As List
	Items.Initialize
	Items.Add("SELECCIONA UNA OPCIÓN")
	If c.RowCount > 0 Then
		For i = 0 To c.RowCount-1
			c.Position = i
			Items.Add(c.GetString("GIRO"))
		Next
		cb_giro.SetItems(Items)
	End If
	giros = "SELECCIONA UNA OPCIÓN"
	c.Close
End Sub

Sub GPS_LocationChanged (Location1 As Location)
	If B4XPages.MainPage.lat_gps <> "0.0" Then
		GUARDA.Visible = True 'Si hay ubicaccion, mostramos el boton de guardar.
		l_sinUbicacion.Visible = True
		lat = Location1.Latitude
		lon = Location1.Longitude
		l_sinUbicacion.Text = ("Latitud: " & lat & ", Longotud: "& lon)
	End If
	
	b_ubicacion.TextSize = 13
	b_ubicacion.Text = $"Precisión GPS $1.0{Location1.Accuracy} m"$
	If Location1.Accuracy > 200 Then
		b_ubicacion.TextColor = Colors.Red
		b_ubicacion.TextSize = 16
		b_ubicacion.Text = $"Mala señal $1.0{Location1.Accuracy} m"$
	End If
End Sub

Sub CANCELA_Click
	B4XPages.ShowPage("Principal")
	CallSubDelayed(Tracker, "StartFLP")
End Sub

Sub GUARDA_Click
	' Verifica si el nombre de la tienda está vacío
	If E_NOMBRE.Text = "" Then
		MsgboxAsync("Por favor captura el nombre de la Tienda","Atención")
		' Verifica si la dirección tiene más de 3 caracteres
		Else If et_direccion.Text.Length > 3 Then
		' Verifica si la latitud es diferente de 0
		If lat <> 0 Then
			' Verifica si el giro del cliente está seleccionado
			If giros <> "SELECCIONA UNA OPCIÓN" Or cb_giro.SelectedItem <> "SELECCIONA UNA OPCIÓN" Then
				' Verifica si el encargado que atiende el negocio está capturado
				If ET_Atiende.Text <> "" Then
					DateTime.DateFormat = "MM/dd/yyyy"
					DateTime.Timeformat = "HHmmss"
					sDate = DateTime.Date(DateTime.Now)
					sTime = DateTime.Time(DateTime.Now)
					Log($" ////////////   Date: ${sDate} - Time: ${sTime} ////////////////"$)
					' Aquí creamos manualmente la hora con el separador de los 2 puntos porque en algunas versiones de Android no respeta el formato "Timeformat = 'HH:mm:ss'"
					Private hora As String = sTime.SubString2(0,2)
					Private mins As String = sTime.SubString2(2,4)
					Private segs As String = sTime.SubString(4)
					sTime = hora & ":" & mins & ":" & segs
					Log("////////////// sTime: "&sTime&" ////////////////")
					c = Starter.skmt.ExecQuery("select CAT_CL_RUTA FROM kmt_info")
					c.Position = 0
					no_ruta = c.GetString("CAT_CL_RUTA")
					no_cliente = "N" & sTime & no_ruta
					Log("++ ++ no_cliente = "&no_cliente)
					c.Close
					Starter.skmt.ExecNonQuery2("INSERT INTO kmt_info(CAT_CL_CODIGO,CAT_CL_RUTA,CAT_CL_NOMBRE,CAT_CL_ATIENDE1,CAT_CL_ATIENTE2,CAT_CL_TELEFONO,CAT_CL_EMAIL,CAT_CL_CALLE,CAT_CL_NOEXT,CAT_CL_NOINT,CAT_CL_CALLE1,CAT_CL_CALLE2,CAT_CL_COLONIA,CAT_CL_MUNI,CAT_CL_EDO,CAT_CL_CP,CAT_CL_LONG,CAT_CL_LAT,CAT_CL_MTOCOMPRA,CAT_CL_NUM_SERIEFISICO, gestion, CAT_CL_GIRO) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0,0,?) ", Array As Object (no_cliente,no_ruta, E_NOMBRE.Text,"null","null","null","null","null","null","null","null","null","null","null","null","null",B4XPages.MainPage.lon_gps,B4XPages.MainPage.lat_gps, cb_giro.SelectedItem))
					Starter.skmt.ExecNonQuery2("INSERT INTO HIST_STAY_STORE(HSS_CODIGO,  HSS_IN , HSS_OUT , HSS_TOT) VALUES (?,0,0,0)", Array As Object (no_cliente))
					Starter.skmt.ExecNonQuery("delete from CUENTAA")
					Starter.skmt.ExecNonQuery2("INSERT INTO CUENTAA VALUES (?)", Array As Object(no_cliente))
					c = Starter.skmt.ExecQuery("select ID_ALMACEN from CAT_ALMACEN")
					If c.RowCount > 0 Then
						c.Position = 0
						ALMACEN = c.GetString("ID_ALMACEN")
					End If
					c.Close
					c = Starter.skmt.ExecQuery("select usuario from usuarioa")
					c.Position = 0
					usuario = c.GetString("USUARIO")
					c.Close
					' Starter.skmt.ExecNonQuery2("INSERT INTO HIST_FOTO_CLIENTE(CODIGO, ALMACEN, RUTA) VALUES(?,?,?)", Array As Object(no_cliente, ALMACEN, no_ruta))
					' Starter.skmt.ExecNonQuery2("INSERT INTO  NOVENTA (NV_CLIENTE,NV_FECHA,NV_USER,NV_MOTIVO,NV_LAT,NV_LON,NV_NOMBRE,NV_DIRECCION) VALUES(?,?,?,?,?,?,?,?) ", Array As Object (no_cliente,sDate & sTime, usuario, "NUEVO CLIENTE", lat, lon, E_NOMBRE.Text,et_direccion.Text))
                    
					DateTime.DateFormat = "dd/MM/yyyy"
					DateTime.Timeformat = "HH:mm:ss"
					sDate2 = DateTime.Date(DateTime.Now)
					sTime2 = DateTime.Time(DateTime.Now)
                    
					Starter.skmt.ExecNonQuery2("INSERT INTO CLIENTES_NUEVOS(CN_ID, CN_FECHA, CN_USER, CN_LAT, CN_LON, CN_NOMBRE, CN_DIRECCION, CN_FOTO, CN_RUTA, CN_GIRO, CN_SOLICITA) VALUES (?,?,?,?,?,?,?,?,?,?,?)", Array As String(no_cliente, sDate2 &" "&sTime2, usuario, lat, lon, E_NOMBRE.Text, et_direccion.Text, ALMACEN, no_ruta, cb_giro.SelectedItem, ET_Atiende.Text))
					' fototomada = "0"
					
					Subs.bitacora(Subs.fechanormal(DateTime.Now), usuario, ALMACEN, Subs.traeRuta, "Nuevo Cliente", "", Subs.fechanormal(DateTime.Now), Subs.fechanormal(DateTime.Now), Starter.lat_gps, Starter.lon_gps, "2", "", "", no_cliente)
					Log("Bitacora guardada")
					B4XPages.ShowPage("Cliente")
					CallSubDelayed(Tracker, "StartFLP")
				Else
					' Mensaje de advertencia si ET_Atiende.Text está vacío
					MsgboxAsync("Por favor, debe capturar al encargado que atiende el negocio.","Atención")
				End If
			Else
				MsgboxAsync("Por favor captura el giro del cliente","Atención")
			End If
		Else
			MsgboxAsync("Por favor revisa que tengas señal GPS","Atención")
		End If
	Else
		MsgboxAsync("Por favor captura la dirección del cliente","Atención")
	End If
End Sub




Private Sub p_nuevoCliente_Click
	
End Sub

'Private Sub b_foto_inci_Click
'	camEx2.TakePicture
'	p_camara.Visible = False
''	StopCamera2
'End Sub
'
'Private Sub InitializeCamera2
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_CAMERA)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		camEx2.Initialize(p_cam, frontCamera, Me, "Camera1")
'		frontCamera = camEx2.Front
'		Log("inicializamos Camara")
'	Else
'		ToastMessageShow("Sin permisos de camara!!!", True)
'	End If
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_WRITE_EXTERNAL_STORAGE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		Log("con permisos para escritura")
'	Else
'		ToastMessageShow("Sin permisos de escritura!!!", True)
'	End If
'	
'	Starter.rp.CheckAndRequest(Starter.rp.PERMISSION_READ_EXTERNAL_STORAGE)
'	Wait For B4XPage_PermissionResult (Permission As String, Result As Boolean)
'	If Result Then
'		Log("con permisos para escritura")
'	Else
'		ToastMessageShow("Sin permisos de lectura!!!", True)
'	End If
'End Sub
'
'Sub Camera1_Ready (Success As Boolean)
'	Log("Camara ready")
'	If Success Then
'		camEx2.SetJpegQuality(90)
'		camEx2.SetContinuousAutoFocus
'		camEx2.CommitParameters
'		camEx2.StartPreview
'		Log(camEx2.GetPreviewSize)
'	Else
'		ToastMessageShow("Cannot open camera.", True)
'		Log("Cannot open camera")
'	End If
'End Sub
'
'Sub Camera1_PictureTaken (Data()As Byte)
'	Log("tome foto")
'	Dim filename As String = fototomada
'	Dim Dirp As String = File.DirInternal
'	Dim Dir As String
'	Dim Dir2 As String
'	Try
'		File.MakeDir(Dirp,"/promotoriakmts")
'		Dir = "/promotoriakmts"
'		Log("creado en promotoria " & Dirp & Dir)
'	Catch
'		Dir = ""
'		Log("creado en raiz")
'	End Try
'	
'	Try
'		File.MakeDir(Dirp & Dir,"/reduccion")
'		Dir2 = "/reduccion"
'		Log("creado en promotoria " & Dirp & Dir & Dir2)
'	Catch
'		Dir = ""
'		Log("creado en raiz")
'	End Try
'	
'	camEx2.SavePictureToFile(Data, Dirp&Dir, filename)
'	camEx2.StartPreview 'restart preview
'	ToastMessageShow("Picture saved." & CRLF  & "File size: " & File.Size(Dir, filename) & Dir &"," & filename, True)
'	Log("Picture saved." & CRLF  & "File size: " & File.Size(Dir, filename) & Dir &"," & filename)
'	p_camara.Visible = False
'	StopCamera2
'	
'End Sub
'
'Private Sub StopCamera2
''	Capturing = False
'	If camEx2.IsInitialized Then
'		camEx2.Release
'	End If
'End Sub
'
'
'Private Sub B_FOTO_Click
'	DateTime.DateFormat="ddMMyyyyHHmmss"
'	InitializeCamera2
'	Subs.panelVisible(p_camara, 0, 0)
'	fototomada = DateTime.Now & "_cliente.jpg"
'End Sub

Private Sub cb_giro_SelectedIndexChanged (Index As Int)
	giros = cb_giro.SelectedItem
End Sub

