using Lada.Framework.DTO;
using ladaexpress.vn.Infrastructures.DTO.Models.Service;
using ladaexpress.vn.Infrastructures.DTO.Results.Crm;
using ladaexpress.vn.Infrastructures.Services;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace ladaexpress.vn.Controllers
{
    public class LeadController : Controller
    {
        private readonly ILeadService _leadService;

        public LeadController(ILeadService leadService)
        {
            _leadService = leadService;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<JsonResult> SendAsync(LeadModel model, string returnUrl = null)
        {
            var result = new LeadResult();
            if (!ModelState.IsValid)
            {
                var errors = ModelState
                                       .Where(x => x.Value.Errors.Count > 0)
                                       .ToDictionary(
                                           kvp => kvp.Key,
                                           kvp => kvp.Value.Errors[0].ErrorMessage
                                       );

                return Json(new { success = false, errors });
            }

            // Thực hiện lưu thông tin tại đây

            TempData["LeadInfo"] = JsonConvert.SerializeObject(model);

            // Fix for CS8601: Possible null reference assignment
            model.SourcePath = HttpContext.Request.Headers.Referer.ToString() ?? string.Empty;

            result = await _leadService.Create(model);

            return Json(new { success = true, redirectUrl = "/lien-he-thanh-cong" });
        }

        public ActionResult ThankYou()
        {
            return View();
        }
    }
}
