using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Mono.TextTemplating; using Newtonsoft.Json; using PSTW_CentralSystem.Areas.Inventory.Models; using PSTW_CentralSystem.DBContext; using PSTW_CentralSystem.Models; using System.ComponentModel.Design; using System.Diagnostics; using System.Reflection; namespace PSTW_CentralSystem.Controllers.API.Inventory { [ApiController] [Route("[controller]")] public class InvMainAPI : Controller { private readonly ILogger _logger; private readonly AuthDBContext _authDbContext; public InvMainAPI(ILogger logger, AuthDBContext authDbContext) { _logger = logger; _authDbContext = authDbContext; } public class DepartmentCompany { public int DepartmentId { get; set; } public string? DepartmentName { get; set; } public int CompanyId { get; set; } public string? CompanyName { get; set; } } public async Task> GetDepartmentWithCompanyList() { var departmentList = await _authDbContext.Departments.ToListAsync(); var companyList = await _authDbContext.Companies.ToListAsync(); // Create a new list to store departments with their company name var departmentWithCompanyList = departmentList.Select(department => new DepartmentCompany { DepartmentId = department.DepartmentId, DepartmentName = department.DepartmentName, CompanyId = department.CompanyId, CompanyName = companyList.FirstOrDefault(company => company.CompanyId == department.CompanyId)?.CompanyName }).ToList(); // Return the constructed list as JSON return departmentWithCompanyList; } public async Task GetDepartmentWithCompany(int companyId, int departmentId) { var departmentList = await _authDbContext.Departments.FirstOrDefaultAsync(d => d.DepartmentId == departmentId ); var companyList = await _authDbContext.Companies.FirstOrDefaultAsync(c => c.CompanyId == companyId); // Create a new list to store departments with their company name var departmentWithCompany = new DepartmentCompany { DepartmentId = departmentList.DepartmentId, DepartmentName = departmentList.DepartmentName, CompanyId = departmentList.CompanyId, CompanyName = companyList?.CompanyName }; // Return the constructed list as JSON return departmentWithCompany; } #region Manufacturer [HttpPost("ManufacturerList")] public async Task ManufacturerList() { var manifacturerList = await _authDbContext.Manufacturers.ToListAsync(); return Json(manifacturerList); } [HttpPost("AddManufacturer")] public async Task AddManufacturer([FromBody] ManufacturerModel manufacturer) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (manufacturer == null) { return NotFound("Manufacturer is null"); } try { _authDbContext.Manufacturers.Add(new ManufacturerModel { ManufacturerName = manufacturer.ManufacturerName, }); await _authDbContext.SaveChangesAsync(); var updatedList = await _authDbContext.Manufacturers.ToListAsync(); return Json(updatedList); } catch (Exception ex) { return BadRequest(ex.Message); } } [HttpDelete("DeleteManufacturer/{id}")] public async Task DeleteManufacturer(int id) { var manufacturer = await _authDbContext.Manufacturers.FindAsync(id); if (manufacturer == null) { return NotFound(new { success = false, message = "Manufacturer not found" }); } _authDbContext.Manufacturers.Remove(manufacturer); await _authDbContext.SaveChangesAsync(); return Ok(new { success = true, message = "Manufacturer deleted successfully" }); } #endregion Manufacturer #region Product [HttpPost("ProductList")] public async Task ProductList() { var productList = await _authDbContext.Products.Include("Manufacturer").ToListAsync(); return Json(productList); } [HttpPost("ProductListWithItem")] public async Task ProductListWithItem() { var productList = await _authDbContext.Products .Include(p => p.Items) // Include related items .Include(p => p.Manufacturer) // Include related manufacturer .ToListAsync(); return Json(productList); } [HttpPost("AddProduct")] public async Task AddProduct([FromBody] ProductModel product) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (product == null) { return NotFound("Product is null"); } try { product.QuantityProduct = 0; var productImage = product.ImageProduct; // Save image to wwwroot/media/inventory/images | Images name is product.ModelNo | product.ImageProduct is in base64 string if (!string.IsNullOrEmpty(product.ImageProduct)) { var bytes = Convert.FromBase64String(product.ImageProduct); var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/media/inventory/images", product.ModelNo + ".jpg"); await System.IO.File.WriteAllBytesAsync(filePath, bytes); product.ImageProduct = "/media/inventory/images/" + product.ModelNo + ".jpg"; } _authDbContext.Products.Add(product); await _authDbContext.SaveChangesAsync(); var updatedList = await _authDbContext.Products.Include("Manufacturer").Where(x => x.ManufacturerId == x.ManufacturerId).ToListAsync(); return Json(updatedList); } catch (Exception ex) { return BadRequest(ex.Message); } } [HttpDelete("DeleteProduct/{id}")] public async Task DeleteProduct(int id) { var Product = await _authDbContext.Products.FindAsync(id); if (Product == null) { return NotFound(new { success = false, message = "Product not found" }); } _authDbContext.Products.Remove(Product); await _authDbContext.SaveChangesAsync(); return Ok(new { success = true, message = "Product deleted successfully" }); } #endregion Product #region Company [HttpPost("CompanyDepartmentList")] public async Task CompanyDepartmentList() { var companyList = await _authDbContext.Companies .Include(c => c.Departments) .Select(c => new { c.CompanyId, c.CompanyName, Departments = c.Departments .OrderBy(d => d.DepartmentId) .Select(d => new { d.DepartmentId, d.DepartmentName }) }) .ToListAsync(); return Json(companyList); } #endregion Company #region Department [HttpPost("DepartmentCompanyList")] public async Task DepartmentCompanyList() { var itemDepartment = await _authDbContext.Departments .Include(d => d.Company) // Include the related Company entity .Select(d => new { d.DepartmentId, d.DepartmentName, d.CompanyId, d.Company.CompanyName, }) .ToListAsync(); //return Json(await GetDepartmentWithCompanyList()); return Json(itemDepartment); } #endregion Department #region Supplier [HttpPost("SupplierList")] public async Task SupplierList() { var supplierList = await _authDbContext.Suppliers.ToListAsync(); return Json(supplierList); } #endregion Supplier #region Item [HttpPost("ItemList")] public async Task ItemList() { var itemList = await _authDbContext.Items.ToListAsync(); return Json(itemList); } [HttpPost("AddItem")] public async Task AddItem([FromBody] ItemModel item) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (item == null) { return NotFound("Item is null"); } try { var companyDepartment = await GetDepartmentWithCompany(item.CompanyId, item.DepartmentId); var itemProduct = _authDbContext.Products.Where(p => p.ProductId == item.ProductId).FirstOrDefault(); string? companyInitial = companyDepartment?.CompanyName?.ToString().Substring(0, 1).ToUpper(); string? depatmentInitial = companyDepartment?.DepartmentName?.ToString().Substring(0, 1).ToUpper(); char? initialCategory = itemProduct?.Category.ToString().Substring(0, 1).ToUpper().FirstOrDefault(); string? productId = itemProduct?.ProductId.ToString("D3"); string? itemId = item?.ItemID+1.ToString("D5"); var uniqueId = companyInitial+depatmentInitial+initialCategory+productId+itemId?.ToUpper(); _authDbContext.Items.Add(item); await _authDbContext.SaveChangesAsync(); var updatedItem = await _authDbContext.Items.Select(i => new { i.ItemID, i.UniqueID, i.CompanyId, i.DepartmentId, i.ProductId, i.SerialNumber, i.Quantity, i.Supplier, i.PurchaseDate, i.PONo, i.Currency, i.PriceInRM, i.CurrencyRate, i.ConvertPrice, i.DODate, i.Warranty, i.EndWDate, i.InvoiceDate, }).FirstOrDefaultAsync(i => i.ItemID == item.ItemID); updatedItem.UniqueID = uniqueId; _authDbContext.Items.Add(item); await _authDbContext.SaveChangesAsync(); return Json(updatedItem); } catch (Exception ex) { return BadRequest(ex.Message); } } [HttpDelete("DeleteItem/{id}")] public async Task DeleteItem(int id) { var item = await _authDbContext.Items.FindAsync(id); if (item == null) { return NotFound(new { success = false, message = "Item not found" }); } _authDbContext.Items.Remove(item); await _authDbContext.SaveChangesAsync(); return Ok(new { success = true, message = "Item deleted successfully" }); } #endregion Item } }