using Microsoft.AspNetCore.Mvc;
using Aberwyn.Data;
using Aberwyn.Models;
using System.Linq;

namespace Aberwyn.Controllers
{
    public class PizzaController : Controller
    {
        private readonly MenuService _menuService;
        private readonly ApplicationDbContext _context;

        public PizzaController(MenuService menuService, ApplicationDbContext context)
        {
            _menuService = menuService;
            _context = context;
        }

        [HttpGet]
        public IActionResult Order()
        {
            var pizzas = _menuService.GetMeals()
                .Where(m => m.Name.ToLower().Contains("pizza"))
                .OrderBy(m => m.Name)
                .ToList();

            var orders = _context.PizzaOrders
                .OrderByDescending(o => o.OrderedAt)
                .ToList();

            ViewBag.Pizzas = pizzas;
            ViewBag.ExistingOrders = orders;
            return View();
        }

        [HttpPost]
        public IActionResult Order(string customerName, string pizzaName)
        {
            if (string.IsNullOrWhiteSpace(customerName) || string.IsNullOrWhiteSpace(pizzaName))
            {
                TempData["Error"] = "Både namn och pizza måste anges.";
                return RedirectToAction("Order");
            }

            var order = new PizzaOrder
            {
                CustomerName = customerName.Trim(),
                PizzaName = pizzaName.Trim()
            };

            _context.PizzaOrders.Add(order);
            _context.SaveChanges();

            TempData["Success"] = "Beställningen har lagts!";
            return RedirectToAction("Order");
        }
    }
}
