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

namespace _0503NeshinaRogova
{
    public partial class OperatorForm : Form
    {
        private int currentUserId;
        private string connectionString = "Server=cfif31.ru;Port=3306;Database=ISPr25-21_NeshinaPV_1003;Uid=ISPr25-21_NeshinaPV;Pwd=ISPr25-21_NeshinaPV;Charset=utf8mb4;";

        public OperatorForm(int userId)
        {
            InitializeComponent();
            currentUserId = userId;
   Requests();
            MastersList();
            StatusesList();
        }

       
        private void Requests()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = @"SELECT 
                                            r.request_id AS 'ID', 
                                            DATE_FORMAT(r.start_date, '%d.%m.%Y') AS 'Дата', 
                                            t.tech_type_name AS 'Тип', 
                                            r.climate_tech_model AS 'Модель', 
                                            r.problem_description AS 'Проблема', 
                                            s.status_name AS 'Статус',
                                            u.fio AS 'Клиент',
                                            CASE WHEN m.fio IS NULL THEN 'Не назначен' ELSE m.fio END AS 'Мастер'
                                     FROM requests r
                                     JOIN tech_types t ON r.tech_type_id = t.tech_type_id
                                     JOIN request_statuses s ON r.status_id = s.status_id
                                     JOIN users u ON r.client_id = u.user_id
                                     LEFT JOIN users m ON r.master_id = m.user_id
                                     ORDER BY r.request_id DESC";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    DataTable dt = new DataTable();
                    new MySqlDataAdapter(cmd).Fill(dt);
                    dataGridViewRequests.DataSource = dt;
                    foreach (DataGridViewRow row in dataGridViewRequests.Rows)
                    {
                        if (row.Cells["Статус"].Value?.ToString() == "Новая заявка")
                        {
                            row.DefaultCellStyle.BackColor = Color.LightYellow;
                            row.DefaultCellStyle.ForeColor = Color.Black;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки заявок: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void MastersList()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = "SELECT user_id, fio FROM users WHERE type_id = 2 ORDER BY fio";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    DataTable dt = new DataTable();
                    new MySqlDataAdapter(cmd).Fill(dt);
                    comboBoxMasters.DataSource = dt;
                    comboBoxMasters.DisplayMember = "fio";
                    comboBoxMasters.ValueMember = "user_id";
                    comboBoxMasters.SelectedIndex = -1;
                    comboBoxMasters.Text = "-- Выберите мастера --";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки мастеров: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void StatusesList()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = "SELECT status_id, status_name FROM request_statuses ORDER BY status_id";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    DataTable dt = new DataTable();
                    new MySqlDataAdapter(cmd).Fill(dt);
                    comboBoxStatus.DataSource = dt;
                    comboBoxStatus.DisplayMember = "status_name";
                    comboBoxStatus.ValueMember = "status_id";
                    comboBoxStatus.SelectedIndex = -1;
                    comboBoxStatus.Text = "-- Выберите статус --";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки статусов: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (dataGridViewRequests.CurrentRow == null)
            {
                MessageBox.Show("Выберите заявку из списка!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrWhiteSpace(textBoxComment.Text))
            {
                MessageBox.Show("Введите текст комментария!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textBoxComment.Focus();
                return;
            }
            int requestId = Convert.ToInt32(dataGridViewRequests.CurrentRow.Cells["ID"].Value);
            AddSystemComment(requestId, textBoxComment.Text, currentUserId);
            textBoxComment.Clear();
            MessageBox.Show("Комментарий добавлен!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void AddSystemComment(int requestId, string message, int authorId)
        {
        
            string query = @"INSERT INTO comments (comment_id, message, master_id, request_id) 
                             VALUES (@cid, @msg, @master, @req)";

            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    int newId = GetNextCommentId(conn);
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@cid", newId);
                    cmd.Parameters.AddWithValue("@msg", message);
                    cmd.Parameters.AddWithValue("@master", authorId); 
                    cmd.Parameters.AddWithValue("@req", requestId);

                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка добавления комментария: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private int GetNextCommentId(MySqlConnection conn)
        {
            string sql = "SELECT IFNULL(MAX(comment_id), 0) + 1 FROM comments";
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            object result = cmd.ExecuteScalar();
            return Convert.ToInt32(result);
        }

        private void buttonAddRequest_Click(object sender, EventArgs e)
        {
            if (dataGridViewRequests.CurrentRow == null)
            {
                MessageBox.Show("Выберите заявку из списка!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int requestId = Convert.ToInt32(dataGridViewRequests.CurrentRow.Cells["ID"].Value);

            if (comboBoxMasters.SelectedValue == null)
            {
                MessageBox.Show("Выберите мастера из списка!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int masterId = Convert.ToInt32(comboBoxMasters.SelectedValue);

            if (comboBoxStatus.SelectedValue == null)
            {
                MessageBox.Show("Выберите новый статус!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int newStatusId = Convert.ToInt32(comboBoxStatus.SelectedValue);
            string query = "UPDATE requests SET master_id = @masterID, status_id = @statusID WHERE request_id = @requestID";
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@masterID", masterId);
                    cmd.Parameters.AddWithValue("@statusID", newStatusId);
                    cmd.Parameters.AddWithValue("@requestID", requestId);

                    int rows = cmd.ExecuteNonQuery();

                    if (rows > 0)
                    {
                        MessageBox.Show($"Заявка №{requestId} обновлена!\nМастер: {comboBoxMasters.Text}\nСтатус изменен.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        Requests();
                        string logMessage = $"Заявка принята оператором. Назначен мастер: {comboBoxMasters.Text}. Статус изменен на '{comboBoxStatus.Text}'.";
                        AddSystemComment(requestId, logMessage, currentUserId);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка обновления: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Form1 form1 = new Form1();
            form1.Show();
            this.Close();
        }
    }
}