using MySql.Data.MySqlClient;
using PdfSharp.Drawing;
using PdfSharp.Fonts;
using PdfSharp.Pdf;
using System;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using static System.Runtime.InteropServices.JavaScript.JSType;
using System.IO;

namespace SkyTeam
{
    public partial class BuchungenPage : Page
    {
        public BuchungenPage()
        {
            InitializeComponent();
            LoadBookings();
        }

        private void LoadBookings()
        {
            if (SessionManager.CurrentUserId == 0) return; 

            string query = @"SELECT b.Id AS BuchungId, f.Flugnummer, f.Abflugort, f.Zielort, f.Abflugdatum, b.Status 
                             FROM buchungen b
                             JOIN fluege f ON b.FlugId = f.Id
                             WHERE b.UserId = @uid";

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

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

                    if (dt.Rows.Count > 0)
                    {
                        BookingsGrid.ItemsSource = dt.DefaultView;
                        NoBookingsView.Visibility = Visibility.Collapsed;
                        BookingsGrid.Visibility = Visibility.Visible;
                        CancelBtn.Visibility = Visibility.Visible;
                        CreatePdfBtn.Visibility = Visibility.Visible;
                    }
                    else
                    {
                        NoBookingsView.Visibility = Visibility.Visible;
                        BookingsGrid.Visibility = Visibility.Collapsed;
                        CancelBtn.Visibility = Visibility.Collapsed;
                        CreatePdfBtn.Visibility = Visibility.Collapsed;
                    }
                }
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

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

            DataRowView row = (DataRowView)BookingsGrid.SelectedItem;
            int bid = Convert.ToInt32(row["BuchungId"]);

            if (MessageBox.Show("Stornieren?", "Confirm", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                using (MySqlConnection conn = new MySqlConnection(DatenbankServices.GetConnection()))
                {
                    conn.Open();
                    new MySqlCommand($"DELETE FROM buchungen WHERE Id={bid}", conn).ExecuteNonQuery();
                }
                LoadBookings(); 
            }
        }
        // Idee und Grundlage aus folgendem Video:
        // https://www.youtube.com/watch?v=sfeJprlUT7E
        // Datum: 05.03.2026
        // Anpassung und Implementierung mit Unterstützung von ChatGPT (OpenAI) 
        public class CustomFontResolver : IFontResolver
        {
            private readonly string fontPath = "OpenSans-Regular.ttf";

            public string DefaultFontName => "OpenSans";

            public byte[] GetFont(string faceName)
            {
                return File.ReadAllBytes(fontPath);
            }

            public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
            {
                return new FontResolverInfo("OpenSans");
            }
        }

        // Feature: PDF-Export für Flugbuchungen hinzugefügt
        //Quelle:
        //YouTube Tutorial: https://www.youtube.com/watch?v=C-yMypr_TdY
        //Datum: 05.03.2026
        private void CreatePdf_Click(object sender, RoutedEventArgs e)
        {
            if (BookingsGrid.SelectedItem == null)
            {
                MessageBox.Show("Bitte wählen Sie einen Flug aus.");
                return;
            }

            DataRowView row = (DataRowView)BookingsGrid.SelectedItem;

            int buchungId = Convert.ToInt32(row["BuchungId"]);
            string flugNr = row["Flugnummer"].ToString();
            string von = row["Abflugort"].ToString();
            string nach = row["Zielort"].ToString();
            DateTime datum = Convert.ToDateTime(row["Abflugdatum"]);
            string status = row["Status"].ToString();

            string logoPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "icon.png");
            XImage logo = XImage.FromFile(logoPath);

            PdfDocument document = new PdfDocument();
            document.Info.Title = "Flugbuchung";

            PdfPage page = document.AddPage();
            XGraphics gfx = XGraphics.FromPdfPage(page);

            XFont titleFont = new XFont("OpenSans", 30);
            XFont textFont = new XFont("OpenSans", 20);

            gfx.DrawImage(logo, 40, 20, 100, 100);
            gfx.DrawString("Flugbuchung", titleFont, XBrushes.Black, new XPoint(200, 80));
            gfx.DrawString($"Buchung-ID: {buchungId}", textFont, XBrushes.Black, new XPoint(40, 160));
            gfx.DrawString($"Flug-Nr.: {flugNr}", textFont, XBrushes.Black, new XPoint(40, 200));
            gfx.DrawString($"Von: {von}", textFont, XBrushes.Black, new XPoint(40, 240));
            gfx.DrawString($"Nach: {nach}", textFont, XBrushes.Black, new XPoint(40, 280));
            gfx.DrawString($"Datum: {datum:dd.MM.yyyy}", textFont, XBrushes.Black, new XPoint(40, 320));
            gfx.DrawString($"Status: {status}", textFont, XBrushes.Black, new XPoint(40, 360));

            string filename = $"Flugbuchung_{buchungId}.pdf";
            document.Save(filename);

            MessageBox.Show($"PDF erfolgreich erstellt: {filename}");
        }

        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());
        private void OpenReservierungSuche_Click(object sender, RoutedEventArgs e) => NavigationService.Navigate(new ReservierungssuchePage());

        
    }
}