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

namespace ProviderApp
{
    public partial class AddEditContractForm : Form
    {
        private int? contractId = null;

        public AddEditContractForm(int? id = null)
        {
            contractId = id;
            InitializeComponent();

            if (contractId.HasValue)
            {
                Text = "Редактирование договора";
                LoadContractData();
            }
            else
            {
                Text = "Добавление договора";
                dtpSignDate.Value = DateTime.Now;
                cmbStatus.SelectedItem = "active";
            }

            LoadComboBoxes();
        }

        private void LoadComboBoxes()
        {
            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    // Загрузка клиентов
                    string sqlClients = "SELECT client_id, last_name || ' ' || first_name AS name FROM clients ORDER BY last_name";
                    using (var cmd = new NpgsqlCommand(sqlClients, conn))
                    using (var da = new NpgsqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        cmbClient.DisplayMember = "name";
                        cmbClient.ValueMember = "client_id";
                        cmbClient.DataSource = dt;
                    }

                    // Загрузка тарифов
                    string sqlTariffs = "SELECT tariff_id, name FROM tariffs ORDER BY name";
                    using (var cmd = new NpgsqlCommand(sqlTariffs, conn))
                    using (var da = new NpgsqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        cmbTariff.DisplayMember = "name";
                        cmbTariff.ValueMember = "tariff_id";
                        cmbTariff.DataSource = dt;
                    }

                    // Загрузка сотрудников
                    string sqlEmployees = "SELECT employee_id, last_name || ' ' || first_name AS name FROM employees ORDER BY last_name";
                    using (var cmd = new NpgsqlCommand(sqlEmployees, conn))
                    using (var da = new NpgsqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        da.Fill(dt);
                        cmbEmployee.DisplayMember = "name";
                        cmbEmployee.ValueMember = "employee_id";
                        cmbEmployee.DataSource = dt;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки данных: {ex.Message}");
            }
        }

        private void LoadContractData()
        {
            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    string sql = "SELECT client_id, tariff_id, employee_id, sign_date, status FROM contracts WHERE contract_id = @id";
                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("@id", contractId.Value);
                        using (var reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                cmbClient.SelectedValue = reader["client_id"];
                                cmbTariff.SelectedValue = reader["tariff_id"];
                                cmbEmployee.SelectedValue = reader["employee_id"];

                                // ИСПРАВЛЕНО: работаем с DateOnly напрямую
                                object signDateObj = reader["sign_date"];
                                if (signDateObj is DateOnly dateOnly)
                                {
                                    dtpSignDate.Value = dateOnly.ToDateTime(TimeOnly.MinValue);
                                }
                                else if (signDateObj is DateTime dateTime)
                                {
                                    dtpSignDate.Value = dateTime;
                                }
                                else
                                {
                                    dtpSignDate.Value = Convert.ToDateTime(signDateObj);
                                }

                                cmbStatus.SelectedItem = reader["status"].ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки договора: {ex.Message}");
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (cmbClient.SelectedValue == null || cmbTariff.SelectedValue == null || cmbEmployee.SelectedValue == null)
            {
                MessageBox.Show("Заполните все поля.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                using (var conn = DBConnection.GetConnection())
                {
                    if (contractId.HasValue)
                    {
                        // Редактирование
                        string sql = @"UPDATE contracts SET client_id=@client, tariff_id=@tariff, employee_id=@employee, 
                                      sign_date=@date, status=@status WHERE contract_id=@id";
                        using (var cmd = new NpgsqlCommand(sql, conn))
                        {
                            cmd.Parameters.AddWithValue("@id", contractId.Value);
                            cmd.Parameters.AddWithValue("@client", cmbClient.SelectedValue);
                            cmd.Parameters.AddWithValue("@tariff", cmbTariff.SelectedValue);
                            cmd.Parameters.AddWithValue("@employee", cmbEmployee.SelectedValue);
                            cmd.Parameters.AddWithValue("@date", DateOnly.FromDateTime(dtpSignDate.Value));
                            cmd.Parameters.AddWithValue("@status", cmbStatus.SelectedItem.ToString());
                            cmd.ExecuteNonQuery();
                        }
                        MessageBox.Show("Договор успешно обновлён!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        // Добавление
                        string sql = @"INSERT INTO contracts (client_id, tariff_id, employee_id, sign_date, status) 
                                      VALUES (@client, @tariff, @employee, @date, @status)
                                      RETURNING contract_id";

                        using (var cmd = new NpgsqlCommand(sql, conn))
                        {
                            cmd.Parameters.AddWithValue("@client", cmbClient.SelectedValue);
                            cmd.Parameters.AddWithValue("@tariff", cmbTariff.SelectedValue);
                            cmd.Parameters.AddWithValue("@employee", cmbEmployee.SelectedValue);
                            cmd.Parameters.AddWithValue("@date", DateOnly.FromDateTime(dtpSignDate.Value));
                            cmd.Parameters.AddWithValue("@status", cmbStatus.SelectedItem.ToString());

                            int newId = Convert.ToInt32(cmd.ExecuteScalar());
                            MessageBox.Show($"Договор №{newId} успешно добавлен!", "Успех",
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }

                DialogResult = DialogResult.OK;
                Close();
            }
            catch (PostgresException ex) when (ex.SqlState == "23505")
            {
                MessageBox.Show("Ошибка: такой договор уже существует. Попробуйте снова.",
                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка сохранения: {ex.Message}",
                    "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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