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

namespace _0503NeshinaRogova
{
    public partial class MasterForm : Form
    {
        private int currentUserId; 
        private string connectionString = "Server=cfif31.ru; port=3306; Database=ISPr25-21_NeshinaPV_0503; username=ISPr25-21_NeshinaPV; password=ISPr25-21_NeshinaPV";

        public MasterForm(int userId)
        {
            InitializeComponent();
            currentUserId = userId;
            tatuses();
            Requests();
        }

        private void tatuses()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = "SELECT statusID, statusName FROM request_statuses";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    DataTable dt = new DataTable();
                    new MySqlDataAdapter(cmd).Fill(dt);
                    comboBoxStatus.DataSource = dt;
                    comboBoxStatus.DisplayMember = "statusName";
                    comboBoxStatus.ValueMember = "statusID";
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row["statusName"].ToString() == "Готова к выдаче")
                        {
                            comboBoxStatus.SelectedValue = row["statusID"];
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки статусов: " + ex.Message);
            }
        }

        private void Requests()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = @"SELECT 
                                        r.requestID AS '№',
                                        r.startDate AS 'Дата приема',
                                        t.techTypeName AS 'Тип',
                                        r.orgTechModel AS 'Модель',
                                        r.problemDescription AS 'Неисправность',
                                        s.statusName AS 'Текущий статус',
                                        r.repairParts AS 'Запчасти',
                                        r.completionDate AS 'Дата сдачи'
                                     FROM requests r
                                     JOIN tech_types t ON r.techTypeID = t.techTypeID
                                     JOIN request_statuses s ON r.statusID = s.statusID
                                     WHERE r.masterID = @masterID
                                     ORDER BY r.requestID DESC";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@masterID", currentUserId);
                    DataTable dt = new DataTable();
                    new MySqlDataAdapter(cmd).Fill(dt);
                    dataGridViewRequests.DataSource = dt;
                    dataGridViewRequests.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    dataGridViewRequests.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                    foreach (DataGridViewRow row in dataGridViewRequests.Rows)
                    {
                        if (row.Cells["Текущий статус"].Value?.ToString() == "Готова к выдаче")
                        {
                            row.DefaultCellStyle.BackColor = Color.LightGreen;
                        }
                        else if (row.Cells["Текущий статус"].Value?.ToString() == "В процессе ремонта")
                        {
                            row.DefaultCellStyle.BackColor = Color.LightYellow;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки заявок: " + ex.Message);
            }
        }


        private void dataGridViewRequests_SelectionChanged_1(object sender, EventArgs e)
        {
            if (dataGridViewRequests.CurrentRow == null) return;
            try
            {
                textBoxParts.Clear();
                textBoxComment.Clear();
                dtpCompletion.Checked = false;
                var parts = dataGridViewRequests.CurrentRow.Cells["Запчасти"].Value;
                if (parts != DBNull.Value && parts != null)
                    textBoxParts.Text = parts.ToString();
                var dateVal = dataGridViewRequests.CurrentRow.Cells["Дата сдачи"].Value;
                if (dateVal != DBNull.Value && dateVal != null)
                {
                    dtpCompletion.Value = Convert.ToDateTime(dateVal);
                    dtpCompletion.Checked = true;
                }
                string currentStatus = dataGridViewRequests.CurrentRow.Cells["Текущий статус"].Value.ToString();
                foreach (DataRowView row in comboBoxStatus.Items)
                {
                    if (row["statusName"].ToString() == currentStatus)
                    {
                        comboBoxStatus.SelectedValue = row["statusID"];
                        break;
                    }
                }
            }
            catch { }
        }

        private void buttonSaveReport_Click(object sender, EventArgs e)
        {
            if (dataGridViewRequests.CurrentRow == null)
            {
                MessageBox.Show("Выберите заявку из списка!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            int requestId = Convert.ToInt32(dataGridViewRequests.CurrentRow.Cells["№"].Value);
            string parts = textBoxParts.Text.Trim();
            string commentText = textBoxComment.Text.Trim();
            int newStatusId = Convert.ToInt32(comboBoxStatus.SelectedValue);
            DateTime? completionDate = null;
            if (dtpCompletion.Checked)
                completionDate = dtpCompletion.Value.Date;
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string updateQuery = @"UPDATE requests 
                                           SET repairParts = @parts, 
                                               completionDate = @compDate, 
                                               statusID = @status
                                           WHERE requestID = @reqId";
                    MySqlCommand cmdUpdate = new MySqlCommand(updateQuery, conn);
                    cmdUpdate.Parameters.AddWithValue("@parts", (object)parts ?? DBNull.Value);
                    cmdUpdate.Parameters.AddWithValue("@compDate", (object)completionDate ?? DBNull.Value);
                    cmdUpdate.Parameters.AddWithValue("@status", newStatusId);
                    cmdUpdate.Parameters.AddWithValue("@reqId", requestId);
                    int rows = cmdUpdate.ExecuteNonQuery();
                    if (rows > 0)
                    {
                        if (!string.IsNullOrEmpty(commentText))
                        {
                            string insertComment = "INSERT INTO comments (message, masterID, requestID) VALUES (@msg, @master, @req)";
                            MySqlCommand cmdComm = new MySqlCommand(insertComment, conn);
                            cmdComm.Parameters.AddWithValue("@msg", commentText);
                            cmdComm.Parameters.AddWithValue("@master", currentUserId);
                            cmdComm.Parameters.AddWithValue("@req", requestId);
                            cmdComm.ExecuteNonQuery();
                        }
                        MessageBox.Show("Отчет сохранен! Статус заявки обновлен.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        textBoxParts.Clear();
                        textBoxComment.Clear();
                        Requests();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка сохранения отчета: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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