context: using CmsData.Codes;
  using CmsWeb.Code;
  using CmsWeb.Lifecycle;
  using CmsWeb.Models;
  using System;
  using System.Linq;
  // Used for HTML Image Capture
  using System.Web;
  using System.Web.Mvc;
  using CmsWeb.Areas.Main.Models;
  using CmsWeb.Areas.Manage.Models;
  using Newtonsoft.Json;
  using UtilityExtensions;
  using Content = CmsData.Content;
  using HtmlDocument = HtmlAgilityPack.HtmlDocument;
  
  namespace CmsWeb.Areas.Manage.Controllers
  {
      [Authorize(Roles = "Admin,Design")]
      [ValidateInput(false)]
      [RouteArea("Manage", AreaPrefix = "Display"), Route("{action}/{id?}")]
      public class DisplayController : CmsStaffController
      {
          public DisplayController(IRequestManager requestManager) : base(requestManager)
          {
          }
  
          [Route("~/Display")]
          [Route("~/Manage/Display")]
          public ActionResult Index()
          {
              return View(new ContentModel(CurrentDatabase));
          }
  
          [HttpPost]
          public ActionResult SetContentKeywordFilter(string keywordfilter, string tab)
          {
              if (keywordfilter.HasValue())
              {
                  Util.ContentKeywordFilter = keywordfilter.Trim();
              }
              else
              {
                  Util.ContentKeywordFilter = null;
              }
  
              return Redirect($"/Display#tab_{tab}");
          }
  
          [HttpPost]
          public ActionResult SetContentEmailTemplatesFilter(string tab, string rolesfilter, string emailTemplateDisplayTypesFilter)
          {
              if (rolesfilter.HasValue())
              {
                  Util.ContentRolesFilter = rolesfilter.Trim();
              }
              else
              {
                  Util.ContentRolesFilter = null;
              }
              if (emailTemplateDisplayTypesFilter.HasValue())
              {
                  Util.ContentEmailTemplateDisplayTypesFilter = emailTemplateDisplayTypesFilter.Trim();
              }
              else
              {
                  Util.ContentEmailTemplateDisplayTypesFilter = null;
              }
  
              return Redirect($"/Display#tab_{tab}");
          }
  
          public ActionResult ContentEdit(int? id, bool? snippet)
          {
              if (!id.HasValue)
              {
                  throw new HttpException(404, "No ID found.");
              }
  
              var q = from c in CurrentDatabase.Contents
                      where c.Id == id.Value
                      select new { content = c, keywords = string.Join(",", c.ContentKeyWords.Select(vv => vv.Word)) };
              var i = q.SingleOrDefault();
              if (i == null)
              {
                  throw new HttpException(404, "No ID found.");
              }
  
              if (snippet == true)
              {
                  i.content.Snippet = true;
                  CurrentDatabase.SubmitChanges();
              }
              ViewBag.ContentKeywords = i.keywords;
              if (ContentTypeCode.IsUnlayer(i.content.TypeID))
              {
                  ViewBag.TemplateId = id;
                  return View("UnLayerCompose", i.content);
              }
              return RedirectEdit(i.content);
          }
  
          public ActionResult Content(int? id)
          {
              if (!id.HasValue)
              {
                  throw new HttpException(404, "No ID found.");
              }
  
              var content = CurrentDatabase.ContentFromID(id.Value);
              if (content == null)
              {
                  throw new HttpException(404, "No ID found.");
              }
  
              return Content(content.Body);
          }
  
          [HttpPost]
          public ActionResult ContentCreate(int newType, string newName, int? newRole, bool? useUnlayer)
          {
              var content = new Content();
              content.Name = newName;
              if (!content.Name.HasValue())
                  content.Name = "new template " + DateTime.Now.FormatDateTm();
              content.TypeID = newType == ContentTypeCode.TypeEmailTemplate && useUnlayer == true
                  ? ContentTypeCode.TypeUnlayerTemplate
                  : newType;
              content.RoleID = newRole ?? 0;
              content.Body = "";
              content.Title = "";
              content.DateCreated = DateTime.Now;
              content.CreatedBy = Util.UserName;
              var ContentKeywordFilter = Util.ContentKeywordFilter;
              if (ContentKeywordFilter.HasValue())
              {
                  content.SetKeyWords(CurrentDatabase, new[] { ContentKeywordFilter });
              }
              var tid = EmailTemplatesModel.FetchTemplateByName("Empty Template", CurrentDatabase).Id;
              if (ContentTypeCode.EmailTemplates.Contains(content.TypeID))
                  content.Id = tid;
  
              CurrentDatabase.Contents.InsertOnSubmit(content);
              CurrentDatabase.SubmitChanges();
              ViewBag.ContentKeywords = ContentKeywordFilter ?? "";
  
              if (useUnlayer == true)
              {
                  ViewBag.TemplateId = 0; // force using a blank empty template with only "click here to edit content"
                  return View("UnLayerCompose", content);
              }
  
              return RedirectEdit(content);
          }
  
          [HttpPost]
          [ValidateInput(false)]
          public ActionResult SaveUnlayerTemplateCopy(int saveid, string name, int roleid, string title, string body, string unlayerDesign)
          {
              var m = GetDisplayModel();
              var existing = m.SaveUnlayerTemplateCommon(saveid, name, roleid, title, body, unlayerDesign);
              var content = m.Clone(existing);
              m.SaveThumbnail(body, content);
              CurrentDatabase.Contents.InsertOnSubmit(content);
              CurrentDatabase.SubmitChanges();
              return Redirect($"/Display/ContentEdit/{content.Id}");
          }
  
          [HttpPost]
          [ValidateInput(false)]
          public ActionResult SaveUnlayerTemplate(int? saveid, string name, int roleid, string title, string body, string unlayerDesign)
          {
              var m = GetDisplayModel();
              try
              {
                  var content = m.SaveUnlayerTemplateCommon(saveid, name, roleid, title, body, unlayerDesign);
                  ViewBag.templateID = content.Id;
                  var templatedraft = content.TypeID == ContentTypeCode.TypeUnlayerTemplate ? "emailTemplates" : "savedDrafts";
                  return Redirect($"/Display/#tab_{templatedraft}");
              }
              catch (Exception e)
              {
                  return Content(e.Message);
              }
  
          }
  
          // This method only applies to TypeEmailTemplate
          [HttpPost]
          public ActionResult ContentUpdateCopy(int id, string name, string title, string body, bool? snippet, int? roleid, string contentKeyWords, string stayaftersave = null)
          {
              var m = GetDisplayModel();
              var existing = m.ContentUpdateCommon(id, name, title, body, snippet, roleid, contentKeyWords);
              var content = m.Clone(existing);
              m.SaveThumbnail(body, content);
              CurrentDatabase.Contents.InsertOnSubmit(content);
              CurrentDatabase.SubmitChanges();
              return Redirect($"/Display/ContentEdit/{content.Id}");
          }
  
          [HttpPost]
          public ActionResult ContentUpdate(int id, string name, string title, string body, bool? snippet, int? roleid, string contentKeyWords, string stayaftersave = null)
          {
              var m = GetDisplayModel();
              var content = m.ContentUpdateCommon(id, name, title, body, snippet, roleid, contentKeyWords);
  
              if (content.Name.Equal("CustomReportsMenu"))
              {
                  try
                  {
                      var list = ReportsMenuModel.CustomItems1;
                  }
                  catch (Exception ex)
                  {
                      if (ex is System.Xml.XmlException)
                      {
                          return Content(Util.EndShowMessage(ex.Message, "javascript: history.go(-1)",
                              "There is invalid XML in this document. Go Back to Repair"));
                      }
                  }
              }
              else if (content.Name.Equal("CustomReports"))
              {
                  try
                  {
                      var list = CurrentDatabase.ViewCustomScriptRoles.ToList();
                  }
                  catch (Exception ex)
                  {
  
gt:                     if (ex.Message.Contains("XML parsing", ignoreCase: true))