using LendWise.Web.Data; using LendWise.Web.Models; using LendWise.Web.Services; using Microsoft.AspNetCore.Mvc; namespace LendWise.Web.Controllers; [Route("apply")] public class ApplyController(AppDbContext db, ProductCatalog catalog, ILogger logger) : Controller { private static readonly string[] ApplicantTypes = ["Salaried", "Self-employed"]; [HttpGet("")] public IActionResult Index(string? product) { var model = new ApplyViewModel { ProductSlug = catalog.Find(product)?.Slug }; return View(model); } [HttpPost("")] [ValidateAntiForgeryToken] public async Task Index(ApplyViewModel model) { // Bots fill the hidden field; send them to the thank-you page without saving anything. if (!string.IsNullOrWhiteSpace(model.Website)) { return RedirectToAction(nameof(Thanks), new { id = 0 }); } if (catalog.Find(model.ProductSlug) is null) { ModelState.AddModelError(nameof(model.ProductSlug), "Choose a loan type."); } if (model.ApplicantType is null || !ApplicantTypes.Contains(model.ApplicantType)) { ModelState.AddModelError(nameof(model.ApplicantType), "Choose one option."); } if (!ModelState.IsValid) { return View(model); } var lead = new LoanLead { FullName = model.FullName.Trim(), Mobile = model.Mobile.Trim(), Email = model.Email.Trim(), City = model.City.Trim(), ApplicantType = model.ApplicantType!, ProductSlug = model.ProductSlug!, Amount = model.Amount ?? 0, MonthlyIncome = model.MonthlyIncome ?? 0, IpAddress = HttpContext.Connection.RemoteIpAddress?.ToString() }; try { db.LoanLeads.Add(lead); await db.SaveChangesAsync(); } catch (Exception ex) { logger.LogError(ex, "Could not save loan application."); ModelState.AddModelError(string.Empty, "We could not save your request just now. Please try again in a few minutes."); return View(model); } return RedirectToAction(nameof(Thanks), new { id = lead.Id }); } [HttpGet("thanks/{id:int}")] public IActionResult Thanks(int id) { ViewData["Reference"] = id > 0 ? $"LW-{id:D6}" : null; return View(); } }