File size: 2,451 Bytes
6db0915
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
using ECommerce.Model.Entities;
using ECommerce.Model.Repositories;
using ECommerce.Presenter.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace Ecommerce_web_project.Controllers.Admin;

[Area("Admin")]
[Authorize(Roles = "Admin")]
public class CategoriesController : Controller
{
    private readonly IRepository<Category> _repo;

    public CategoriesController(IRepository<Category> repo) => _repo = repo;

    public async Task<IActionResult> Index()
    {
        var categories = await _repo.GetAllAsync();
        var model = categories.Select(c => new CategoryViewModel
        {
            Id = c.Id,
            Name = c.Name,
            Description = c.Description,
            ImageUrl = c.ImageUrl
        }).ToList();
        return View(model);
    }

    public IActionResult Create() => View();

    [HttpPost]
    public async Task<IActionResult> Create(CategoryViewModel model)
    {
        if (!ModelState.IsValid) return View(model);
        var category = new Category
        {
            Name = model.Name,
            Description = model.Description,
            ImageUrl = model.ImageUrl
        };
        await _repo.AddAsync(category);
        return RedirectToAction(nameof(Index));
    }

    public async Task<IActionResult> Edit(Guid id)
    {
        var category = await _repo.GetByIdAsync(id);
        if (category == null) return NotFound();
        return View(new CategoryViewModel
        {
            Id = category.Id,
            Name = category.Name,
            Description = category.Description,
            ImageUrl = category.ImageUrl
        });
    }

    [HttpPost]
    public async Task<IActionResult> Edit(CategoryViewModel model)
    {
        if (!ModelState.IsValid) return View(model);
        var category = await _repo.GetByIdAsync(model.Id);
        if (category == null) return NotFound();
        category.Name = model.Name;
        category.Description = model.Description;
        category.ImageUrl = model.ImageUrl;
        category.UpdatedAt = DateTime.UtcNow;
        await _repo.UpdateAsync(category);
        return RedirectToAction(nameof(Index));
    }

    [HttpPost]
    public async Task<IActionResult> Delete(Guid id)
    {
        var category = await _repo.GetByIdAsync(id);
        if (category == null) return NotFound();
        await _repo.DeleteAsync(category);
        return RedirectToAction(nameof(Index));
    }
}