using System.Data; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using MyDarling.Models; namespace MyDarling.Controllers { [Authorize] public class BundleController : Controller { private DataContext context; private IWebHostEnvironment environment; public BundleController(DataContext context, IWebHostEnvironment environment) { this.environment = environment; this.context = context; } public ActionResult Index() { return View(context.UnderwearBundles.Include(b => b.Figures)); } public ActionResult Create() { return View(); } [HttpPost] public async Task Create([Bind] UnderwearBundle bundle) { try { if (ModelState.IsValid) { await context.UnderwearBundles.AddAsync(bundle); context.SaveChanges(); return RedirectToAction(nameof(Index)); } } catch (DataException) { ModelState.AddModelError("", "Unable to save changes"); } return View(bundle); } public async Task Details(int id) { return View(await context.UnderwearBundles.Include(b => b.Figures).Where(b => b.Id == id).FirstOrDefaultAsync()); } public async Task Edit(int id) { return View(nameof(Details), await context.UnderwearBundles.FindAsync(id)); } [HttpPost] public async Task Edit(int? id) { if (id == null) { return NotFound(); } var bundle = await context.UnderwearBundles.FindAsync(id); if (bundle == null) { return NotFound(); } var file = Request.Form.Files.FirstOrDefault(); if (await TryUpdateModelAsync( bundle, "", b => b.Name, b => b.Description, b => b.Figures, b => b.Price)) { if (file != null) { var newFigure = new Figure(); bundle.Figures.Add(newFigure); newFigure.FilePath = $"/Content/{bundle.Id}/{Guid.NewGuid()}{Path.GetExtension(file.FileName)}"; var savePath = environment.WebRootPath + "/Content/" + bundle.Id + "/"; if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } using var fileStream = new FileStream(environment.WebRootPath + newFigure.FilePath, FileMode.Create); await file.CopyToAsync(fileStream); } try { await context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } catch (System.Exception) { ModelState.AddModelError("", "Unable to save changes"); } } return View(bundle); } [HttpPost] public async Task Delete(int id) { var bundleToDelete = await context.UnderwearBundles.FindAsync(id); if (bundleToDelete == null) { return NotFound(); } try { var bundleDirPath = String.Concat(environment.WebRootPath, "/Content/", bundleToDelete.Id); if (Directory.Exists(bundleDirPath)) { Directory.Delete(bundleDirPath, true); } // foreach (var figure in bundleToDelete.Figures) // { // using FigureController controller = new(context, environment); // await controller.Delete(figure.Id); // } context.UnderwearBundles.Remove(bundleToDelete); await context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } catch (DbUpdateException) { return RedirectToAction(nameof(Delete), new { id = id, saveChangesError = true }); } } } }