using System;
using System.Data;
using System.Windows.Forms;
using Npgsql;

namespace ProviderApp
{
    public partial class DashboardForm : UserControl
    {
        public DashboardForm()
        {
            InitializeComponent();
            this.Load += DashboardForm_Load;
            LoadDashboardData();
        }

        private void DashboardForm_Load(object sender, EventArgs e)
        {
            LoadDashboardData();
        }

        public void RefreshData()
        {
            LoadDashboardData();
        }

        private void LoadDashboardData()
        {
            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    // 1. Количество клиентов
                    string sqlClients = "SELECT COUNT(*) FROM sizov_ev.clients";
                    using (var cmd = new NpgsqlCommand(sqlClients, conn))
                    {
                        int clientsCount = Convert.ToInt32(cmd.ExecuteScalar());
                        lblClientsCount.Text = clientsCount.ToString();
                    }

                    // 2. Количество активных договоров
                    string sqlActiveContracts = "SELECT COUNT(*) FROM sizov_ev.contracts WHERE status = 'active'";
                    using (var cmd = new NpgsqlCommand(sqlActiveContracts, conn))
                    {
                        int activeContracts = Convert.ToInt32(cmd.ExecuteScalar());
                        lblContractsCount.Text = activeContracts.ToString();
                    }

                    // 3. Общая выручка (сумма всех платежей)
                    string sqlRevenue = "SELECT COALESCE(SUM(amount), 0) FROM sizov_ev.payments";
                    using (var cmd = new NpgsqlCommand(sqlRevenue, conn))
                    {
                        decimal revenue = Convert.ToDecimal(cmd.ExecuteScalar());
                        lblRevenueAmount.Text = $"{revenue:N0} ₽";
                    }

                    // 4. Самый популярный тариф
                    string sqlPopularTariff = @"
                        SELECT 
                            t.name,
                            COUNT(c.contract_id) as cnt
                        FROM sizov_ev.tariffs t
                        LEFT JOIN sizov_ev.contracts c ON t.tariff_id = c.tariff_id
                        GROUP BY t.tariff_id, t.name
                        ORDER BY cnt DESC
                        LIMIT 1";

                    using (var cmd = new NpgsqlCommand(sqlPopularTariff, conn))
                    {
                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                string tariffName = reader["name"].ToString();
                                int count = Convert.ToInt32(reader["cnt"]);
                                lblPopularTariffName.Text = $"{tariffName} ({count} подкл.)";
                            }
                            else
                            {
                                lblPopularTariffName.Text = "Нет данных";
                            }
                        }
                    }

                    // Обновляем приветствие с именем пользователя
                    if (AuthHelper.CurrentUser.IsAuthenticated)
                    {
                        lblWelcome.Text = $"Добро пожаловать, {AuthHelper.CurrentUser.FullName}!";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки данных: {ex.Message}");
                lblClientsCount.Text = "Ошибка";
                lblContractsCount.Text = "Ошибка";
                lblRevenueAmount.Text = "Ошибка";
                lblPopularTariffName.Text = "Ошибка";
            }
        }
    }
}