using System;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using MySql.Data.MySqlClient;

namespace SkyTeam
{
    public partial class verfuegbareFluge : Page
    {
        private string _fromCity;
        private string _toCity;
        private DateTime? _flightDate;

        public verfuegbareFluge(string from = "", string to = "", DateTime? date = null)
        {
            InitializeComponent();

            _fromCity = from;
            _toCity = to;
            _flightDate = date;

            LoadFlights();
        }

        private void LoadFlights()
        {
            string query = @"SELECT f.Id, f.Flugnummer, f.Abflugort AS 'From', f.Zielort AS 'To', 
                             z.Modell AS Plane, f.Abflugdatum AS Date
                             FROM fluege f
                             JOIN flugzeuge z ON f.FlugzeugId = z.Id
                             WHERE 1=1"; 

            if (!string.IsNullOrWhiteSpace(_fromCity))
            {
                query += " AND f.Abflugort LIKE @from";
            }
            if (!string.IsNullOrWhiteSpace(_toCity))
            {
                query += " AND f.Zielort LIKE @to";
            }
            if (_flightDate.HasValue)
            {
                query += " AND DATE(f.Abflugdatum) = @date";
            }

            try
            {
                using (MySqlConnection conn = new MySqlConnection(DatenbankServices.GetConnection()))
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand(query, conn);

                    if (!string.IsNullOrWhiteSpace(_fromCity))
                        cmd.Parameters.AddWithValue("@from", "%" + _fromCity + "%");

                    if (!string.IsNullOrWhiteSpace(_toCity))
                        cmd.Parameters.AddWithValue("@to", "%" + _toCity + "%");

                    if (_flightDate.HasValue)
                        cmd.Parameters.AddWithValue("@date", _flightDate.Value.ToString("yyyy-MM-dd"));

                    MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    AvailableFlightsDataGrid.ItemsSource = dt.DefaultView;

                    if (dt.Rows.Count == 0)
                    {
                        MessageBox.Show("Keine Flüge gefunden.");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler beim Laden: " + ex.Message);
            }
        }

        private void BookFlight_Click(object sender, RoutedEventArgs e)
        {
            if (AvailableFlightsDataGrid.SelectedItem == null)
            {
                MessageBox.Show("Bitte wählen Sie einen Flug aus!");
                return;
            }

            // Source: Stack Overflow  "Get selected row item in DataGrid WPF"
            DataRowView row = (DataRowView)AvailableFlightsDataGrid.SelectedItem;
            int flightId = Convert.ToInt32(row["Id"]);

            if (SessionManager.CurrentUserId == 0)
            {
                MessageBox.Show("Fehler: Nicht eingeloggt.");
                return;
            }

            string query = "INSERT INTO buchungen (UserId, FlugId) VALUES (@uid, @fid)";

            try
            {
                using (MySqlConnection conn = new MySqlConnection(DatenbankServices.GetConnection()))
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@uid", SessionManager.CurrentUserId);
                    cmd.Parameters.AddWithValue("@fid", flightId);
                    cmd.ExecuteNonQuery();
                }

                MessageBox.Show("Erfolgreich gebucht!");
                NavigationService.Navigate(new BuchungenPage());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Fehler: " + ex.Message);
            }
        }

        private void HomeButton_Click(object sender, RoutedEventArgs e) => NavigationService.Navigate(new NavigationPage());
        private void BookingsButton_Click(object sender, RoutedEventArgs e) => NavigationService.Navigate(new BuchungenPage());
        private void SettingsButton_Click(object sender, RoutedEventArgs e) => NavigationService.Navigate(new SettingsPage());
        private void LogoutButton_Click(object sender, RoutedEventArgs e) => NavigationService.Navigate(new LogInPage());
    }
}