using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using OneForMe.Data; using OneForMe.Models; namespace OneForMe.Controllers; [Authorize] public class OrderController : Controller { private readonly ApplicationDbContext _context; public OrderController(ApplicationDbContext context) { _context = context; } // GET: Order/Create public IActionResult Create() { return View(); } // POST: Order/Create [HttpPost] public async Task Create(Order order, string[] itemNames, decimal[] itemPrices) { if (!ModelState.IsValid) return View(); order.OrderCode = GenerateOrderCode(); order.CreatorName = User.Identity?.Name ?? "Unknown"; _context.Orders.Add(order); await _context.SaveChangesAsync(); // Add menu items for (int i = 0; i < itemNames.Length; i++) { if (!string.IsNullOrEmpty(itemNames[i]) && itemPrices[i] > 0) { _context.MenuItems.Add(new MenuItem { OrderId = order.Id, Name = itemNames[i], Price = itemPrices[i] }); } } await _context.SaveChangesAsync(); return RedirectToAction("Details", new { code = order.OrderCode }); } // GET: Order/Join public async Task Join(string code) { var order = await _context.Orders .Include(o => o.MenuItems) .Include(o => o.OrderItems) .FirstOrDefaultAsync(o => o.OrderCode == code); if (order == null) return NotFound("Order not found"); if (order.IsClosed) return BadRequest("This order is closed"); return View(order); } // POST: Order/AddItem [HttpPost] public async Task AddItem(int orderId, int menuItemId, int quantity, string participantName, string? participantEmail) { var order = await _context.Orders.FindAsync(orderId); if (order == null || order.IsClosed) return BadRequest("Order not found or is closed"); var menuItem = await _context.MenuItems.FindAsync(menuItemId); if (menuItem == null) return BadRequest("Menu item not found"); var orderItem = new OrderItem { OrderId = orderId, MenuItemId = menuItemId, Quantity = quantity, ParticipantName = participantName, ParticipantEmail = participantEmail }; _context.OrderItems.Add(orderItem); await _context.SaveChangesAsync(); return RedirectToAction("Join", new { code = order.OrderCode }); } // GET: Order/Details/{code} public async Task Details(string code) { var order = await _context.Orders .Include(o => o.MenuItems) .Include(o => o.OrderItems) .FirstOrDefaultAsync(o => o.OrderCode == code); if (order == null) return NotFound(); return View(order); } private string GenerateOrderCode() { return Guid.NewGuid().ToString().Substring(0, 8).ToUpper(); } }