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

namespace ZhkhApp
{
    public partial class PaymentForm : Form
    {
        private int receiptId;
        private decimal totalAmount;
        private decimal remainingAmount;
        private int userId;

        public PaymentForm(int receiptId, decimal totalAmount, int userId)
        {
            this.receiptId = receiptId;
            this.totalAmount = totalAmount;
            this.userId = userId;
            InitializeComponent();

            cbMethod.Items.Clear();
            cbMethod.Items.AddRange(new[] { "Банковская карта", "Наличные (в кассе)", "Онлайн-кошелёк" });
            cbMethod.SelectedIndex = 0;

            LoadReceiptInfo();
            LoadPenalty();
        }

        private void LoadReceiptInfo()
        {
            try
            {
                string query = @"
                    SELECT r.receipt_id, a.apt_number, r.period_month, r.period_year,
                           r.total_sum, r.penalty, r.remaining_amount
                    FROM receipts r
                    JOIN apartments a ON r.apartment_id = a.apartment_id
                    WHERE r.receipt_id = @receiptId";

                using (var conn = new NpgsqlConnection(MainForm.ConnectionString))
                {
                    conn.Open();
                    using (var cmd = new NpgsqlCommand(query, conn))
                    {
                        cmd.Parameters.AddWithValue("@receiptId", receiptId);
                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                string aptNumber = reader["apt_number"].ToString();
                                int month = Convert.ToInt32(reader["period_month"]);
                                int year = Convert.ToInt32(reader["period_year"]);
                                remainingAmount = Convert.ToDecimal(reader["remaining_amount"]);

                                lblReceiptInfo.Text = $"Квитанция №{receiptId} | Кв.{aptNumber} | {month}.{year}";
                                lblAmountToPay.Text = $"Сумма к оплате: {remainingAmount:F2} руб.";
                                txtAmount.Text = remainingAmount.ToString("F2");

                                if (remainingAmount <= 0)
                                {
                                    btnPay.Enabled = false;
                                    lblStatus.Text = "Квитанция уже оплачена!";
                                }
                                else
                                {
                                    btnPay.Enabled = true;
                                }
                            }
                            else
                            {
                                lblStatus.Text = "Квитанция не найдена!";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = $"Ошибка: {ex.Message}";
            }
        }

        private void LoadPenalty()
        {
            try
            {
                string query = "SELECT calculate_penalty(@receiptId, CURRENT_DATE)";

                using (var conn = new NpgsqlConnection(MainForm.ConnectionString))
                {
                    conn.Open();
                    using (var cmd = new NpgsqlCommand(query, conn))
                    {
                        cmd.Parameters.AddWithValue("@receiptId", receiptId);
                        object result = cmd.ExecuteScalar();
                        decimal penalty = result != DBNull.Value ? Convert.ToDecimal(result) : 0;
                        lblPenaltyInfo.Text = $"Пени за просрочку: {penalty:F2} руб.";
                    }
                }
            }
            catch (Exception ex)
            {
                lblPenaltyInfo.Text = "Пени: ошибка расчета";
            }
        }

        private void CbMethod_SelectedIndexChanged(object sender, EventArgs e)
        {
            pnlCardDetails.Visible = (cbMethod.SelectedIndex == 0);
        }

        private void TxtCardNumber_TextChanged(object sender, EventArgs e)
        {
            string text = txtCardNumber.Text.Replace(" ", "");
            if (text.Length >= 4)
            {
                if (text.Length >= 8)
                {
                    if (text.Length >= 12)
                    {
                        txtCardNumber.Text = $"{text.Substring(0, 4)} {text.Substring(4, 4)} {text.Substring(8, 4)} {text.Substring(12)}";
                    }
                    else
                    {
                        txtCardNumber.Text = $"{text.Substring(0, 4)} {text.Substring(4, 4)} {text.Substring(8)}";
                    }
                }
                else
                {
                    txtCardNumber.Text = $"{text.Substring(0, 4)} {text.Substring(4)}";
                }
                txtCardNumber.SelectionStart = txtCardNumber.Text.Length;
            }
        }

        private void BtnPay_Click(object sender, EventArgs e)
        {
            if (!decimal.TryParse(txtAmount.Text, out decimal paymentAmount) || paymentAmount <= 0)
            {
                lblStatus.Text = "Введите корректную сумму оплаты!";
                return;
            }

            if (paymentAmount > remainingAmount)
            {
                lblStatus.Text = "Сумма оплаты не может превышать остаток задолженности!";
                return;
            }

            if (cbMethod.SelectedIndex == 0)
            {
                string cardNumber = txtCardNumber.Text.Replace(" ", "");
                if (cardNumber.Length < 16)
                {
                    lblStatus.Text = "Введите корректный номер карты (16 цифр)!";
                    return;
                }
                if (txtCardExpiry.Text.Length < 5)
                {
                    lblStatus.Text = "Введите срок действия карты (ММ/ГГ)!";
                    return;
                }
                if (txtCardCvv.Text.Length < 3)
                {
                    lblStatus.Text = "Введите CVV код (3 цифры)!";
                    return;
                }
            }

            try
            {
                using (var conn = new NpgsqlConnection(MainForm.ConnectionString))
                {
                    conn.Open();

                    string insertPayment = @"
                        INSERT INTO payments (receipt_id, payment_date, amount, payment_method, status)
                        VALUES (@receiptId, CURRENT_DATE, @amount, @method, 'paid')";

                    using (var cmd = new NpgsqlCommand(insertPayment, conn))
                    {
                        cmd.Parameters.AddWithValue("@receiptId", receiptId);
                        cmd.Parameters.AddWithValue("@amount", paymentAmount);
                        cmd.Parameters.AddWithValue("@method", cbMethod.SelectedItem.ToString());
                        cmd.ExecuteNonQuery();
                    }
                }

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                lblStatus.Text = $"Ошибка оплаты: {ex.Message}";
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}