using Npgsql;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xceed.Words.NET;

namespace PM11
{
    public partial class Form2 : Form
    {
        private readonly string connString;
        private readonly int userId;

        public Form2(int userId, string connString)
        {
            InitializeComponent();
            this.userId = userId;
            this.connString = connString;
            LoadTable();
            ShowButton(Program.role_id == 1);

        }

        private void Form2_Load(object sender, EventArgs e)
        {
            
        }

        private void ShowButton(bool visible)
        {
            button1.Visible = visible;
            button2.Visible = visible;
            button3.Visible = visible;
            button4.Visible = visible;
        }

        private void LoadTable()
        {
            string sql = Program.role_id == 1
                ? "SELECT id, date_start, date_end, time_start, time_end, detail_id, master_id FROM job"
                : "SELECT id, date_start, date_end, time_start, time_end, detail_id, master_id FROM job WHERE master_id = (SELECT id FROM masters WHERE user_id = @userId)";

            using (var conn = new NpgsqlConnection(Program.connString))
            {
                conn.Open();
                using (var cmd = new NpgsqlCommand(sql, conn))
                {
                    if (Program.role_id != 1)
                        cmd.Parameters.AddWithValue("userId", Program.user_id);

                    using (var adapter = new NpgsqlDataAdapter(cmd))
                    {
                        var dt = new DataTable();
                        adapter.Fill(dt);
                        dataGridView1.DataSource = dt;
                        dataGridView1.Columns["id"].Visible = false;
                    }
                }
                conn.Close();
            }
        }


        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void AddData(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            var row = dataGridView1.CurrentRow;

            try
            {
                using (var conn = new NpgsqlConnection(Program.connString))
                {
                    conn.Open();
                    string sql = "INSERT INTO job (date_start, date_end, time_start, time_end, detail_id, master_id) VALUES (@ds, @de, @ts, @te, @did, @mid)";
                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("ds", DateTime.Parse(row.Cells["date_start"].Value.ToString()));
                        cmd.Parameters.AddWithValue("de", DateTime.Parse(row.Cells["date_end"].Value.ToString()));
                        cmd.Parameters.AddWithValue("ts", TimeSpan.Parse(row.Cells["time_start"].Value.ToString()));
                        cmd.Parameters.AddWithValue("te", TimeSpan.Parse(row.Cells["time_end"].Value.ToString()));
                        cmd.Parameters.AddWithValue("did", int.Parse(row.Cells["detail_id"].Value.ToString()));
                        cmd.Parameters.AddWithValue("mid", int.Parse(row.Cells["master_id"].Value.ToString()));
                        cmd.ExecuteNonQuery();
                    }
                    conn.Close();

                }
                MessageBox.Show("Запись добавлена!", "Успех");
                LoadTable();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка:\n" + ex.Message, "Ошибка");
            }
        }

        private void ViewTable(object sender, EventArgs e)
        {
            Form3 form3 = new Form3();
            form3.Show();
            this.Hide();
        }

        private void DeleteData(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;

            int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells["id"].Value);

            if (MessageBox.Show("Удалить запись?", "Подтверждение", MessageBoxButtons.YesNo) != DialogResult.Yes) return;

            try
            {
                using (var conn = new NpgsqlConnection(Program.connString))
                {
                    conn.Open();
                    using (var cmd = new NpgsqlCommand("DELETE FROM job WHERE id = @id", conn))
                    {
                        cmd.Parameters.AddWithValue("id", id);
                        cmd.ExecuteNonQuery();
                    }
                    conn.Close();

                }
                MessageBox.Show("Запись удалена!", "Успех");
                LoadTable();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка:\n" + ex.Message, "Ошибка");
            }
        }

        private void UpdateData(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;

            var row = dataGridView1.CurrentRow;
            int id = Convert.ToInt32(row.Cells["id"].Value);

            try
            {
                using (var conn = new NpgsqlConnection(Program.connString))
                {
                    conn.Open();
                    string sql = "UPDATE job SET date_start=@ds, date_end=@de, time_start=@ts, time_end=@te, detail_id=@did, master_id=@mid WHERE id=@id";
                    using (var cmd = new NpgsqlCommand(sql, conn))
                    {
                        cmd.Parameters.AddWithValue("ds", DateTime.Parse(row.Cells["date_start"].Value.ToString()));
                        cmd.Parameters.AddWithValue("de", DateTime.Parse(row.Cells["date_end"].Value.ToString()));
                        cmd.Parameters.AddWithValue("ts", TimeSpan.Parse(row.Cells["time_start"].Value.ToString()));
                        cmd.Parameters.AddWithValue("te", TimeSpan.Parse(row.Cells["time_end"].Value.ToString()));
                        cmd.Parameters.AddWithValue("did", int.Parse(row.Cells["detail_id"].Value.ToString()));
                        cmd.Parameters.AddWithValue("mid", int.Parse(row.Cells["master_id"].Value.ToString()));
                        cmd.Parameters.AddWithValue("id", id);
                        cmd.ExecuteNonQuery();
                    }
                    conn.Close();

                }
                MessageBox.Show("Запись обновлена!", "Успех");
                LoadTable();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка:\n" + ex.Message, "Ошибка");
            }
        }

        private void CreateReport(object sender, EventArgs e)
        {
            try
            {
                string path = "отчёт_job.docx";

                using (var doc = DocX.Create(path))
                {
                    // Заголовок
                    var title = doc.InsertParagraph("Отчёт по таблице Job");
                    title.FontSize(16).Bold();

                    doc.InsertParagraph($"Дата формирования: {DateTime.Now:dd.MM.yyyy HH:mm}");
                    doc.InsertParagraph("");

                    // Таблица
                    var dt = (DataTable)dataGridView1.DataSource;
                    var table = doc.AddTable(dt.Rows.Count + 1, dt.Columns.Count);

                    // Заголовки столбцов
                    for (int col = 0; col < dt.Columns.Count; col++)
                        table.Rows[0].Cells[col].Paragraphs[0].Append(dt.Columns[col].ColumnName).Bold();

                    // Данные
                    for (int row = 0; row < dt.Rows.Count; row++)
                        for (int col = 0; col < dt.Columns.Count; col++)
                            table.Rows[row + 1].Cells[col].Paragraphs[0].Append(dt.Rows[row][col]?.ToString() ?? "");

                    doc.InsertTable(table);
                    doc.Save();
                }

                MessageBox.Show($"Отчёт сохранён: {path}", "Успех");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка:\n" + ex.Message, "Ошибка");
            }
        }

        private void SearchInf(object sender, EventArgs e)
        {
            var dt = (DataTable)dataGridView1.DataSource;
            dt.DefaultView.RowFilter = string.IsNullOrEmpty(textBox1.Text)
                ? ""
                : $"master_id = '{textBox1.Text}'";
        }

        private void Closed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }
}
