using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace mateo
{
    public partial class MainWindow : Window
    {
        byte[] image; //очищать!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        int idattraction = 0;


        public MainWindow()
        {
            InitializeComponent();
            listAttraction.ItemsSource = DB.GetContext().Attraction.Where(x => x.FKStatusAttraction != 2).ToList();

        }


        #region раздел Услуги
        private void btnUslugiClick(object sender, RoutedEventArgs e)
        {
            gridTickets.Visibility = Visibility.Hidden;
        }

        #endregion





        private void btnProfileClick(object sender, RoutedEventArgs e)
        {
            gridTickets.Visibility = Visibility.Hidden;

            Profile profile = new Profile();
            profile.Show();
            this.Close();
        }

        private void btnBronClick(object sender, RoutedEventArgs e)
        {
            border_bron.Visibility = Visibility.Visible;
        }

        private void btn_pay_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btn_first_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btn_cancel_Click(object sender, RoutedEventArgs e)
        {
            border_bron.Visibility = Visibility.Hidden;
        }

        #region соцсети
        private void btn_whatsapp(object sender, RoutedEventArgs e)
        {

        }

        private void btn_gmail(object sender, RoutedEventArgs e)
        {

        }

        private void btn_vk(object sender, RoutedEventArgs e)
        {

        }
        private void btn_insta(object sender, RoutedEventArgs e)
        {

        }
        #endregion
        private void btnLogout(object sender, RoutedEventArgs e)
        {
            First first = new First();
            first.Show();
            this.Close();
        }
        private void btnExit(object sender, RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void ViewAttraction(object sender, MouseButtonEventArgs e)
        {
            if (listAttraction.SelectedItem is Attraction attraction)
            {
                stackPriceOld.Visibility = Visibility.Visible;
                stackPriceBaby.Visibility = Visibility.Visible;
                stackAttraction.Visibility = Visibility.Visible;
                txtNameAttraction.Text = attraction.NameAttraction;
                image = attraction.ImageAttraction;
                MemoryStream ms = new MemoryStream(image);
                imgAttraction.Source = BitmapFrame.Create(ms);
                txtDescriptionAttraction.Text = attraction.Description;
                txtPriceOld.Text = String.Format("Взрослый: {0:0.00}", attraction.PriceOld);
                txtPriceBaby.Text = String.Format("Детский: {0:0.00}", attraction.PriceBaby);
                if (attraction.PriceOld == 0 || attraction.PriceOld == null) stackPriceOld.Visibility = Visibility.Hidden;
                if (attraction.PriceBaby == 0 || attraction.PriceBaby == null) stackPriceBaby.Visibility = Visibility.Hidden;
            }
        }

        private void btnBackAttraction(object sender, RoutedEventArgs e)
        {
            stackAttraction.Visibility = Visibility.Hidden;
        }


        public void Summ(decimal summ)
        {
            try
            {
                summ = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).Sum(x => x.Quantity * x.Summ);
            }
            catch
            {
                summ = 0;
            }
            if (summ == 0) txtSumm.Text = "Сумма: 0.00";

            else txtSumm.Text = String.Format("Сумма: {0:0,00}", summ);
        }

        private void btnTickets(object sender, RoutedEventArgs e)
        {
            gridTickets.Visibility = Visibility.Visible;
            listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();
            decimal summ = 0;
            Summ(summ);
        }

        private void BtnAddOldAttraction(object sender, RoutedEventArgs e)
        {

            //записываем id аттракциона по названию
            var attr = DB.GetContext().Attraction.Where(x => x.NameAttraction == txtNameAttraction.Text).FirstOrDefault();
            idattraction = attr.IDAttraction;

            if (DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKAttraction == idattraction && x.FKStatusPuy == 2&&x.FKTypeTickets==1).FirstOrDefault() != null)
                MessageBox.Show("Вы уже добавили такой билет, если хотите изменить количество, перейдите пожалуйста в раздел \"Билеты\"", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            else
            {

                Tickets tickets = new Tickets
                {
                    FKUser = DB.Iduser,
                    FKAttraction = idattraction,
                    FKTypeTickets = 1,
                    FKStatusPuy = 2,
                    Quantity = 1,
                    Summ = Convert.ToDecimal(attr.PriceOld),
                    Date = DateTime.Now
                };
                DB.GetContext().Tickets.Add(tickets);
                DB.GetContext().SaveChanges();
                MessageBox.Show("Билет добавлен в раздел \"Билеты\"", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();

            }
        }

        private void BtnAddBabyAttraction(object sender, RoutedEventArgs e)
        {
            var attr = DB.GetContext().Attraction.Where(x => x.NameAttraction == txtNameAttraction.Text).FirstOrDefault();
            //записываем id аттракциона по названию
            idattraction = attr.IDAttraction;

            if (DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKAttraction == idattraction && x.FKStatusPuy == 2 && x.FKTypeTickets == 2).FirstOrDefault() != null)
                MessageBox.Show("Вы уже добавили такой билет, если хотите изменить количество, перейдите пожалуйста в раздел \"Билеты\"", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            else
            {
                Tickets tickets = new Tickets
                {
                    FKUser = DB.Iduser,
                    FKAttraction = idattraction,
                    FKTypeTickets = 2,
                    FKStatusPuy = 2,
                    Quantity = 1,
                    Summ = Convert.ToDecimal(attr.PriceBaby),
                    Date = DateTime.Now
                };
                DB.GetContext().Tickets.Add(tickets);
                DB.GetContext().SaveChanges();
                MessageBox.Show("Билет добавлен в раздел \"Билеты\"", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser==DB.Iduser&&x.FKStatusPuy==2).ToList();

               
            }
        }

        private void BtnDeleteTickets(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).DataContext is Tickets tickets)
            {
                decimal summ = 0;
                DB.GetContext().Tickets.Remove(tickets);
                DB.GetContext().SaveChanges();
                listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();
                try
                {
                    summ = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).Sum(x => x.Quantity * x.Summ);
                }
                catch
                {
                    summ = 0;                    
                }
                if (summ == 0) txtSumm.Text = "Сумма: 0.00";

                else txtSumm.Text = String.Format("Сумма: {0:0,00}", summ);
            }
        }

        private void BtnTicketsMinus(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).DataContext is Tickets tickets)
            {
                if (tickets.Quantity == 1) MessageBox.Show("Количество не может быть меньше 1", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                else tickets.Quantity -= 1;
                DB.GetContext().SaveChanges();
                listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();
                decimal summ = 0;
                Summ(summ);

            }
        }

        private void BtnTicketsPlus(object sender, RoutedEventArgs e)
        {
            if ((sender as Button).DataContext is Tickets tickets)
            {
                if (tickets.Quantity == 30) MessageBox.Show("Превышено количество билетов", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                else tickets.Quantity += 1;
                DB.GetContext().SaveChanges();
                listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();
                decimal summ = 0;
                Summ(summ);

            }
        }

        private void BtnPuyAll(object sender, RoutedEventArgs e)
        {
            if (DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).FirstOrDefault() == null)
            {
                MessageBox.Show("Вы не выбрали билет, перейдите в раздел \"Услуги\", чтобы выбрать", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }

            else
            {
                decimal summ = 0;
                Summ(summ);

                var card = DB.GetContext().Users.Where(x => x.IDUsers == DB.Iduser).FirstOrDefault().FKCard;
                var balance = DB.GetContext().Card.Where(x => x.IDCard == card).FirstOrDefault();

                if (balance.Balance < summ)
                {
                    MessageBox.Show("У Вас недостаточно средств, пополните баланс и повторите попытку", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                else
                {
                    balance.Balance -= Convert.ToDecimal(summ);

                    var tickets = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();
                    tickets.ForEach(x => x.FKStatusPuy = 1);


                    History history = new History()
                    {
                        FKUser = DB.Iduser,
                        DateTime = DateTime.Now,
                        Summ = summ
                    };

                    DB.GetContext().History.Add(history);
                    DB.GetContext().SaveChanges();
                    MessageBox.Show("Оплата прошла успешно", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);

                    listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();

                    try
                    {
                        summ = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).Sum(x => x.Quantity * x.Summ);
                    }
                    catch
                    {
                        summ = 0;
                    }
                    if (summ == 0) txtSumm.Text = "Сумма: 0.00";

                    else txtSumm.Text = String.Format("Сумма: {0:0,00}", summ);
                };
            }
        }
    }
}
