using RestaurantApp.DAL;
using RestaurantApp.Models;
using System;
using System.Data;
using System.Linq;
using System.Net;
using System.Windows.Forms;

namespace RestaurantApp
{
    public partial class ReservationEditForm : Form
    {
        private ReservationRepository repo = new ReservationRepository();
        private OrderRepository orderRepo = new OrderRepository();
        private EmployeeRepository empRepo = new EmployeeRepository();
        private ClientRepository clientRepo = new ClientRepository();
        private Reservation reservation;
        private bool isEdit = false;

        public ReservationEditForm()
        {
            InitializeComponent();
            isEdit = false;
            reservation = new Reservation();
            this.Text = "Новое бронирование";
            LoadData();
            cmbStatus.SelectedIndex = 0;
            chkNoClient.CheckedChanged += (s, e) => cmbClient.Enabled = !chkNoClient.Checked;

            btnSave.Click += BtnSave_Click;
            btnCancel.Click += (s, e) => DialogResult = DialogResult.Cancel;
        }

        public ReservationEditForm(Reservation existingReservation)
        {
            InitializeComponent();
            isEdit = true;
            reservation = existingReservation;
            this.Text = "Редактирование бронирования";
            LoadData();
            LoadReservationData();

            btnSave.Click += BtnSave_Click;
            btnCancel.Click += (s, e) => DialogResult = DialogResult.Cancel;
        }

        private void LoadData()
        {
            // Загружаем столы
            var tables = orderRepo.GetTables();
            cmbTable.DisplayMember = "info";
            cmbTable.ValueMember = "table_id";
            cmbTable.DataSource = tables;

            // Загружаем официантов
            var employees = empRepo.GetWaiters();
            cmbEmployee.DisplayMember = "FullName";
            cmbEmployee.ValueMember = "EmployeeId";
            cmbEmployee.DataSource = employees;

            // Загружаем клиентов
            var clients = clientRepo.GetAll();
            var clientList = clients.Select(c => new { c.ClientId, FullName = $"{c.LastName} {c.FirstName} ({c.Phone})" }).ToList();
            cmbClient.DisplayMember = "FullName";
            cmbClient.ValueMember = "ClientId";
            cmbClient.DataSource = clientList;

            // Выбираем текущего пользователя как официанта
            if (!string.IsNullOrEmpty(Program.CurrentRole) && Program.CurrentRole == "waiter")
            {
                var currentEmp = employees.FirstOrDefault(e => e.FullName == Program.CurrentUser);
                if (currentEmp != null)
                    cmbEmployee.SelectedValue = currentEmp.EmployeeId;
            }
        }

        private void LoadReservationData()
        {
            cmbTable.SelectedValue = reservation.TableId;
            if (reservation.ClientId.HasValue)
            {
                cmbClient.SelectedValue = reservation.ClientId.Value;
                chkNoClient.Checked = false;
            }
            else
            {
                chkNoClient.Checked = true;
                cmbClient.Enabled = false;
            }
            if (reservation.EmployeeId.HasValue)
                cmbEmployee.SelectedValue = reservation.EmployeeId.Value;
            dtpReservedAt.Value = reservation.ReservedAt;
            numDuration.Value = reservation.DurationMin;
            numGuests.Value = reservation.GuestsCount;
            cmbStatus.Text = reservation.Status;
            txtNotes.Text = reservation.Notes;
        }

        private void SaveData()
        {
            reservation.TableId = (int)cmbTable.SelectedValue;
            reservation.ClientId = chkNoClient.Checked ? (int?)null : (int?)cmbClient.SelectedValue;
            reservation.EmployeeId = (int?)cmbEmployee.SelectedValue;
            reservation.ReservedAt = dtpReservedAt.Value;
            reservation.DurationMin = (int)numDuration.Value;
            reservation.GuestsCount = (int)numGuests.Value;
            reservation.Status = cmbStatus.Text;
            reservation.Notes = txtNotes.Text;

            if (reservation.GuestsCount <= 0)
                throw new Exception("Количество гостей должно быть больше 0");

            if (isEdit)
                repo.Update(reservation);
            else
                repo.Insert(reservation);
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            try
            {
                SaveData();
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}