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

namespace ProviderApp
{
    public partial class ClientsForm : UserControl
    {
        private DataTable clientsTable;

        public ClientsForm()
        {
            InitializeComponent();
            this.Load += ClientsForm_Load;
            btnAdd.Click += BtnAdd_Click;
            btnEdit.Click += BtnEdit_Click;
            btnDelete.Click += BtnDelete_Click;
            btnExport.Click += BtnExport_Click;
            StyleDataGridView();
        }

        private void StyleDataGridView()
        {
            dgvClients.ColumnHeadersDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(230, 92, 0);
            dgvClients.ColumnHeadersDefaultCellStyle.ForeColor = System.Drawing.Color.White;
            dgvClients.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("Segoe UI", 11F, System.Drawing.FontStyle.Bold);
            dgvClients.DefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(40, 40, 40);
            dgvClients.DefaultCellStyle.ForeColor = System.Drawing.Color.White;
            dgvClients.AlternatingRowsDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(45, 45, 45);
            dgvClients.EnableHeadersVisualStyles = false;
        }
        public void RefreshData()
        {
            LoadClients();
        }
        private void ClientsForm_Load(object sender, EventArgs e)
        {
            LoadClients();
            btnAdd.Visible = AuthHelper.CurrentUser.IsManager;
            btnEdit.Visible = AuthHelper.CurrentUser.IsManager;
            btnDelete.Visible = AuthHelper.CurrentUser.IsAdmin;
            btnExport.Visible = AuthHelper.CurrentUser.IsManager;
        }

        private void LoadClients()
        {
            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    string sql;

                    if (!AuthHelper.CurrentUser.IsManager)
                    {
                        sql = "SELECT client_id, last_name, first_name, middle_name, phone, address FROM sizov_ev.clients_masked ORDER BY client_id";
                    }
                    else
                    {
                        sql = "SELECT client_id, last_name, first_name, middle_name, phone, address FROM sizov_ev.clients ORDER BY client_id";
                    }

                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        DataTable dt = new DataTable();
                        using (var da = new NpgsqlDataAdapter(cmd))
                        {
                            da.Fill(dt);
                        }

                        clientsTable = dt;
                        dgvClients.DataSource = clientsTable;

                        if (dgvClients.Columns["client_id"] != null)
                            dgvClients.Columns["client_id"].HeaderText = "ID";
                        if (dgvClients.Columns["last_name"] != null)
                            dgvClients.Columns["last_name"].HeaderText = "Фамилия";
                        if (dgvClients.Columns["first_name"] != null)
                            dgvClients.Columns["first_name"].HeaderText = "Имя";
                        if (dgvClients.Columns["middle_name"] != null)
                            dgvClients.Columns["middle_name"].HeaderText = "Отчество";
                        if (dgvClients.Columns["phone"] != null)
                            dgvClients.Columns["phone"].HeaderText = "Телефон";
                        if (dgvClients.Columns["address"] != null)
                            dgvClients.Columns["address"].HeaderText = "Адрес";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки клиентов: {ex.Message}");
            }
        }

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

            using (var form = new AddEditClientForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    AuthHelper.LogAction("Клиент добавлен", "clients");
                    LoadClients();
                }
            }
        }

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

            if (dgvClients.CurrentRow == null)
            {
                MessageBox.Show("Выберите клиента.");
                return;
            }

            int clientId = Convert.ToInt32(dgvClients.CurrentRow.Cells["client_id"].Value);
            AuthHelper.LogAction($"Попытка редактирования клиента ID={clientId}", "clients", clientId);

            using (var form = new AddEditClientForm(clientId))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    AuthHelper.LogAction($"Клиент ID={clientId} отредактирован", "clients", clientId);
                    LoadClients();
                }
            }
        }

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

            if (dgvClients.CurrentRow == null)
            {
                MessageBox.Show("Выберите клиента.");
                return;
            }

            if (MessageBox.Show("Удалить клиента?", "Подтверждение", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                int clientId = Convert.ToInt32(dgvClients.CurrentRow.Cells["client_id"].Value);

                try
                {
                    using (var conn = DBConnection.GetConnection())
                    {
                        string sql = "DELETE FROM sizov_ev.clients WHERE client_id = @id";
                        using (var cmd = new NpgsqlCommand(sql, conn))
                        {
                            cmd.Parameters.AddWithValue("@id", clientId);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    AuthHelper.LogAction($"Клиент ID={clientId} удалён", "clients", clientId);
                    LoadClients();
                    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())
                {
                    string sql = @"SELECT 
                        client_id as ""ID"", 
                        last_name as ""Фамилия"", 
                        first_name as ""Имя"", 
                        middle_name as ""Отчество"", 
                        phone as ""Телефон"", 
                        address as ""Адрес""
                        FROM sizov_ev.clients ORDER BY client_id";

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