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 OrderEditForm : Form
    {
        private OrderRepository repo = new OrderRepository();
        private EmployeeRepository empRepo = new EmployeeRepository();
        private ClientRepository clientRepo = new ClientRepository();

        public OrderEditForm()
        {
            InitializeComponent();
            LoadData();

            chkNoClient.CheckedChanged += (s, e) =>
            {
                cmbClient.Enabled = !chkNoClient.Checked;
                if (chkNoClient.Checked) cmbClient.SelectedIndex = -1;
            };

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

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

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

            // Загружаем клиентов
            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 currentWaiter = waiters.FirstOrDefault(w => w.FullName == Program.CurrentUser);
                if (currentWaiter != null)
                    cmbWaiter.SelectedValue = currentWaiter.EmployeeId;
            }
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            if (cmbTable.SelectedItem == null)
            {
                MessageBox.Show("Выберите стол");
                return;
            }

            if (cmbWaiter.SelectedItem == null)
            {
                MessageBox.Show("Выберите официанта");
                return;
            }

            var order = new Order
            {
                TableId = (int)cmbTable.SelectedValue,
                EmployeeId = (int)cmbWaiter.SelectedValue,
                ClientId = chkNoClient.Checked ? (int?)null : (int?)cmbClient.SelectedValue,
                DiscountPct = numDiscount.Value
            };

            try
            {
                int orderId = repo.InsertOrder(order);
                DialogResult = DialogResult.OK;
                Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Ошибка: {ex.Message}");
            }
        }
    }
}