using Data.SeaHavenIndustries; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Api.SeaHavenIndustries.Controllers { [Authorize] [ApiController] [Route("api/[controller]")] public class DropdownOptionsController : Controller { private readonly ApplicationDbContext _db; public DropdownOptionsController(ApplicationDbContext db) { _db = db; } [HttpGet] public async Task GetAll([FromQuery] string? category = null) { var query = _db.DropdownOptions.Where(d => d.IsActive); if (!string.IsNullOrWhiteSpace(category)) query = query.Where(d => d.Category == category); var data = await query.OrderBy(d => d.Category).ThenBy(d => d.SortOrder).ThenBy(d => d.Value).ToListAsync(); return Ok(data); } [HttpGet("ByCategory/{category}")] public async Task GetByCategory(string category, [FromQuery] string? parent = null) { var query = _db.DropdownOptions.Where(d => d.IsActive && d.Category == category); if (!string.IsNullOrWhiteSpace(parent)) query = query.Where(d => d.ParentValue == parent); var data = await query.OrderBy(d => d.SortOrder).ThenBy(d => d.Value).ToListAsync(); return Ok(data); } [HttpPost] public async Task Create([FromBody] DropdownOption model) { if (string.IsNullOrWhiteSpace(model.Category) || string.IsNullOrWhiteSpace(model.Value)) return BadRequest(new { message = "Category and Value are required" }); var existing = await _db.DropdownOptions .AnyAsync(d => d.Category == model.Category && d.Value == model.Value && d.ParentValue == model.ParentValue); if (existing) return BadRequest(new { message = "This option already exists" }); model.Id = 0; model.IsActive = true; _db.DropdownOptions.Add(model); await _db.SaveChangesAsync(); return Ok(model); } [HttpPut("{id}")] public async Task Update(int id, [FromBody] DropdownOption model) { var item = await _db.DropdownOptions.FindAsync(id); if (item == null) return NotFound(new { message = "Option not found" }); item.Value = model.Value; item.ParentValue = model.ParentValue; item.SortOrder = model.SortOrder; item.IsActive = model.IsActive; await _db.SaveChangesAsync(); return Ok(item); } [HttpDelete("{id}")] public async Task Delete(int id) { var item = await _db.DropdownOptions.FindAsync(id); if (item == null) return NotFound(new { message = "Option not found" }); _db.DropdownOptions.Remove(item); await _db.SaveChangesAsync(); return Ok(new { message = "Deleted" }); } } }