using LearningMaterialSystem.Data;
using LearningMaterialSystem.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LearningMaterialSystem.Controllers;

[Authorize(Roles = "BoPhanChuyenMon")]
public class MonHocsController : Controller
{
    private readonly ApplicationDbContext _context;

    public MonHocsController(ApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<IActionResult> Index()
    {
        var monHocs = await _context.MonHocs.AsNoTracking().ToListAsync();
        return View(monHocs);
    }

    public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(MonHoc monHoc)
    {
        if (!ModelState.IsValid)
        {
            return View(monHoc);
        }

        _context.MonHocs.Add(monHoc);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    public async Task<IActionResult> Edit(int id)
    {
        var monHoc = await _context.MonHocs.FindAsync(id);
        if (monHoc == null)
        {
            return NotFound();
        }

        return View(monHoc);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, MonHoc monHoc)
    {
        if (id != monHoc.Id)
        {
            return NotFound();
        }

        if (!ModelState.IsValid)
        {
            return View(monHoc);
        }

        _context.MonHocs.Update(monHoc);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    public async Task<IActionResult> Delete(int id)
    {
        var monHoc = await _context.MonHocs.FindAsync(id);
        if (monHoc == null)
        {
            return NotFound();
        }

        return View(monHoc);
    }

    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var monHoc = await _context.MonHocs.FindAsync(id);
        if (monHoc != null)
        {
            _context.MonHocs.Remove(monHoc);
            await _context.SaveChangesAsync();
        }

        return RedirectToAction(nameof(Index));
    }
}

