B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=12.8
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore

	Dim g As GPS
	Dim clie_id As String
	Dim sDate,sTime As String
	Dim usuario As String
	
	Dim c As Cursor
	Dim ruta As String
	Dim Regresar As Button
	

	Dim ListView1 As ListView
	Dim L_CANT As Label
	Dim L_TOTAL As Label
	Dim borra As Button
	Dim Existe As String
	Dim result As String
	'    Dim lat_gps, lon_gps As String

	Private Titulo As Label
	Private b_desc As Button
	Private ListView2 As ListView
	Dim tgl As Toggle
	Private p_nota As Panel
	Private Panel1 As Panel
	Private l_productohist As Label
	Private l_s1 As Label
	Private l_s2 As Label
	Private l_s3 As Label
	Private l_s4 As Label
	Private CustomListView1 As CustomListView
	Private L_PROMEDIOHIST As Label
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)
	Root = Root1
	'load the layout to Root
	Root.LoadLayout("nota2")
	borra.Visible = False
	Titulo.Text = "Acumulado"
	b_desc.Visible = False
End Sub


Sub B4XPage_Appear
'	p_nota.Height = Root.Height
'	p_nota.Width = Root.Width
	Panel1.Visible = False
	If Not(Starter.gps.GPSEnabled) Then
		ToastMessageShow("Es necesario tener el GPS encendido", True)
		StartActivity(Starter.gps.LocationSettingsIntent)
	End If
	L_CANT.Text =""
	L_TOTAL.Text=""
	c=B4XPages.MainPage.skmt.ExecQuery("select count(*) as EXISTE from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa)")
	C.Position=0
	Existe = C.GetString("EXISTE")
	C.Close
	c=B4XPages.MainPage.skmt.ExecQuery("select HVD_CLIENTE,HVD_PRONOMBRE,HVD_CANT,HVD_COSTO_TOT, HVD_FECHA from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) order by HVD_FECHA asc")
	ListView1.Clear
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			Dim label1 As Label
			label1 = ListView1.TwoLinesLayout.Label
			label1.TextSize = 15
			label1.TextColor = Colors.White
			Dim label2 As Label
			label2 = ListView1.TwoLinesLayout.SecondLabel
			label2.TextSize = 15
			label2.TextColor = Colors.White
			ListView1.AddTwoLines(c.GetString("HVD_PRONOMBRE"),"Cantidad #"& c.GetString("HVD_CANT")& " SubTotal $"& c.GetString("HVD_COSTO_TOT")&"      Fecha: "& c.GetString("HVD_FECHA"))
		Next
	End If
	If Existe <> 0 Then
		c=B4XPages.MainPage.skmt.ExecQuery("select SUM(HVD_CANT) AS PC_NOART, SUM(HVD_COSTO_TOT) AS PC_MONTO from HIST_VENTAS where HVD_CLIENTE in (Select CUENTA from cuentaa)")
		C.Position=0
		L_CANT.Text = c.GetString("PC_NOART")
		L_TOTAL.Text = c.GetString("PC_MONTO")
	End If
	ListView1.Visible = False
'	CustomListView1.AsView.Visible = True
	CustomListView1.AsView.Height = Root.Height * 0.45
	CustomListView1.Clear
	Dim prohit As Cursor = B4XPages.MainPage.skmt.ExecQuery("select distinct HVD_PRONOMBRE from HIST_VENTAS WHERE HVD_CLIENTE IN (Select CUENTA from cuentaa) order by HVD_PRONOMBRE asc")

	If prohit.RowCount > 0 Then
    
		' --- Bucle 1: Recorrer cada producto ---
		For sfdf = 0 To prohit.RowCount - 1
			prohit.Position = sfdf
			Dim nombreProducto As String = prohit.GetString("HVD_PRONOMBRE")
        
			' 1. Preparamos las variables para las 4 semanas
			'    (Sem4 = hace 28 días, Sem1 = hace 7 días)
			Dim cant_sem4 As String = "0"
			Dim cant_sem3 As String = "0"
			Dim cant_sem2 As String = "0"
			Dim cant_sem1 As String = "0"
        
			' --- 2. Query 2: (MODIFICADO) ---
			'    Este es el query de SQLite que hicimos, adaptado
			'    para usar la variable 'nombreProducto'
'			Dim sql As String = $"
'				WITH FechasObjetivo (Fecha) AS (
'   					SELECT strftime('%d/%m/%Y', date('now', 'localtime', '-28 days'))
'   					UNION ALL
'   					SELECT strftime('%d/%m/%Y', date('now', 'localtime', '-21 days'))
'    				UNION ALL
'  					SELECT strftime('%d/%m/%Y', date('now', 'localtime', '-14 days'))
'   					UNION ALL
'   					SELECT strftime('%d/%m/%Y', date('now', 'localtime', '-7 days'))
'				)
'				SELECT 
'   					COALESCE(SUM(H.HVD_CANT), 0) AS HVD_CANT_TOTAL
'				FROM 
'   					FechasObjetivo AS F
'				LEFT JOIN 
'    				HIST_VENTAS AS H 
'    				ON F.Fecha = H.HVD_FECHA
'    				AND H.HVD_CLIENTE IN (SELECT CUENTA FROM cuentaa)
'    				AND H.HVD_PRONOMBRE = '${nombreProducto}'
'				GROUP BY
'   					F.Fecha
'				ORDER BY 
'   					SUBSTR(F.Fecha, 7, 4),
'    				SUBSTR(F.Fecha, 4, 2),
			'    				SUBSTR(F.Fecha, 1, 2)
'				"$


			Dim sql As String = $"
    WITH FechasObjetivo (Fecha) AS (
        SELECT strftime('%d/%m/%Y', date('now', 'localtime', '-28 days'))
        UNION ALL
        SELECT strftime('%d/%m/%Y', date('now', 'localtime', '-21 days'))
        UNION ALL
        SELECT strftime('%d/%m/%Y', date('now', 'localtime', '-14 days'))
        UNION ALL
        SELECT strftime('%d/%m/%Y', date('now', 'localtime', '-7 days'))
    )
    SELECT 
        COALESCE(SUM(H.HVD_CANT), 0) AS HVD_CANT_TOTAL,
        -- Si el mes de la fecha es igual al mes actual, devuelve 1, si no 0
        CASE WHEN SUBSTR(F.Fecha, 4, 2) = strftime('%m', 'now', 'localtime') THEN 1 ELSE 0 END AS EsMesActual
    FROM 
        FechasObjetivo AS F
    LEFT JOIN 
        HIST_VENTAS AS H 
        ON F.Fecha = H.HVD_FECHA
        AND H.HVD_CLIENTE IN (SELECT CUENTA FROM cuentaa)
        AND H.HVD_PRONOMBRE = '${nombreProducto}'
    GROUP BY F.Fecha
    ORDER BY SUBSTR(F.Fecha, 7, 4), SUBSTR(F.Fecha, 4, 2), SUBSTR(F.Fecha, 1, 2)
"$
        
			' Log($"Ejecutando para: ${nombreProducto}")
			' Log(sql) ' Descomenta esto si necesitas depurar el query
        
			Dim prohit2 As Cursor = B4XPages.MainPage.skmt.ExecQuery(sql)
        
			' --- 3. Leer los 4 resultados (YA NO NECESITAMOS BUCLE) ---
			'    Sabemos que el query SIEMPRE devuelve 4 filas
			'    en el orden correcto (hace 28, 21, 14, 7 días)
'			Log(prohit2.RowCount)
'			If prohit2.RowCount = 4 Then
'				prohit2.Position = 0
'				cant_sem4 = prohit2.GetString("HVD_CANT_TOTAL") ' Fila 1 (-28 días)
'            
'				prohit2.Position = 1
'				cant_sem3 = prohit2.GetString("HVD_CANT_TOTAL") ' Fila 2 (-21 días)
'            
'				prohit2.Position = 2
'				cant_sem2 = prohit2.GetString("HVD_CANT_TOTAL") ' Fila 3 (-14 días)
'            
'				prohit2.Position = 3
'				cant_sem1 = prohit2.GetString("HVD_CANT_TOTAL") ' Fila 4 (-7 días)
'			Else
'				Log($"Error: El query no devolvió 4 filas para '${nombreProducto}'"$)
'			End If
'        
'			prohit2.Close ' Cerramos el cursor interno
'        	
			Dim promx As Double = (cant_sem4 +  cant_sem3 + cant_sem2 + cant_sem1) / 4
'			
'			
'			CustomListView1.Add(CreateListItem(nombreProducto, cant_sem4, cant_sem3, cant_sem2, cant_sem1, promx ), 1)


			' Variables nuevas para el color (1 = Mes Actual, 0 = Otro)
			Dim c1, c2, c3, c4 As Int

			If prohit2.RowCount = 4 Then
				prohit2.Position = 0
				cant_sem4 = prohit2.GetString("HVD_CANT_TOTAL")
				c1 = prohit2.GetInt("EsMesActual")
    
				prohit2.Position = 1
				cant_sem3 = prohit2.GetString("HVD_CANT_TOTAL")
				c2 = prohit2.GetInt("EsMesActual")
    
				prohit2.Position = 2
				cant_sem2 = prohit2.GetString("HVD_CANT_TOTAL")
				c3 = prohit2.GetInt("EsMesActual")
    
				prohit2.Position = 3
				cant_sem1 = prohit2.GetString("HVD_CANT_TOTAL")
				c4 = prohit2.GetInt("EsMesActual")
			Else
				Log("Error en filas")
			End If
			prohit2.Close

			' Pasamos los indicadores de color al método (c1, c2, c3, c4)
			CustomListView1.Add(CreateListItem(nombreProducto, cant_sem4, cant_sem3, cant_sem2, cant_sem1, promx, c1, c2, c3, c4), 1)
'    
		Next
    
		prohit.Close ' Cerramos el cursor externo
    
	End If
	
	
	
	
End Sub


'Sub CreateListItem(prodhis As String, s1 As Int, s2 As Int, s3 As Int,s4 As Int, prom As Double) As Panel 'ignore
'	Dim p As B4XView = xui.CreatePanel("")
'	p.SetLayoutAnimated(0, 0, 0, 288dip, 170dip)
'	p.LoadLayout("historicobat")
'	l_productohist.Text = prodhis
'	l_s1.Text = s1
'	l_s2.Text = s2
'	l_s3.Text = s3
'	l_s4.Text = s4
'	L_PROMEDIOHIST.text = "Promedio " & prom
'	
'	Return p
'End Sub


Sub CreateListItem(prodhis As String, s1 As Int, s2 As Int, s3 As Int, s4 As Int, prom As Double, m1 As Int, m2 As Int, m3 As Int, m4 As Int) As Panel
	Dim p As B4XView = xui.CreatePanel("")
'	p.SetLayoutAnimated(0, 0, 0, 100%x, 170dip) ' En B4A es mejor usar %x para el ancho
	p.SetLayoutAnimated(0, 0, 0, 288dip, 170dip)
	p.LoadLayout("historicobat")
    
	l_productohist.Text = prodhis
	l_s1.Text = s1
	l_s2.Text = s2
	l_s3.Text = s3
	l_s4.Text = s4
    
	' Cambiar color de fondo de los labels según el mes
	' Si mX es 1 (mes actual) -> Azul, si no -> Amarillo
	l_s1.Color = IIf(m1 = 1, xui.Color_Blue, xui.Color_Yellow)
	l_s2.Color = IIf(m2 = 1, xui.Color_Blue, xui.Color_Yellow)
	l_s3.Color = IIf(m3 = 1, xui.Color_Blue, xui.Color_Yellow)
	l_s4.Color = IIf(m4 = 1, xui.Color_Blue, xui.Color_Yellow)
    
	' Opcional: Cambiar el color del texto para que contraste
	l_s1.TextColor = IIf(m1 = 1, xui.Color_White, xui.Color_Black)
	l_s2.TextColor = IIf(m2 = 1, xui.Color_White, xui.Color_Black)
	l_s3.TextColor = IIf(m3 = 1, xui.Color_White, xui.Color_Black)
	l_s4.TextColor = IIf(m4 = 1, xui.Color_White, xui.Color_Black)

	L_PROMEDIOHIST.Text = "Promedio " & NumberFormat(prom, 1, 2)
    
	Return p
End Sub

' Función auxiliar por si no tienes activado el IIf de B4A (disponible en versiones recientes)
'Sub IIf(Condition As Boolean, TrueValue As Object, FalseValue As Object) As Object
'    If Condition Then Return TrueValue Else Return FalseValue
'End Sub