using Microsoft.Win32;
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using Word = Microsoft.Office.Interop.Word;

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


        #region Для тестов
        public bool AddChangePhoto(int a)
        {
            bool tf = false;
            DB.Iduser = a;

            string imageLoc;
            OpenFileDialog dld = new OpenFileDialog();
            dld.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|JPEG Files (*.jpeg)|*.jpeg";
            if (dld.ShowDialog() == true)
            {
                imageLoc = dld.FileName;
                imgProfile.Source = new BitmapImage(new Uri(imageLoc));
                FileStream fs = new FileStream(imageLoc, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);

                image = br.ReadBytes((int)fs.Length);
                var img = DB.GetContext().Users.Where(x => x.IDUsers == DB.Iduser).FirstOrDefault();
                img.Image = image;
                DB.GetContext().SaveChanges();

                tf = true;
            }
            if (imgProfile.Source != null) btnAddPhoto.Content = "Изменить фото";

            return tf;
        }

        public bool PlusBalance(string a, string b, string c, string d, string balance, int idcard)
        {
            card1.Text = a;
            card2.Text = b;
            card3.Text = c;
            card4.Text = d;
            txtPlusBalabce.Text = balance;
            bool tf = false;

            var bal = DB.GetContext().Card.Where(x => x.IDCard == idcard).FirstOrDefault();
            if (txtPlusBalabce.Text != "" && card1.Text.Length == 4 && card2.Text.Length == 4 && card3.Text.Length == 4 && card4.Text.Length == 4)
            {
                try //типа проверка на введенные значения
                {
                    if (bal.Balance == null) bal.Balance = 0;
                    bal.Balance += Convert.ToDecimal(txtPlusBalabce.Text);
                    DB.GetContext().SaveChanges();
                    gridPlusBalance.Visibility = Visibility.Hidden;
                    MessageBox.Show("Успешно", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                    tf = true;
                }
                catch
                {
                    MessageBox.Show("Ошибка, проверьте введенные данные", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else MessageBox.Show("Проверьте заполнение полей", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);

            return tf;
        }


        public decimal AddOldAttractionSumm(int idattraction, int iduser)
        {
            try
            {
                if (DB.GetContext().Attraction.Where(x => x.IDAttraction == idattraction && x.FKStatusAttraction == 2).FirstOrDefault() != null) return 0;

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

                else
                {
                    var attr = DB.GetContext().Attraction.Where(x => x.IDAttraction == idattraction).FirstOrDefault();

                    Tickets tickets = new Tickets
                    {
                        FKUser = 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 == iduser && x.FKStatusPuy == 2).ToList();

                    return Convert.ToDecimal(attr.PriceOld);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return 0;
        }


        public decimal AddBabyAttractionSumm(int idattraction, int iduser)
        {

            try
            {
                if (DB.GetContext().Attraction.Where(x => x.IDAttraction == idattraction && x.FKStatusAttraction == 2).FirstOrDefault() != null) return 0;

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

                else
                {
                    var attr = DB.GetContext().Attraction.Where(x => x.IDAttraction == idattraction).FirstOrDefault();

                    Tickets tickets = new Tickets
                    {
                        FKUser = 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 == iduser && x.FKStatusPuy == 2).ToList();

                    return Convert.ToDecimal(attr.PriceBaby);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            return 0;
        }

        public bool TicketsMinus(int quantity)
        {
            bool tf = false;

            if (quantity == 1) MessageBox.Show("Количество не может быть меньше 1", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            else
            {
                quantity -= 1;
                tf = true;
            }
            DB.GetContext().SaveChanges();
            listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();
            decimal summ = 0;
            summ = Summ(summ);

            return tf;
        }
        public bool TicketsPlus(int quantity)
        {
            bool tf = false;

            if (quantity == 30) MessageBox.Show("Превышено количество билетов", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            else
            {
                quantity += 1;
                tf = true;
            }
            DB.GetContext().SaveChanges();
            listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();
            decimal summ = 0;
            summ = Summ(summ);

            return tf;
        }

        public int TicketsMinusInt(int quantity)
        {
            if (quantity == 1) MessageBox.Show("Количество не может быть меньше 1", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            else 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(summ);

            return quantity;
        }

        public int TicketsPlusInt(int quantity)
        {
            if (quantity == 30) MessageBox.Show("Превышено количество билетов", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            else 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(summ);

            return quantity;
        }


        #endregion



        public void Update() //функция для обновления информации о пользователе
        {
            try
            {
                //фио
                var fio = DB.GetContext().Users.FirstOrDefault(x => x.IDUsers == DB.Iduser);
                txtNameProfile.Text = fio.LastName + " " + fio.FirstName + " " + fio.MiddleName;

                //выводим баланс карты
                DB.Idcard = fio.FKCard;
                txtBalanceProfile.Text = "Баланс карты: " + String.Format("{0:0.00}", Convert.ToDecimal(DB.GetContext().Card.FirstOrDefault(x => x.IDCard == fio.FKCard).Balance));

                //выводим картинку из бд
                if (fio.Image != null)
                {
                    image = fio.Image;
                    MemoryStream ms = new MemoryStream(image);
                    imgProfile.Source = BitmapFrame.Create(ms);
                }
                if (imgProfile.Source != null) btnAddPhoto.Content = "Изменить фото";

                //История платежей
                datagridHistoryProfile.ItemsSource = DB.GetContext().History.Where(x => x.FKUser == DB.Iduser).ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            try
            {
                listAllAttraction.ItemsSource = DB.GetContext().Attraction.Where(x => x.FKStatusAttraction != 2).ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }

            //Update();
        }

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

        private void ViewAllAttraction(object sender, MouseButtonEventArgs e) //просмотр каждого аттракцинона для выбора нужного
        {
            try
            {
                if (listAllAttraction.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;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnBackAttraction(object sender, RoutedEventArgs e) //кнопка Назад после просмотра
        {
            stackAttraction.Visibility = Visibility.Hidden;
        }

        #endregion

        #region Раздел Билеты

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

            AddOldAttractionSumm(idattraction, DB.Iduser);
        }

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

        public decimal 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);

            return summ;
        }

        private void btnTickets(object sender, RoutedEventArgs e) //вывод добавленных билетов
        {
            stackAttraction.Visibility = Visibility.Hidden;
            listAllAttraction.Visibility = Visibility.Hidden;
            gridProfile.Visibility = Visibility.Hidden;
            gridPlusBalance.Visibility = Visibility.Hidden;
            gridTickets.Visibility = Visibility.Visible;
            try
            {
                listTickets.ItemsSource = DB.GetContext().Tickets.Where(x => x.FKUser == DB.Iduser && x.FKStatusPuy == 2).ToList();
                decimal summ = 0;
                summ = Summ(summ);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnTicketsMinus(object sender, RoutedEventArgs e) //уменьшение количества билетов
        {
            try
            {
                if ((sender as Button).DataContext is Tickets tickets)
                {
                    TicketsMinus(tickets.Quantity);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnTicketsPlus(object sender, RoutedEventArgs e) //увеличение количества билетов
        {
            try
            {
                if ((sender as Button).DataContext is Tickets tickets)
                {
                    TicketsPlus(tickets.Quantity);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void BtnDeleteTickets(object sender, RoutedEventArgs e) //удаление добавленных билетов
        {
            try
            {
                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);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

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

                else
                {
                    summ = 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
                    {
                        #region ЧЕК
                        SaveFileDialog saveFileDialog = new SaveFileDialog();
                        saveFileDialog.Title = "Выберите место для сохранения чека";
                        saveFileDialog.FileName = "Чек за " + DateTime.Now.ToShortDateString() + " - PDF";
                        saveFileDialog.Filter = "PDF Files |*.pdf";
                        if (saveFileDialog.ShowDialog() == true)
                        {
                            var application = new Word.Application();
                            Word.Document document = application.Documents.Add();

                            Word.Paragraph paragraph = document.Paragraphs.Add();
                            Word.Range cellrange = paragraph.Range;
                            Word.InlineShape inlineShape = cellrange.InlineShapes.AddPicture(@"C:\Users\polin\OneDrive\Рабочий стол\mateo\mateo\image\logocheck.png");
                            inlineShape.Width = 400;
                            inlineShape.Height = 100;
                            paragraph.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            cellrange.InsertParagraphAfter();

                            Word.Paragraph paragraph2 = document.Paragraphs.Add();
                            Word.Range range2 = paragraph2.Range;
                            range2.Text = "Чек №" + (DB.GetContext().History.OrderByDescending(x => x.IDHistory).FirstOrDefault().IDHistory + 1).ToString();
                            paragraph2.set_Style("Заголовок");
                            paragraph2.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            range2.Font.Size = 18;
                            range2.InsertParagraphAfter();

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

                            Word.Paragraph tableparagraph = document.Paragraphs.Add();
                            Word.Range tablerange = tableparagraph.Range;
                            Word.Table paymentstable = document.Tables.Add(tablerange, report.Count() + 2, 2);
                            paymentstable.Borders.InsideLineStyle = paymentstable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;

                            paymentstable.PreferredWidth = 400;

                            paymentstable.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter;
                            paymentstable.Borders.OutsideColor = Word.WdColor.wdColorWhite;
                            paymentstable.Borders.InsideColor = Word.WdColor.wdColorWhite;

                            Word.Range cellRange;

                            cellRange = paymentstable.Cell(1, 1).Range;
                            cellRange.Columns.SetWidth(application.CentimetersToPoints(10f), Word.WdRulerStyle.wdAdjustNone);

                            cellRange = paymentstable.Cell(1, 2).Range;
                            cellRange.Columns.SetWidth(application.CentimetersToPoints(5f), Word.WdRulerStyle.wdAdjustNone);
                            cellRange.Text = "Дата: " + DateTime.Now;
                            paymentstable.Cell(1, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                            range2.Font.Size = 16;

                            for (int i = 0; i < report.Count(); i++)
                            {
                                var orders = report[i];
                                var type = DB.GetContext().TypeTickets.Where(x => x.IDTypeTickets == orders.FKTypeTickets).FirstOrDefault();

                                cellRange = paymentstable.Cell(i + 2, 1).Range;
                                cellRange.Text = orders.Attraction.NameAttraction + " (" + type.TypeTickets1 + ")" + " x" + orders.Quantity;
                                cellRange.Font.Size = 12;

                                cellRange = paymentstable.Cell(i + 2, 2).Range;
                                paymentstable.Cell(i + 2, 2).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
                                cellRange.Font.Size = 12;
                                decimal price = orders.Summ * orders.Quantity;
                                cellRange.Text = String.Format("{0:0.00}", price).ToString() + " руб.";
                            }


                            cellRange = paymentstable.Cell(report.Count() + 3, 1).Range;
                            cellRange.Text = "Итого: " + String.Format("{0:0.00}", summ).ToString() + " руб.";
                            cellRange.set_Style("Заголовок");
                            cellRange.Bold = 1;
                            paymentstable.Cell(report.Count() + 3, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;
                            cellRange.Font.Size = 20;

                            //№ карты
                            cellRange.InsertParagraphAfter();
                            tablerange.InsertParagraphAfter();


                            Word.Paragraph paragraph3 = document.Paragraphs.Add();
                            Word.Range range3 = paragraph3.Range;
                            range3.Text = "-------------------------------------------------------------";
                            paragraph3.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            range3.Font.Size = 18;
                            range3.InsertParagraphAfter();


                            Word.Paragraph paragraph4 = document.Paragraphs.Add();
                            Word.Range range4 = paragraph4.Range;
                            range4.Text = "№ карты лояльности: " + balance.NumberCard;
                            paragraph4.set_Style("Заголовок");
                            paragraph4.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
                            range4.Font.Size = 14;
                            range4.InsertParagraphAfter();

                            document.SaveAs2(saveFileDialog.FileName, Word.WdExportFormat.wdExportFormatPDF);
                        }
                        #endregion

                        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();

                        summ = Summ(summ);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        #endregion

        #region Раздел Профиль
        private void btnProfileClick(object sender, RoutedEventArgs e)
        {
            stackAttraction.Visibility = Visibility.Hidden;
            listAllAttraction.Visibility = Visibility.Hidden;
            gridTickets.Visibility = Visibility.Hidden;
            gridProfile.Visibility = Visibility.Visible;
            Update();
        }

        private void BtnAddPhoto(object sender, RoutedEventArgs e) //добавить/изменить фото пользователя в разделе Профиль и в бд
        {
            try
            {
                AddChangePhoto(DB.Iduser);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Update();
        }

        private void BtnDeletePhoto(object sender, RoutedEventArgs e) //удаление фото в тч из бд
        {
            try
            {
                var fio = DB.GetContext().Users.FirstOrDefault(x => x.IDUsers == DB.Iduser);
                fio.Image = null;
                DB.GetContext().SaveChanges();
                imgProfile.Source = null;
                btnAddPhoto.Content = "добавить фото";
                Update();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
        private void BtbBalance(object sender, RoutedEventArgs e) //кнопка Пополнить баланс, открываем форму для пополнения баланса
        {
            txtPlusBalabce.Text = "";
            gridPlusBalance.Visibility = Visibility.Visible;
        }

        private void BtbPlusBalance(object sender, RoutedEventArgs e) //пополняем баланс
        {
            PlusBalance(card1.Text, card2.Text, card3.Text, card4.Text, txtPlusBalabce.Text, DB.Idcard);
            Update();
        }

        private void txtchangedCard(object sender, TextChangedEventArgs e)
        {
            if (card1.Text.Length == 4) card2.Focus();
            if (card2.Text.Length == 4) card3.Focus();
            if (card3.Text.Length == 4) card4.Focus();

            if (sender is TextBox textBox)
            {
                textBox.Text = new string
               (textBox.Text.Where(ch => (ch >= '0' && ch <= '9')).ToArray());
            }
        }

        private void BtnCancelBalance(object sender, RoutedEventArgs e)
        {
            gridPlusBalance.Visibility = Visibility.Hidden;
            Update();
        }

        #endregion

        #region Прочее
        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();
        }

        //#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

        #endregion
    }
}
