using System;
using System.Windows.Forms;
using RestaurantApp.DAL;
using RestaurantApp.Models;

namespace RestaurantApp
{
    public partial class ClientEditForm : Form
    {
        private ClientRepository repo = new ClientRepository();
        private Client client;
        private bool isEdit = false;

        public ClientEditForm()
        {
            InitializeComponent();
            isEdit = false;
            client = new Client();
            Text = "Новый клиент";
            dtpBirthDate.Value = DateTime.Now.AddYears(-18);

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

        public ClientEditForm(Client existingClient)
        {
            InitializeComponent();
            isEdit = true;
            client = existingClient;
            Text = "Редактирование клиента";
            LoadData();

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

        private void LoadData()
        {
            txtFirstName.Text = client.FirstName;
            txtLastName.Text = client.LastName;
            txtPhone.Text = client.Phone;
            txtEmail.Text = client.Email;
            if (client.BirthDate.HasValue)
                dtpBirthDate.Value = client.BirthDate.Value;
            numBonusPoints.Value = client.BonusPoints;
        }

        private void SaveData()
        {
            client.FirstName = txtFirstName.Text.Trim();
            client.LastName = txtLastName.Text.Trim();
            client.Phone = txtPhone.Text.Trim();
            client.Email = txtEmail.Text.Trim();
            client.BirthDate = dtpBirthDate.Value;
            client.BonusPoints = (int)numBonusPoints.Value;

            if (string.IsNullOrWhiteSpace(client.FirstName))
                throw new Exception("Введите имя");
            if (string.IsNullOrWhiteSpace(client.LastName))
                throw new Exception("Введите фамилию");

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

        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);
            }
        }
    }
}