B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Activity
Version=9.9
@EndOfDesignText@
#Region  Project Attributes 
	#ApplicationLabel: BusTrack Parent
	#VersionCode: 1
	#VersionName: 1.0.0
	'SupportedOrientations possible values: unspecified, portrait or landscape.
	#SupportedOrientations: portrait
	#CanInstallToExternalStorage: False
#End Region
#Region  Activity Attributes 
    #FullScreen: False
    #IncludeTitle: True
    #IgnoreWarnings: 15, 32, 9
#End Region

Sub Process_Globals
End Sub

Sub Globals
    ' Login UI
    Private pnlLogin As Panel
    Private txtPhone As EditText
    Private btnLogin As Button
    
    ' Student Selection UI
    Private pnlStudents As Panel
    Private lstStudents As ListView
    Private btnLogoutParent As Button
    
    Private lblTokenStatus As Label
    Private CurrentStudents As List
    Private rp As RuntimePermissions
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.Title = "BusTrack Parent"
    
    ' Initialize UI programmatically
    InitializeUI
    
    CheckLoginState
    
    ' Force Firebase Initialization (Nudge)
    Dim analytics As FirebaseAnalytics
    analytics.Initialize
    Log("Firebase Nudge Sent")
    
    ' Request Notification Permission (Android 13+)
    CheckNotificationPermission
    
    ' Log SHA1 for Firebase Console Verification
    Log("--- APP DIAGNOSTICS ---")
    Log("Package: " & Application.PackageName)
    Log("-----------------------")
End Sub

Sub CheckNotificationPermission
    Dim p As Phone
    If p.SdkVersion >= 33 Then
        rp.CheckAndRequest("android.permission.POST_NOTIFICATIONS")
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
        If Result = False Then
            ToastMessageShow("Notifications are disabled. You won't receive bus alerts.", True)
        End If
    End If
End Sub

Sub InitializeUI
    ' Login Panel
    pnlLogin.Initialize("")
    Activity.AddView(pnlLogin, 0, 0, 100%x, 100%y)
    pnlLogin.Color = Colors.White
    
    Dim lblTitle As Label
    lblTitle.Initialize("")
    lblTitle.Text = "Parent Login"
    lblTitle.TextSize = 24
    lblTitle.Gravity = Gravity.CENTER
    pnlLogin.AddView(lblTitle, 10%x, 20%y, 80%x, 50dip)
    
    txtPhone.Initialize("txtPhone")
    txtPhone.Hint = "Enter your phone number"
    txtPhone.InputType = txtPhone.INPUT_TYPE_PHONE
    pnlLogin.AddView(txtPhone, 10%x, 35%y, 80%x, 50dip)
    
    btnLogin.Initialize("btnLogin")
    btnLogin.Text = "LOGIN"
    pnlLogin.AddView(btnLogin, 10%x, 45%y, 80%x, 50dip)
    
    ' Students Panel
    pnlStudents.Initialize("")
    Activity.AddView(pnlStudents, 0, 0, 100%x, 100%y)
    pnlStudents.Color = Colors.White
    pnlStudents.Visible = False
    
    Dim lblStudents As Label
    lblStudents.Initialize("")
    lblStudents.Text = "Select Your Child"
    lblStudents.TextSize = 20
    lblStudents.Gravity = Gravity.CENTER
    pnlStudents.AddView(lblStudents, 10%x, 10%y, 80%x, 50dip)
    
    lstStudents.Initialize("lstStudents")
    lstStudents.SingleLineLayout.Label.TextColor = Colors.Black
    lstStudents.SingleLineLayout.Label.TextSize = 16
    lstStudents.SingleLineLayout.ItemHeight = 60dip
    pnlStudents.AddView(lstStudents, 5%x, 20%y, 90%x, 60%y)
    
    ' Logout Button
    btnLogoutParent.Initialize("btnLogoutParent")
    btnLogoutParent.Text = "LOGOUT / CHANGE NUMBER"
    btnLogoutParent.TextColor = Colors.Red
    pnlStudents.AddView(btnLogoutParent, 10%x, 85%y, 80%x, 50dip)
    
    lblTokenStatus.Initialize("")
    lblTokenStatus.Text = "FCM Status: Initializing..."
    lblTokenStatus.TextSize = 10
    lblTokenStatus.TextColor = Colors.LightGray
    lblTokenStatus.Gravity = Gravity.CENTER
    Activity.AddView(lblTokenStatus, 0, 95%y, 100%x, 5%y)
End Sub

Sub Activity_Resume
End Sub

Sub CheckLoginState
    If APIModule.GetToken = "" Or APIModule.GetStudents = "" Then
        ShowLogin
    Else
        ShowStudentSelection
    End If
End Sub

Sub ShowLogin
    pnlLogin.Visible = True
    pnlStudents.Visible = False
End Sub

Sub ShowStudentSelection
    pnlLogin.Visible = False
    pnlStudents.Visible = True
    Log("Showing student selection")
    LoadStudents
    
    ' Register FCM Token if we have one and are logged in
    TryRegisterFCM
End Sub

Public Sub TryRegisterFCM
	Try
		' Don't try to register if UI isn't ready
		If lblTokenStatus.IsInitialized = False Then
			Log("TryRegisterFCM: UI not ready yet, skipping")
			Return
		End If
		
		Dim phone As String = ""
		If File.Exists(File.DirInternal, "parent_phone.txt") Then
			phone = File.ReadString(File.DirInternal, "parent_phone.txt")
		End If
		
		Dim token As String = CallSub(FirebaseMessaging, "GetToken")
		Log("Attempting FCM Registration: Phone=" & phone & ", Token=" & token)
		
		' Validate token is not empty, "null", or invalid
		If token <> "" And token <> "null" And token.Length > 20 Then
			lblTokenStatus.Text = "FCM Status: Registered ✅"
			lblTokenStatus.TextColor = Colors.RGB(76, 175, 80)
			If phone <> "" Then
				APIModule.RegisterFCMToken(phone, token)
			End If
		Else
			lblTokenStatus.Text = "FCM Status: No Token (Waiting for Google...)"
			lblTokenStatus.TextColor = Colors.Red
			Log("FCM Registration skipped: token missing or invalid")
			' Firebase will call TryRegisterFCM automatically via fm_TokenRefresh when token is ready
		End If
	Catch
		Log("Error in TryRegisterFCM: " & LastException)
		' Silently fail - don't crash the app
	End Try
End Sub

Sub btnLogin_Click
    Dim phone As String = txtPhone.Text.Trim
    Log("Login attempt with phone: " & phone)
    If phone = "" Then
        ToastMessageShow("Please enter your phone number", True)
        Return
    End If
    File.WriteString(File.DirInternal, "parent_phone.txt", phone)
    
    Dim data As Map
    data.Initialize
    data.Put("phone", phone)
    
    Dim json As JSONGenerator
    json.Initialize(data)
    
    Dim job As HttpJob
    job.Initialize("parent_login", Me)
    job.PostString(APIModule.ServerURL & "/parent_login.php", json.ToString)
    job.GetRequest.SetHeader("Content-Type", "application/json")
End Sub

Sub LoadStudents
    Dim studentsJson As String = APIModule.GetStudents
    Log("Loading students from storage: " & studentsJson)
    If studentsJson <> "" Then
        Try
            Dim parser As JSONParser
            parser.Initialize(studentsJson)
            CurrentStudents = parser.NextArray
            Log("Students count: " & CurrentStudents.Size)
            
            lstStudents.Clear
            For Each student As Map In CurrentStudents
                Dim sName As String = student.Get("name")
                Dim sBus As String = student.GetDefault("bus_number", "Not Assigned")
                Log("Adding student: " & sName)
                lstStudents.AddSingleLine(sName & " - Bus: " & sBus)
            Next
            
            If CurrentStudents.Size = 0 Then
                ToastMessageShow("No students found", True)
            End If
        Catch
            Log("Error loading students: " & LastException)
        End Try
    End If
End Sub

' Clean up unused sub

Sub lstStudents_ItemClick (Position As Int, Value As Object)
    Dim selectedStudent As Map = CurrentStudents.Get(Position)
    
    Dim busIdObj As Object = selectedStudent.GetDefault("bus_id", 0)
    If 0 = busIdObj Then
        ToastMessageShow("No bus assigned to this student", True)
        Return
    End If
    
    ' Save selected student as JSON string
    Dim gen As JSONGenerator
    gen.Initialize(selectedStudent)
    File.WriteString(File.DirInternal, "selected_student.json", gen.ToString)
    StartActivity(MapActivity)
End Sub

Sub btnLogoutParent_Click
    File.Delete(File.DirInternal, "parent_token.txt")
    File.Delete(File.DirInternal, "students.json")
    File.Delete(File.DirInternal, "parent_phone.txt")
    ShowLogin
End Sub

Sub JobDone(Job As HttpJob)
    If Job.Success Then
        If Job.JobName = "parent_login" Then
            Try
                Dim parser As JSONParser
                parser.Initialize(Job.GetString)
                Dim root As Map = parser.NextObject
                Log("Server Response: " & Job.GetString)
                
                Dim success As Boolean = root.Get("success")
                If success Then
                    Dim token As String = root.Get("token")
                    APIModule.SaveToken(token)
                    
                    ' Save students list
                    Dim students As List = root.Get("students")
                    Log("Received " & students.Size & " students from server")
                    
                    Dim gen As JSONGenerator
                    gen.Initialize2(students)
                    Dim studentsJson As String = gen.ToString
                    APIModule.SaveStudents(studentsJson)
                    
                    ToastMessageShow("Login success: " & students.Size & " students", False)
                    ShowStudentSelection
                Else
                    Dim errorMsg As String = root.Get("error")
                    ToastMessageShow("Error: " & errorMsg, True)
                End If
            Catch
                Log(LastException)
                ToastMessageShow("Login failed", True)
            End Try
        Else If Job.JobName = "register_fcm" Then
            Log("FCM Token registration response: " & Job.GetString)
            Try
                Dim parser As JSONParser
                parser.Initialize(Job.GetString)
                Dim root As Map = parser.NextObject
                If root.Get("success") = True Then
                    Log("FCM Token registered successfully")
                End If
            Catch
                Log("FCM registration parse error: " & LastException)
            End Try
        End If
    Else
        ToastMessageShow("Network error: " & Job.ErrorMessage, True)
    End If
    Job.Release
End Sub
