using MySql.Data.MySqlClient;
using System;
using System.Data;
using System.Windows.Forms;

namespace _0503NeshinaRogova
{
    public partial class EditRequestForm : Form
    {
        private string connectionString;
        private bool isEditMode;
        private int requestId;

        public EditRequestForm(string connString, bool editMode, int id)
        {
            InitializeComponent();
            connectionString = connString;
            isEditMode = editMode;
            requestId = id;

            if (isEditMode)
            {
                Text = "Редактирование заявки №" + id;
                Edit();
            }
            else
            {
                Text = "Новая заявка";
                dtpDate.Value = DateTime.Now;
                dtpCompletion.Checked = false; 
            }

            ComboBoxes();
        }

        private void ComboBoxes()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    DataTable dtTech = new DataTable();
                    new MySqlDataAdapter("SELECT tech_type_id, tech_type_name FROM tech_types ORDER BY tech_type_name", conn).Fill(dtTech);
                    cbTechType.DataSource = dtTech;
                    cbTechType.DisplayMember = "tech_type_name";
                    cbTechType.ValueMember = "tech_type_id";
                    DataTable dtStatus = new DataTable();
                    new MySqlDataAdapter("SELECT status_id, status_name FROM request_statuses ORDER BY status_id", conn).Fill(dtStatus);
                    cbStatus.DataSource = dtStatus;
                    cbStatus.DisplayMember = "status_name";
                    cbStatus.ValueMember = "status_id";
                    DataTable dtMasters = new DataTable();
                    new MySqlDataAdapter("SELECT user_id, fio FROM users WHERE type_id = 2 ORDER BY fio", conn).Fill(dtMasters);
                    DataRow emptyRow = dtMasters.NewRow();
                    emptyRow["user_id"] = DBNull.Value;
                    emptyRow["fio"] = "Не назначен";
                    dtMasters.Rows.InsertAt(emptyRow, 0);
                    cbMaster.DataSource = dtMasters;
                    cbMaster.DisplayMember = "fio";
                    cbMaster.ValueMember = "user_id";
                    cbMaster.SelectedValue = DBNull.Value; 
                    DataTable dtClients = new DataTable();
                    new MySqlDataAdapter("SELECT user_id, fio FROM users WHERE type_id = 4 ORDER BY fio", conn).Fill(dtClients);
                    cbClient.DataSource = dtClients;
                    cbClient.DisplayMember = "fio";
                    cbClient.ValueMember = "user_id";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки списков: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Edit()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = "SELECT * FROM requests WHERE request_id = @id";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@id", requestId);
                    MySqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        dtpDate.Value = Convert.ToDateTime(reader["start_date"]);
                        if (reader["tech_type_id"] != DBNull.Value)
                            cbTechType.SelectedValue = reader["tech_type_id"];

                        tbModel.Text = reader["climate_tech_model"].ToString();
                        tbProblem.Text = reader["problem_description"].ToString();
                        if (reader["status_id"] != DBNull.Value)
                            cbStatus.SelectedValue = reader["status_id"];
                        if (reader["completion_date"] != DBNull.Value)
                        {
                            dtpCompletion.Value = Convert.ToDateTime(reader["completion_date"]);
                            dtpCompletion.Checked = true;
                        }
                        else
                        {
                            dtpCompletion.Checked = false;
                        }
                        tbParts.Text = reader["repair_parts"].ToString();
                        if (reader["master_id"] != DBNull.Value)
                            cbMaster.SelectedValue = reader["master_id"];
                        else
                            cbMaster.SelectedValue = DBNull.Value;
                        if (reader["client_id"] != DBNull.Value)
                            cbClient.SelectedValue = reader["client_id"];
                    }
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки данных заявки: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

        private void btnSave_Click_1(object sender, EventArgs e)
        {
            
            if (cbTechType.SelectedValue == null || cbStatus.SelectedValue == null || cbClient.SelectedValue == null)
            {
                MessageBox.Show("Заполните обязательные поля (Техника, Статус, Клиент)!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrWhiteSpace(tbModel.Text))
            {
                MessageBox.Show("Введите модель техники!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                tbModel.Focus();
                return;
            }

            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query;
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;

                    if (isEditMode)
                    {
                        query = @"UPDATE requests SET 
                                  start_date = @date,
                                  tech_type_id = @tech,
                                  climate_tech_model = @model,
                                  problem_description = @prob,
                                  status_id = @status,
                                  completion_date = @comp,
                                  repair_parts = @parts,
                                  master_id = @master,
                                  client_id = @client
                                  WHERE request_id = @id";
                        cmd.Parameters.AddWithValue("@id", requestId);
                    }
                    else
                    {
                        query = @"INSERT INTO requests 
                                  (start_date, tech_type_id, climate_tech_model, problem_description, status_id, completion_date, repair_parts, master_id, client_id) 
                                  VALUES 
                                  (@date, @tech, @model, @prob, @status, @comp, @parts, @master, @client)";
                    }
                    cmd.CommandText = query;
                    cmd.Parameters.AddWithValue("@date", dtpDate.Value.Date);
                    cmd.Parameters.AddWithValue("@tech", cbTechType.SelectedValue);
                    cmd.Parameters.AddWithValue("@model", tbModel.Text.Trim());
                    cmd.Parameters.AddWithValue("@prob", tbProblem.Text.Trim());
                    cmd.Parameters.AddWithValue("@status", cbStatus.SelectedValue);
                    if (dtpCompletion.Checked)
                        cmd.Parameters.AddWithValue("@comp", (object)dtpCompletion.Value.Date);
                    else
                        cmd.Parameters.AddWithValue("@comp", DBNull.Value);
                    string partsText = tbParts.Text.Trim();
                    cmd.Parameters.AddWithValue("@parts", string.IsNullOrEmpty(partsText) ? (object)DBNull.Value : partsText);
                    if (cbMaster.SelectedValue != null && cbMaster.SelectedIndex > 0) // Index 0 это "Не назначен"
                        cmd.Parameters.AddWithValue("@master", cbMaster.SelectedValue);
                    else
                        cmd.Parameters.AddWithValue("@master", DBNull.Value);

                    cmd.Parameters.AddWithValue("@client", cbClient.SelectedValue);

                    int rows = cmd.ExecuteNonQuery();

                    if (rows > 0)
                    {
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("Не удалось сохранить данные.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка сохранения: " + ex.Message, "Критическая ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void panelFooter_Paint(object sender, PaintEventArgs e)
        {
        }
    }
}