using Microsoft.AspNetCore.Mvc;
using System.Net;
using clivelancaster.Models;
using MailKit.Net.Smtp;
using MimeKit;
using System.Xml.Linq;

namespace clivelancaster.Controllers
{
    public class ContactController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        private readonly IConfiguration _configuration;

        public ContactController(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        [HttpPost]
        public async Task<IActionResult> Index(ContactFormModel model)
        {
            if (ModelState.IsValid)
            {
                // Build the email message
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Clive", "clivelancaster@gmail.com"));
                message.To.Add(new MailboxAddress("Clive", "clivelancaster@gmail.com"));
                message.Subject = "Website: Contact Form - clivelancaster.com";

                var bodyBuilder = new BodyBuilder
                {
                    TextBody = $"Name: {model.NameIncognito}\nEmail: {model.Email}\n\nSubject: {model.SubjectIncognito}\n\nMessage:\n{model.MessageIncognito}"
                };

                message.Body = bodyBuilder.ToMessageBody();

                // Honeypot Check
                if (model.Name != null | model.Subject != null | model.Message != null)
                {
                    ViewBag.Message = "Message sent successfully!";
                }
                else
                {
                    try
                    {
                        using (var client = new SmtpClient())
                        {
                            // Retrieve SMTP settings from appsettings.json
                            var smtpHost = _configuration["SmtpSettings:Host"];
                            int smtpPort = int.Parse(s: _configuration["SmtpSettings:Port"]);
                            var smtpUsername = _configuration["SmtpSettings:Username"];
                            var smtpPassword = _configuration["SmtpSettings:Password"];

                            client.Connect(smtpHost, smtpPort, true);
                            client.Authenticate(smtpUsername, smtpPassword);
                            await client.SendAsync(message);
                            client.Disconnect(true);
                        }

                        ViewBag.Message = "Message sent successfully!";
                    }
                    catch
                    {
                        ViewBag.Message = "Error sending message.";
                    }
                }

                return View();
            }

            return View(model);
        }
    }
}