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

namespace ProviderApp
{
    public partial class ContractsForm : UserControl
    {
        private DataTable contractsTable;

        public ContractsForm()
        {
            InitializeComponent();
            this.Load += ContractsForm_Load;
            btnExecute.Click += BtnExecute_Click;
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            btnExport.Click += BtnExport_Click;
            StyleDataGridView();
        }

        private void StyleDataGridView()
        {
            dgvResult.ColumnHeadersDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(230, 92, 0);
            dgvResult.ColumnHeadersDefaultCellStyle.ForeColor = System.Drawing.Color.White;
            dgvResult.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Bold);
            dgvResult.DefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(40, 40, 40);
            dgvResult.DefaultCellStyle.ForeColor = System.Drawing.Color.White;
            dgvResult.AlternatingRowsDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(45, 45, 45);
            dgvResult.EnableHeadersVisualStyles = false;
        }

        private void ContractsForm_Load(object sender, EventArgs e)
        {
            dtpFrom.Value = new DateTime(2024, 1, 1);
            dtpTo.Value = new DateTime(2024, 12, 31);
            LoadContracts();

            btnAdd.Visible = AuthHelper.CurrentUser.IsManager;
            btnEdit.Visible = AuthHelper.CurrentUser.IsManager;
            btnDelete.Visible = AuthHelper.CurrentUser.IsAdmin;
            btnExport.Visible = AuthHelper.CurrentUser.IsManager;
        }

        public void RefreshData()
        {
            LoadContracts();
        }

        private void BtnExecute_Click(object sender, EventArgs e)
        {
            LoadContracts();
        }

        private void LoadContracts()
        {
            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    DateTime fromDate = dtpFrom.Value.Date;
                    DateTime toDate = dtpTo.Value.Date.AddDays(1).AddSeconds(-1);

                    // РАСЧЁТНЫЙ АТРИБУТ
                    string sql = @"
                        SELECT 
                            c.contract_id,
                            c.client_name,
                            c.tariff_name,
                            c.monthly_price,
                            c.employee_name,
                            c.sign_date,
                            c.status,
                            COALESCE((
                                SELECT SUM(p.amount) 
                                FROM sizov_ev.payments p 
                                WHERE p.contract_id = c.contract_id
                            ), 0) AS total_paid
                        FROM sizov_ev.active_contracts c
                        WHERE c.sign_date BETWEEN @date_from AND @date_to
                        ORDER BY c.sign_date DESC";

                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@date_from", fromDate);
                        cmd.Parameters.AddWithValue("@date_to", toDate);

                        DataTable dt = new DataTable();
                        using (var da = new NpgsqlDataAdapter(cmd))
                        {
                            da.Fill(dt);
                        }
                        contractsTable = dt;
                        dgvResult.DataSource = contractsTable;

                        if (dgvResult.Columns["contract_id"] != null)
                            dgvResult.Columns["contract_id"].HeaderText = "ID";
                        if (dgvResult.Columns["client_name"] != null)
                            dgvResult.Columns["client_name"].HeaderText = "Клиент";
                        if (dgvResult.Columns["tariff_name"] != null)
                            dgvResult.Columns["tariff_name"].HeaderText = "Тариф";
                        if (dgvResult.Columns["monthly_price"] != null)
                            dgvResult.Columns["monthly_price"].HeaderText = "Цена, руб";
                        if (dgvResult.Columns["employee_name"] != null)
                            dgvResult.Columns["employee_name"].HeaderText = "Сотрудник";
                        if (dgvResult.Columns["sign_date"] != null)
                            dgvResult.Columns["sign_date"].HeaderText = "Дата";
                        if (dgvResult.Columns["status"] != null)
                            dgvResult.Columns["status"].HeaderText = "Статус";
                        if (dgvResult.Columns["total_paid"] != null)
                            dgvResult.Columns["total_paid"].HeaderText = "Оплачено, руб";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки: {ex.Message}");
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            if (!AuthHelper.CheckPermission("manager")) return;
            AuthHelper.LogAction("Попытка добавления договора", "contracts");

            using (var form = new AddEditContractForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    AuthHelper.LogAction("Договор добавлен", "contracts");
                    LoadContracts();
                }
            }
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (!AuthHelper.CheckPermission("manager")) return;

            if (dgvResult.CurrentRow == null)
            {
                MessageBox.Show("Выберите договор.");
                return;
            }
            int contractId = Convert.ToInt32(dgvResult.CurrentRow.Cells["contract_id"].Value);
            AuthHelper.LogAction($"Попытка редактирования договора ID={contractId}", "contracts", contractId);

            using (var form = new AddEditContractForm(contractId))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    AuthHelper.LogAction($"Договор ID={contractId} отредактирован", "contracts", contractId);
                    LoadContracts();
                }
            }
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (!AuthHelper.CheckPermission("admin")) return;

            if (dgvResult.CurrentRow == null)
            {
                MessageBox.Show("Выберите договор.");
                return;
            }
            if (MessageBox.Show("Удалить договор?", "Подтверждение", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                int contractId = Convert.ToInt32(dgvResult.CurrentRow.Cells["contract_id"].Value);
                try
                {
                    using (var conn = DBConnection.GetConnection())
                    {
                        string sql = "DELETE FROM sizov_ev.contracts WHERE contract_id = @id";
                        using (var cmd = new NpgsqlCommand(sql, conn))
                        {
                            cmd.Parameters.AddWithValue("@id", contractId);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    AuthHelper.LogAction($"Договор ID={contractId} удалён", "contracts", contractId);
                    LoadContracts();
                    MessageBox.Show("Договор удалён.");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Ошибка удаления: {ex.Message}");
                }
            }
        }

        private void BtnExport_Click(object sender, EventArgs e)
        {
            if (!AuthHelper.CheckPermission("manager")) return;

            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    DateTime fromDate = dtpFrom.Value.Date;
                    DateTime toDate = dtpTo.Value.Date.AddDays(1).AddSeconds(-1);

                    string sql = @"
                        SELECT 
                            c.contract_id as ""ID договора"",
                            c.client_name as ""Клиент"",
                            c.tariff_name as ""Тариф"",
                            c.monthly_price as ""Цена, руб"",
                            c.employee_name as ""Сотрудник"",
                            c.sign_date as ""Дата подписания"",
                            c.status as ""Статус"",
                            COALESCE((SELECT SUM(p.amount) FROM sizov_ev.payments p WHERE p.contract_id = c.contract_id), 0) as ""Оплачено, руб""
                        FROM sizov_ev.active_contracts c
                        WHERE c.sign_date BETWEEN @date_from AND @date_to
                        ORDER BY c.sign_date DESC";

                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@date_from", fromDate);
                        cmd.Parameters.AddWithValue("@date_to", toDate);

                        DataTable dt = new DataTable();
                        using (var da = new NpgsqlDataAdapter(cmd))
                        {
                            da.Fill(dt);
                        }
                        AuthHelper.LogAction("Экспорт договоров в CSV", "contracts");
                        CsvExporter.ExportToCsv(dt, $"Договоры_{DateTime.Now:yyyyMMdd_HHmmss}.csv");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка экспорта: {ex.Message}");
            }
        }
    }
}