using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NeshinaPolina2111
{
    public partial class PartnerDiscountsForm : Form
    {
        public PartnerDiscountsForm (int partnerId)
        {
            InitializeComponent();
            this.partnerId = partnerId;
            MessageBox.Show($"ID партнёра в форме: {partnerId}");

            LoadData();
        }
        public int partnerId {  get; set; }
        private void PartnerDiscountsForm_Load(object sender, EventArgs e)
        {

        }

       
        private void LoadData()
        {
            try
            {
                decimal totalSales = GetTotalSales(partnerId);
                decimal currentDiscount = GetDiscountBySales(totalSales);

                lblTotalSales.Text = $"Общий объём продаж: {totalSales:F2} ₽";
                lblCurrentDiscount.Text = $"Текущая скидка: {currentDiscount:F1}%";

                string nextLevel = GetNextDiscountLevel(totalSales);
                lblNextLevel.Text = $"Следующий уровень: {nextLevel}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки данных: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private decimal GetTotalSales(int partnerId)
        {
            string query = "SELECT COALESCE(SUM(SaleAmount), 0) FROM PartnerSales WHERE idAuthorization = @partnerId";
            var conn = DB.GetInstance().GetConnection();

            using (var cmd = new MySqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@partnerId", partnerId);
                return Convert.ToDecimal(cmd.ExecuteScalar());
            }
        }
        private decimal GetDiscountBySales(decimal totalSales)
        {
            string query = @"
                SELECT DiscountPercent 
                FROM Discounts 
                WHERE MinSales <= @totalSales 
                ORDER BY MinSales DESC 
                LIMIT 1";

            var conn = DB.GetInstance().GetConnection();

            using (var cmd = new MySqlCommand(query, conn))
            {
                cmd.Parameters.AddWithValue("@totalSales", totalSales);
                var result = cmd.ExecuteScalar();
                return result != null ? Convert.ToDecimal(result) : 0;
            }
        }



        private string GetNextDiscountLevel(decimal currentSales)
        {
            string query = @"
                SELECT MinSales, DiscountPercent 
                FROM Discounts 
                WHERE MinSales > @currentSales 
                ORDER BY MinSales ASC 
                LIMIT 1";

            var conn = DB.GetInstance().GetConnection();

            using (var cmd = new MySqlCommand(query, conn))
            {

                cmd.Parameters.AddWithValue("@currentSales", currentSales);
                using (var reader = cmd.ExecuteReader())
                {
                    if (reader.Read())

                    {
                        decimal minSales = Convert.ToDecimal(reader["MinSales"]);
                        decimal discount = Convert.ToDecimal(reader["DiscountPercent"]);
                        return $"{minSales:F2} ₽ → {discount:F1}%";
                    }

                    else
                    {
                        return "Вы достигли максимального уровня скидок!";
                    }
                }
            }


        }

        private void btnClose_Click(object sender, EventArgs e)
        {

        }
    }
}
