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

namespace ZhkhApp
{
    public partial class OperatorForm : Form
    {
        private string currentView = "v_receipts_full";  // вместо таблицы receipts

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

        // Загружаем представления, а не таблицы
        private void LoadViewsList()
        {
            cbTables.Items.Clear();
            cbTables.Items.AddRange(new[] {
                "Квитанции (полные)",
                "Задолженность по квартирам",
                "История платежей"
            });
            cbTables.SelectedIndex = 0;
        }

        private void CbTables_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cbTables.SelectedIndex)
            {
                case 0: currentView = "v_receipts_full"; break;
                case 1: currentView = "v_apartment_debt"; break;
                case 2: currentView = "v_payment_history"; break;
            }
            LoadData();
        }

        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()
        {
            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 = "Должник";
            }
            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_receipts"] != null)
                    dgvList.Columns["total_receipts"].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 = "Задолженность, руб";
            }
            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["period_month"] != null)
                    dgvList.Columns["period_month"].HeaderText = "Месяц";
                if (dgvList.Columns["period_year"] != null)
                    dgvList.Columns["period_year"].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 = "Способ оплаты";
            }
        }

        private void DisplayUserInfo()
        {
            lblUserInfo.Text = $"Оператор: {MainForm.CurrentUsername}";
        }

        // Добавление/редактирование/удаление только для квитанций
        private void BtnAdd_Click(object sender, EventArgs e)
        {
            if (currentView != "v_receipts_full")
            {
                MessageBox.Show("Добавление доступно только для квитанций!");
                return;
            }
            var editForm = new EditForm("receipts", null);
            if (editForm.ShowDialog() == DialogResult.OK) LoadData();
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            if (currentView != "v_receipts_full")
            {
                MessageBox.Show("Редактирование доступно только для квитанций!");
                return;
            }
            if (dgvList.CurrentRow == null) { MessageBox.Show("Выберите запись!"); return; }

            int id = Convert.ToInt32(dgvList.CurrentRow.Cells["receipt_id"].Value);
            var editForm = new EditForm("receipts", id);
            if (editForm.ShowDialog() == DialogResult.OK) LoadData();
        }

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

        // Приём оплаты
        private void BtnReports_Click(object sender, EventArgs e)
        {
            ReportForm reportForm = new ReportForm();
            reportForm.ShowDialog();
        }
        private void BtnPayments_Click(object sender, EventArgs e)
        {
            if (dgvList.CurrentRow == null || currentView != "v_receipts_full")
            {
                MessageBox.Show("Выберите квитанцию для оплаты!");
                return;
            }

            int receiptId = Convert.ToInt32(dgvList.CurrentRow.Cells["receipt_id"].Value);
            decimal totalWithPenalty = Convert.ToDecimal(dgvList.CurrentRow.Cells["total_with_penalty"].Value);
            decimal debt = Convert.ToDecimal(dgvList.CurrentRow.Cells["remaining_amount"]);

            if (debt <= 0)
            {
                MessageBox.Show("Эта квитанция уже оплачена!");
                return;
            }

            var paymentForm = new PaymentForm(receiptId, totalWithPenalty, 0);
            if (paymentForm.ShowDialog() == DialogResult.OK)
            {
                LoadData();
                MessageBox.Show("Платёж принят!");
            }
        }

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