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

namespace ZhkhApp
{
    public partial class AdminForm : Form
    {
        private string currentView = "v_receipts_full";
        private bool isUpdating = false;

        public AdminForm()
        {
            InitializeComponent();
            LoadViewsList();
            LoadData();
            DisplayUserInfo();
        }

        // Загружаем представления для просмотра + таблицы для редактирования
        private void LoadViewsList()
        {
            cbTables.Items.Clear();
            cbTables.Items.AddRange(new[] {
                "Квитанции (полные)",           // v_receipts_full
                "Задолженность по квартирам",   // v_apartment_debt
                "История платежей",             // v_payment_history
                "---",                          // разделитель
                "Управление: Квартиры",         // apartments (редактирование)
                "Управление: Люди",             // persons
                "Управление: Квитанции",        // receipts
                "Управление: Платежи",          // payments
                "Управление: Пользователи",     // users
                "Журнал операций"               // operation_log
            });
            cbTables.SelectedIndex = 0;
        }

        private void CbTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            string selected = cbTables.SelectedItem.ToString();
            isUpdating = true;

            switch (selected)
            {
                case "Квитанции (полные)":
                    currentView = "v_receipts_full";
                    EnableEditButtons(false);
                    break;
                case "Задолженность по квартирам":
                    currentView = "v_apartment_debt";
                    EnableEditButtons(false);
                    break;
                case "История платежей":
                    currentView = "v_payment_history";
                    EnableEditButtons(false);
                    break;
                case "Управление: Квартиры":
                    currentView = "apartments";
                    EnableEditButtons(true);
                    break;
                case "Управление: Люди":
                    currentView = "persons";
                    EnableEditButtons(true);
                    break;
                case "Управление: Квитанции":
                    currentView = "receipts";
                    EnableEditButtons(true);
                    break;
                case "Управление: Платежи":
                    currentView = "payments";
                    EnableEditButtons(true);
                    break;
                case "Управление: Пользователи":
                    currentView = "users";
                    EnableEditButtons(true);
                    break;
                case "Журнал операций":
                    currentView = "operation_log";
                    EnableEditButtons(false);
                    break;
                default:
                    currentView = "v_receipts_full";
                    EnableEditButtons(false);
                    break;
            }
            isUpdating = false;
            LoadData();
        }

        private void EnableEditButtons(bool enable)
        {
            btnAdd.Enabled = enable;
            btnEdit.Enabled = enable;
            btnDelete.Enabled = enable;
        }

        private void BtnLoad_Click(object sender, EventArgs e) => LoadData();
        private void BtnRefresh_Click(object sender, EventArgs e) => LoadData();

        private void LoadData()
        {
            try
            {
                string query = $"SELECT * FROM {currentView}";

                using (var conn = new NpgsqlConnection(MainForm.ConnectionString))
                {
                    conn.Open();
                    using (var adapter = new NpgsqlDataAdapter(query, conn))
                    {
                        DataTable dt = new DataTable();
                        adapter.Fill(dt);
                        dgvList.DataSource = dt;
                    }
                }
                SetRussianHeaders();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка: {ex.Message}");
            }
        }

        private void SetRussianHeaders()
        {
            // v_receipts_full
            if (currentView == "v_receipts_full")
            {
                if (dgvList.Columns["receipt_id"] != null)
                    dgvList.Columns["receipt_id"].HeaderText = "№";
                if (dgvList.Columns["apt_number"] != null)
                    dgvList.Columns["apt_number"].HeaderText = "Квартира";
                if (dgvList.Columns["full_address"] != null)
                    dgvList.Columns["full_address"].HeaderText = "Адрес";
                if (dgvList.Columns["period_month"] != null)
                    dgvList.Columns["period_month"].HeaderText = "Месяц";
                if (dgvList.Columns["period_year"] != null)
                    dgvList.Columns["period_year"].HeaderText = "Год";
                if (dgvList.Columns["total_sum"] != null)
                    dgvList.Columns["total_sum"].HeaderText = "Сумма, руб";
                if (dgvList.Columns["penalty"] != null)
                    dgvList.Columns["penalty"].HeaderText = "Пени, руб";
                if (dgvList.Columns["total_with_penalty"] != null)
                    dgvList.Columns["total_with_penalty"].HeaderText = "Итого, руб";
                if (dgvList.Columns["status"] != null)
                    dgvList.Columns["status"].HeaderText = "Статус";
                if (dgvList.Columns["debtor_name"] != null)
                    dgvList.Columns["debtor_name"].HeaderText = "Должник";
            }
            // v_apartment_debt
            else if (currentView == "v_apartment_debt")
            {
                if (dgvList.Columns["apt_number"] != null)
                    dgvList.Columns["apt_number"].HeaderText = "Квартира";
                if (dgvList.Columns["address"] != null)
                    dgvList.Columns["address"].HeaderText = "Адрес";
                if (dgvList.Columns["total_accrued"] != null)
                    dgvList.Columns["total_accrued"].HeaderText = "Начислено, руб";
                if (dgvList.Columns["total_paid"] != null)
                    dgvList.Columns["total_paid"].HeaderText = "Оплачено, руб";
                if (dgvList.Columns["current_debt"] != null)
                    dgvList.Columns["current_debt"].HeaderText = "Задолженность, руб";
            }
            // v_payment_history
            else if (currentView == "v_payment_history")
            {
                if (dgvList.Columns["payment_id"] != null)
                    dgvList.Columns["payment_id"].HeaderText = "№ платежа";
                if (dgvList.Columns["apt_number"] != null)
                    dgvList.Columns["apt_number"].HeaderText = "Квартира";
                if (dgvList.Columns["payer_name"] != null)
                    dgvList.Columns["payer_name"].HeaderText = "Плательщик";
                if (dgvList.Columns["payment_date"] != null)
                    dgvList.Columns["payment_date"].HeaderText = "Дата оплаты";
                if (dgvList.Columns["amount"] != null)
                    dgvList.Columns["amount"].HeaderText = "Сумма, руб";
                if (dgvList.Columns["payment_method"] != null)
                    dgvList.Columns["payment_method"].HeaderText = "Способ оплаты";
            }
            // apartments
            else if (currentView == "apartments")
            {
                if (dgvList.Columns["apartment_id"] != null)
                    dgvList.Columns["apartment_id"].HeaderText = "ID";
                if (dgvList.Columns["apt_number"] != null)
                    dgvList.Columns["apt_number"].HeaderText = "№ квартиры";
                if (dgvList.Columns["area"] != null)
                    dgvList.Columns["area"].HeaderText = "Площадь, м²";
                if (dgvList.Columns["resident_count"] != null)
                    dgvList.Columns["resident_count"].HeaderText = "Проживает";
                if (dgvList.Columns["address_id"] != null)
                    dgvList.Columns["address_id"].HeaderText = "ID адреса";
            }
            // persons
            else if (currentView == "persons")
            {
                if (dgvList.Columns["person_id"] != null)
                    dgvList.Columns["person_id"].HeaderText = "ID";
                if (dgvList.Columns["last_name"] != null)
                    dgvList.Columns["last_name"].HeaderText = "Фамилия";
                if (dgvList.Columns["first_name"] != null)
                    dgvList.Columns["first_name"].HeaderText = "Имя";
                if (dgvList.Columns["middle_name"] != null)
                    dgvList.Columns["middle_name"].HeaderText = "Отчество";
            }
            // receipts
            else if (currentView == "receipts")
            {
                if (dgvList.Columns["receipt_id"] != null)
                    dgvList.Columns["receipt_id"].HeaderText = "№";
                if (dgvList.Columns["apartment_id"] != null)
                    dgvList.Columns["apartment_id"].HeaderText = "ID квартиры";
                if (dgvList.Columns["total_sum"] != null)
                    dgvList.Columns["total_sum"].HeaderText = "Сумма";
                if (dgvList.Columns["penalty"] != null)
                    dgvList.Columns["penalty"].HeaderText = "Пени";
                if (dgvList.Columns["status"] != null)
                    dgvList.Columns["status"].HeaderText = "Статус";
            }
            // payments
            else if (currentView == "payments")
            {
                if (dgvList.Columns["payment_id"] != null)
                    dgvList.Columns["payment_id"].HeaderText = "ID";
                if (dgvList.Columns["receipt_id"] != null)
                    dgvList.Columns["receipt_id"].HeaderText = "ID квитанции";
                if (dgvList.Columns["amount"] != null)
                    dgvList.Columns["amount"].HeaderText = "Сумма";
                if (dgvList.Columns["payment_date"] != null)
                    dgvList.Columns["payment_date"].HeaderText = "Дата";
                if (dgvList.Columns["payment_method"] != null)
                    dgvList.Columns["payment_method"].HeaderText = "Способ";
            }
            // users
            else if (currentView == "users")
            {
                if (dgvList.Columns["user_id"] != null)
                    dgvList.Columns["user_id"].HeaderText = "ID";
                if (dgvList.Columns["username"] != null)
                    dgvList.Columns["username"].HeaderText = "Логин";
                if (dgvList.Columns["role_id"] != null)
                    dgvList.Columns["role_id"].HeaderText = "ID роли";
                if (dgvList.Columns["person_id"] != null)
                    dgvList.Columns["person_id"].HeaderText = "ID человека";
            }
            // operation_log
            else if (currentView == "operation_log")
            {
                if (dgvList.Columns["log_id"] != null)
                    dgvList.Columns["log_id"].HeaderText = "ID";
                if (dgvList.Columns["table_name"] != null)
                    dgvList.Columns["table_name"].HeaderText = "Таблица";
                if (dgvList.Columns["operation"] != null)
                    dgvList.Columns["operation"].HeaderText = "Операция";
                if (dgvList.Columns["changed_by"] != null)
                    dgvList.Columns["changed_by"].HeaderText = "Кто изменил";
                if (dgvList.Columns["record_id"] != null)
                    dgvList.Columns["record_id"].HeaderText = "ID записи";
                if (dgvList.Columns["change_date"] != null)
                    dgvList.Columns["change_date"].HeaderText = "Дата/время";
            }
        }

        private void DisplayUserInfo()
        {
            lblUserInfo.Text = $"Администратор: {MainForm.CurrentUsername}";
        }

        private string GetPrimaryKeyName(string table)
        {
            switch (table)
            {
                case "apartments": return "apartment_id";
                case "persons": return "person_id";
                case "receipts": return "receipt_id";
                case "payments": return "payment_id";
                case "users": return "user_id";
                default: return table + "_id";
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            if (currentView == "v_receipts_full" || currentView == "v_apartment_debt" ||
                currentView == "v_payment_history" || currentView == "operation_log")
            {
                MessageBox.Show("Нельзя добавить запись в представление!");
                return;
            }
            var editForm = new EditForm(currentView, null);
            if (editForm.ShowDialog() == DialogResult.OK) LoadData();
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (currentView == "v_receipts_full" || currentView == "v_apartment_debt" ||
                currentView == "v_payment_history" || currentView == "operation_log")
            {
                MessageBox.Show("Нельзя редактировать представление!");
                return;
            }
            if (dgvList.CurrentRow == null) { MessageBox.Show("Выберите запись!"); return; }
            string pkName = GetPrimaryKeyName(currentView);
            int id = Convert.ToInt32(dgvList.CurrentRow.Cells[pkName].Value);
            var editForm = new EditForm(currentView, id);
            if (editForm.ShowDialog() == DialogResult.OK) LoadData();
        }

        private void BtnDelete_Click(object sender, EventArgs e)
        {
            if (currentView == "v_receipts_full" || currentView == "v_apartment_debt" ||
                currentView == "v_payment_history" || currentView == "operation_log")
            {
                MessageBox.Show("Нельзя удалить запись из представления!");
                return;
            }
            if (dgvList.CurrentRow == null) { MessageBox.Show("Выберите запись!"); return; }
            if (MessageBox.Show("Удалить?", "Подтверждение", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    string pkName = GetPrimaryKeyName(currentView);
                    int id = Convert.ToInt32(dgvList.CurrentRow.Cells[pkName].Value);
                    using (var conn = new NpgsqlConnection(MainForm.ConnectionString))
                    {
                        conn.Open();
                        using (var cmd = new NpgsqlCommand($"DELETE FROM {currentView} WHERE {pkName} = @id", conn))
                        {
                            cmd.Parameters.AddWithValue("@id", id);
                            cmd.ExecuteNonQuery();
                        }
                    }
                    LoadData();
                    MessageBox.Show("Запись удалена!");
                }
                catch (Exception ex) { MessageBox.Show($"Ошибка: {ex.Message}"); }
            }
        }

        private void BtnPayments_Click(object sender, EventArgs e)
        {
            currentView = "payments";
            cbTables.SelectedItem = "Управление: Платежи";
            LoadData();
        }
        private void BtnLog_Click(object sender, EventArgs e)
        {
            LogForm logForm = new LogForm();
            logForm.ShowDialog();
        }
        private void BtnUsers_Click(object sender, EventArgs e)
        {
            currentView = "users";
            cbTables.SelectedItem = "Управление: Пользователи";
            LoadData();
        }

        private void BtnLogout_Click(object sender, EventArgs e)
        {
            Application.Restart();
        }
    }
}