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

namespace _0503NeshinaRogova
{
    public partial class ClientForm : 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 ClientForm(int userId)
        {
            InitializeComponent();
            currentUserId = userId;
            LoadTechTypes();
            LoadUserRequests();
        }

     
      
        private void LoadTechTypes()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = "SELECT tech_type_id, tech_type_name FROM tech_types ORDER BY tech_type_name";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    DataTable dt = new DataTable();
                    MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                    adapter.Fill(dt);
                    comboBoxTechType.DataSource = dt;
                    comboBoxTechType.DisplayMember = "tech_type_name";
                    comboBoxTechType.ValueMember = "tech_type_id";
                    comboBoxTechType.SelectedIndex = -1;
                    comboBoxTechType.Text = "-- Выберите тип техники --";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка загрузки типов техники: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void LoadUserRequests()
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = @"SELECT 
                                            r.request_id AS '№', 
                                            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 'Статус',
                                            IFNULL(DATE_FORMAT(r.completion_date, '%d.%m.%Y'), '-') 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
                                     WHERE r.client_id = @clientID
                                     ORDER BY r.request_id DESC";
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.AddWithValue("@clientID", currentUserId);
                    DataTable dt = new DataTable();
                    MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
                    adapter.Fill(dt);
                   dataGridViewRequests.DataSource = dt;
                    if (dataGridViewRequests.Columns.Count > 0)
                    {
                        dataGridViewRequests.Columns["№"].Width = 40;
                        dataGridViewRequests.Columns["Дата"].Width = 80;
                        dataGridViewRequests.Columns["Статус"].Width = 110;
                    }
                }
            }
            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();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBoxTechType.SelectedValue == null)
            {
                MessageBox.Show("Выберите тип техники!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                comboBoxTechType.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(textBoxModel.Text))
            {
                MessageBox.Show("Введите модель техники!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textBoxModel.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(textBoxProblem.Text))
            {
                MessageBox.Show("Опишите проблему!", "Внимание", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                textBoxProblem.Focus();
                return;
            }
            int selectedTechTypeId = Convert.ToInt32(comboBoxTechType.SelectedValue);
            string query = @"INSERT INTO requests 
                            (start_date, tech_type_id, climate_tech_model, problem_description, status_id, client_id) 
                            VALUES 
                            (@startDate, @techTypeID, @model, @problem, @statusID, @clientID)";
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    cmd.Parameters.Add("@startDate", MySqlDbType.Date).Value = DateTime.Now.Date;
                    cmd.Parameters.Add("@techTypeID", MySqlDbType.Int32).Value = selectedTechTypeId;
                    cmd.Parameters.Add("@model", MySqlDbType.VarChar).Value = textBoxModel.Text.Trim();
                    cmd.Parameters.Add("@problem", MySqlDbType.Text).Value = textBoxProblem.Text.Trim();
                    cmd.Parameters.Add("@statusID", MySqlDbType.Int32).Value = 3; // 3 = "Новая заявка" (из твоего дампа)
                    cmd.Parameters.Add("@clientID", MySqlDbType.Int32).Value = currentUserId;
                    int rowsAffected = cmd.ExecuteNonQuery();
                    if (rowsAffected > 0)
                    {
                        MessageBox.Show("Заявка успешно создана!\nОжидайте назначения мастера.", "Успех",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                        textBoxModel.Clear();
                        textBoxProblem.Clear();
                        comboBoxTechType.SelectedIndex = -1;
                        comboBoxTechType.Text = " Выберите тип техники";
                        LoadUserRequests(); 
                    }
                    else
                    {
                        MessageBox.Show("Не удалось создать заявку.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка базы данных: " + ex.Message, "Критическая ошибка",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}