using Npgsql;
using System;
using System.Data;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;

namespace ZhkhApp
{
    public partial class LogForm : Form
    {
        public LogForm()
        {
            InitializeComponent();
            LoadLog();
        }

        private void LoadLog()
        {
            try
            {
                string query = @"
                    SELECT log_id, table_name, operation, changed_by, record_id, change_date
                    FROM operation_log
                    ORDER BY change_date DESC
                    LIMIT 500";

                using (var conn = new NpgsqlConnection(MainForm.ConnectionString))
                {
                    conn.Open();
                    using (var adapter = new NpgsqlDataAdapter(query, conn))
                    {
                        DataTable dt = new DataTable();
                        adapter.Fill(dt);
                        dgvLog.DataSource = dt;
                    }
                }

                // Установка заголовков
                if (dgvLog.Columns["log_id"] != null)
                    dgvLog.Columns["log_id"].HeaderText = "ID";
                if (dgvLog.Columns["table_name"] != null)
                    dgvLog.Columns["table_name"].HeaderText = "Таблица";
                if (dgvLog.Columns["operation"] != null)
                    dgvLog.Columns["operation"].HeaderText = "Операция";
                if (dgvLog.Columns["changed_by"] != null)
                    dgvLog.Columns["changed_by"].HeaderText = "Пользователь";
                if (dgvLog.Columns["record_id"] != null)
                    dgvLog.Columns["record_id"].HeaderText = "ID записи";
                if (dgvLog.Columns["change_date"] != null)
                    dgvLog.Columns["change_date"].HeaderText = "Дата/время";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка загрузки журнала: {ex.Message}");
            }
        }

        private void BtnRefresh_Click(object sender, EventArgs e)
        {
            LoadLog();
        }

        private void BtnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}