using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Aberwyn.Models;
using System.Threading.Tasks;
using Aberwyn.Data;

namespace Aberwyn.Controllers
{
    [Authorize]
    public class UserController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly ApplicationDbContext _context;

        public UserController(UserManager<ApplicationUser> userManager, ApplicationDbContext context)
        {
            _userManager = userManager;
            _context = context;
        }

        [HttpGet]
        public async Task<IActionResult> Profile()
        {
            var user = await _userManager.GetUserAsync(User);
            var prefs = await _context.UserPreferences.FindAsync(user.Id) ?? new UserPreferences();

            var model = new UserProfileViewModel
            {
                Name = user.UserName,
                Email = user.Email,
                NotifyPizza = prefs.NotifyPizza,
                NotifyMenu = prefs.NotifyMenu,
                NotifyBudget = prefs.NotifyBudget
            };

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> SaveProfile(UserProfileViewModel model)
        {
            var user = await _userManager.GetUserAsync(User);
            var prefs = await _context.UserPreferences.FindAsync(user.Id);

            if (prefs == null)
            {
                prefs = new UserPreferences { UserId = user.Id };
                _context.UserPreferences.Add(prefs);
            }

            prefs.NotifyPizza = model.NotifyPizza;
            prefs.NotifyMenu = model.NotifyMenu;
            prefs.NotifyBudget = model.NotifyBudget;

            await _context.SaveChangesAsync();

            return RedirectToAction("Profile");
        }
    }
}
