using Justice.Helpers; using Justice.Models; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace Justice.Views { public partial class AddContactPage : ContentPage { private readonly DatabaseHelper _databaseHelper; public ObservableCollection Contacts { get; set; } public AddContactPage() { InitializeComponent(); _databaseHelper = new DatabaseHelper(); Contacts = new ObservableCollection(); ContactsListView.ItemsSource = Contacts; } protected override async void OnAppearing() { base.OnAppearing(); await LoadContactsAsync(); } private async Task LoadContactsAsync() { try { Contacts.Clear(); var contactsFromDb = await _databaseHelper.GetAllAsync(); foreach (var contact in contactsFromDb) { Contacts.Add(contact); } } catch (Exception ex) { await DisplayAlert("Error", $"Failed to load contacts: {ex.Message}", "OK"); } } private async void OnSaveContactClicked(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(NameEntry.Text) || string.IsNullOrWhiteSpace(MobileNumberEntry.Text) || GroupPicker.SelectedItem == null) { await DisplayAlert("Error", "All fields are required.", "OK"); return; } var contact = new EmergencyContact { Name = NameEntry.Text.Trim(), MobileNumber = MobileNumberEntry.Text.Trim(), Group = GroupPicker.SelectedItem.ToString() }; try { await _databaseHelper.InsertAsync(contact); await LoadContactsAsync(); NameEntry.Text = string.Empty; MobileNumberEntry.Text = string.Empty; GroupPicker.SelectedItem = null; await DisplayAlert("Success", "Contact saved successfully!", "OK"); } catch (Exception ex) { await DisplayAlert("Error", $"Failed to save contact: {ex.Message}", "OK"); } } private async void OnDeleteContactClicked(object sender, EventArgs e) { try { Console.WriteLine("Delete button clicked."); // Debug log var button = sender as Button; if (button?.CommandParameter is EmergencyContact contactToDelete) { Console.WriteLine($"Attempting to delete contact: {contactToDelete.Name}"); // Debug log bool confirm = await DisplayAlert("Delete Contact", $"Are you sure you want to delete {contactToDelete.Name}?", "Yes", "No"); if (!confirm) return; await _databaseHelper.DeleteAsync(contactToDelete); Contacts.Remove(contactToDelete); await DisplayAlert("Success", "Contact deleted successfully!", "OK"); } else { Console.WriteLine("CommandParameter is null or invalid."); // Debug log } } catch (Exception ex) { Console.WriteLine($"Error in OnDeleteContactClicked: {ex.Message}"); // Debug log await DisplayAlert("Error", $"Failed to delete contact: {ex.Message}", "OK"); } } } }