using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using RestaurantApp.DAL;
using RestaurantApp.Models;

namespace RestaurantApp
{
    public partial class PaymentForm : Form
    {
        private OrderRepository repo = new OrderRepository();
        private ClientRepository clientRepo = new ClientRepository();

        private int orderId;
        private decimal totalAmount;
        private int? clientId;
        private int availableBonus = 0;

        public PaymentForm(int orderId, decimal totalAmount)
        {
            InitializeComponent();
            this.orderId = orderId;
            this.totalAmount = totalAmount;

            LoadClientInfo();
            LoadData();

            cmbMethod.SelectedIndex = 0;
            cmbMethod.SelectedIndexChanged += (s, e) => UpdateFinalAmount();
            numBonus.ValueChanged += (s, e) => UpdateFinalAmount();

            btnPay.Click += BtnPay_Click;
            btnCancel.Click += (s, e) => DialogResult = DialogResult.Cancel;
        }

        private void LoadClientInfo()
        {
            // Получаем клиента из заказа
            var orders = repo.GetAll("", "");
            var order = orders.FirstOrDefault(o => o.OrderId == orderId);

            if (order != null && order.ClientId.HasValue)
            {
                clientId = order.ClientId;
                var client = clientRepo.GetById(clientId.Value);
                if (client != null)
                {
                    availableBonus = client.BonusPoints;
                    lblBonusInfo.Text = $"(доступно: {availableBonus})";
                    numBonus.Maximum = Math.Min(availableBonus, (int)(totalAmount / 10)); // 1 бонус = 10 руб
                }
                else
                {
                    lblBonusInfo.Text = "(нет бонусов)";
                    numBonus.Enabled = false;
                }
            }
            else
            {
                lblBonusInfo.Text = "(без клиента)";
                numBonus.Enabled = false;
            }
        }

        private void LoadData()
        {
            lblOrderIdValue.Text = orderId.ToString();
            lblAmountValue.Text = $"{totalAmount:N2} ₽";
            UpdateFinalAmount();
        }

        private void UpdateFinalAmount()
        {
            decimal bonusDiscount = numBonus.Value * 10; // 1 бонус = 10 рублей
            decimal finalAmount = totalAmount - bonusDiscount;
            if (finalAmount < 0) finalAmount = 0;

            lblFinalAmountValue.Text = $"{finalAmount:N2} ₽";
        }

        private void BtnPay_Click(object sender, EventArgs e)
        {
            decimal bonusDiscount = numBonus.Value * 10;
            decimal finalAmount = totalAmount - bonusDiscount;
            if (finalAmount < 0) finalAmount = 0;

            if (finalAmount <= 0 && cmbMethod.Text != "bonus")
            {
                MessageBox.Show("Сумма к оплате 0. Выберите оплату бонусами");
                return;
            }

            try
            {
                repo.AddPayment(orderId, finalAmount, cmbMethod.Text);

                // Обновляем статус заказа
                repo.UpdateOrderStatus(orderId, "closed");

                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка оплаты: {ex.Message}");
            }
        }
    }
}