using Data; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.Web.CodeGenerators.Mvc.Templates.BlazorIdentity.Pages.Manage; using Model; using Newtonsoft.Json; using Services.EmailSend; using Services.Interaces; using System.Globalization; using System.Security.Cryptography; using System.Text; using Web.ViewModel.AnswerVM; using Web.ViewModel.QuestionnaireVM; using Web.ViewModel.QuestionVM; namespace Web.Controllers { public class QuestionnaireResponseController : Controller { private readonly IQuestionnaireRepository _questionnaireRepository; private readonly SurveyContext _context; private readonly IEmailServices _emailServices; public QuestionnaireResponseController(IQuestionnaireRepository questionnaireRepository,SurveyContext context, IEmailServices emailServices) { _questionnaireRepository = questionnaireRepository; _context = context; _emailServices = emailServices; } public IActionResult Index() { return View(); } public IActionResult Error() { ViewBag.ErrorMessage = "The survey link has expired. request a new link."; return View(); } public IActionResult DisplayQuestionnaire(int id,string t,string E) { // Check if the token is null or empty if (string.IsNullOrEmpty(t)) { ViewBag.ErrorMessage = "The URL is invalid. Please provide a valid token."; return View("Error"); } // Split the token to extract the expiration date and time string[] tokenParts = t.Split('|'); if (tokenParts.Length != 2) { ViewBag.ErrorMessage = "The URL is invalid. Please provide a valid token."; return View("Error"); } string expiryDateTimeString = tokenParts[1]; // Parse the expiration datetime in UTC format if (!DateTime.TryParseExact(expiryDateTimeString, "yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out DateTime expiryDateTimeUtc)) { ViewBag.ErrorMessage = "The URL is invalid. Please provide a valid token."; return View("Error"); } // Convert the expiration datetime to local time DateTime expiryDateTimeLocal = expiryDateTimeUtc.ToLocalTime(); // Check if the token is expired (accounting for UTC+2 offset) if (expiryDateTimeLocal < DateTime.Now.AddHours(2)) { return RedirectToAction(nameof(Error)); } bool hasAlreadyResponded = _context.Responses.Any(r => r.QuestionnaireId == id && r.UserEmail == E); if (hasAlreadyResponded) { // Retrieve the first username associated with the email, if available var userName = _context.Responses.Where(x => x.UserEmail == E) .Select(x => x.UserName) .FirstOrDefault(); // This ensures you get a single result or null // Ensure userName is not null or empty to use in the message if (!string.IsNullOrEmpty(userName)) { TempData["ErrorMessage"] = $"{userName}"; } else { TempData["ErrorMessage"] = "You have already taken this survey."; } return RedirectToAction(nameof(SubmittedSurvey)); } // Retrieve the questionnaire using the numeric ID var questionnaire = _questionnaireRepository.GetQuestionnaireWithQuestionAndAnswer(id); return View(MapToViewModel(questionnaire)); } [HttpPost] public IActionResult DisplayQuestionnaire([FromForm] ResponseQuestionnaireViewModel questionnaire) { bool hasSubmitted = _context.Responses.Any(r => r.QuestionnaireId == questionnaire.Id && r.UserEmail == questionnaire.Email); var response = new Response { QuestionnaireId = questionnaire.Id, UserName = questionnaire.UserName, UserEmail = questionnaire.Email, SubmissionDate = DateTime.UtcNow, ResponseDetails = questionnaire.Questions.Select(q => new ResponseDetail { QuestionId = q.Id, QuestionType=q.Type, // Handle TextResponse based on question type TextResponse = (q.Type == QuestionType.Open_ended || q.Type == QuestionType.Text || q.Type==QuestionType.Slider) ? string.Join(" ", q.SelectedText) // Ensure SelectedText is appropriately used based on question type : null, ResponseAnswers = q.SelectedAnswerIds .Select(aid => new ResponseAnswer { AnswerId = aid }) .ToList() // Ensure that the list is initialized correctly }).ToList() }; _context.Responses.Add(response); _context.SaveChanges(); var subject = $"Thank You for Your Feedback, {questionnaire.UserName}!"; var toEmail = questionnaire.Email; string emailBody = $@"
Thank you so much for taking the time to provide us with your valuable feedback!
If you have any more thoughts to share or need assistance, please don't hesitate to reach out. You can email us directly at seo@seosoft.dk, and we'll be more than happy to help.
Thank you once again, {questionnaire.UserName}, for helping us make SeoSoft ApS even better. We truly value your support and participation.
Søren Eggert Lundsteen Olsen
Seosoft ApS