context: using CmsData;
  using CmsData.Codes;
  using CmsData.Registration;
  using CmsWeb.Areas.Search.Models;
  using CmsWeb.Code;
  using CmsWeb.Lifecycle;
  using Dapper;
  using Newtonsoft.Json;
  using System;
  using System.Linq;
  using System.Text.RegularExpressions;
  using System.Web.Mvc;
  using UtilityExtensions;
  
  namespace CmsWeb.Areas.Search.Controllers
  {
      [SessionExpire]
      [RouteArea("Org", AreaPrefix = "OrgSearch"), Route("{action=index}/{id?}")]
      public class OrgSearchController : CmsStaffController
      {
          private const string STR_OrgSearch = "OrgSearch";
  
          public OrgSearchController(IRequestManager requestManager) : base(requestManager)
          {
          }
  
          [Route("~/OrgSearch/{progid:int?}/{div:int?}")]
          public ActionResult Index(int? div, int? progid, int? onlinereg, string name)
          {
              Response.NoCache();
              var m = new OrgSearchModel(CurrentDatabase);
              m.StatusId = OrgStatusCode.Active;
  
              if (name.HasValue())
              {
                  m.Name = name;
                  m.StatusId = null;
              }
              if (onlinereg.HasValue)
              {
                  m.OnlineReg = onlinereg;
              }
  
              if (div.HasValue)
              {
                  m.DivisionId = div;
                  if (progid.HasValue)
                  {
                      m.ProgramId = progid;
                  }
                  else
                  {
                      m.ProgramId = m.Division().ProgId;
                  }
  
                  m.TagProgramId = m.ProgramId;
                  m.TagDiv = div;
              }
              else if (progid.HasValue)
              {
                  m.ProgramId = progid;
                  m.TagProgramId = m.ProgramId;
              }
              else if (Util.OrgSearch.IsNotNull())
              {
                  var search = JsonConvert.DeserializeObject<OrgSearchInfo>(Util.OrgSearch);
                  search.CopyPropertiesTo(m);
              }
  
              return View(m);
          }
  
          [HttpPost]
          public ActionResult Results(OrgSearchModel m)
          {
              Util.OrgSearch = JsonConvert.SerializeObject(new OrgSearchInfo(m));
              return View(m);
          }
  
          [HttpPost]
          public ActionResult DivisionIds(int id)
          {
              var m = new OrgSearchModel(CurrentDatabase) { ProgramId = id };
              return View(m);
          }
  
          [HttpPost]
          public ActionResult TagDivIds(int id)
          {
              var m = new OrgSearchModel(CurrentDatabase) { ProgramId = id };
              return View("DivisionIds", m);
          }
  
          [HttpPost]
          public ActionResult ApplyType(int id, OrgSearchModel m)
          {
              var t = (id == -1 ? (int?)null : id);
              if (t == 0)
              {
                  return Content("");
              }
  
              var ot = CurrentDatabase.OrganizationTypes.SingleOrDefault(tt => tt.Id == id);
              if (t.HasValue || ot != null)
              {
                  var q = from o in CurrentDatabase.Organizations
                          join os in m.FetchOrgs() on o.OrganizationId equals os.OrganizationId
                          select o;
                  foreach (var o in q)
                  {
                      o.OrganizationTypeId = t;
                  }
              }
              else
              {
                  return Content("error: missing type");
              }
  
              CurrentDatabase.SubmitChanges();
              return Content("ok");
          }
  
          [HttpPost]
          public ActionResult MakeChildrenOf(int id, OrgSearchModel m)
          {
              var t = (id == -1 ? (int?)null : id);
              if (t == 0)
              {
                  return Content("");
              }
  
              var org = CurrentDatabase.LoadOrganizationById(id);
              if (t.HasValue || org != null)
              {
                  var q = from o in CurrentDatabase.Organizations
                          join os in m.FetchOrgs() on o.OrganizationId equals os.OrganizationId
                          where o.OrganizationId != id
                          select o;
                  foreach (var o in q)
                  {
                      o.ParentOrgId = t;
                  }
              }
              else
              {
                  return Content("error: missing type");
              }
  
              CurrentDatabase.SubmitChanges();
              return Content("ok");
          }
  
          [HttpPost]
          public ActionResult RenameDiv(int id, int divid, string name)
          {
              var d = CurrentDatabase.Divisions.Single(dd => dd.Id == divid);
              d.Name = name;
              CurrentDatabase.SubmitChanges();
              var m = new OrgSearchModel(CurrentDatabase) { ProgramId = id };
              return View("DivisionIds", m);
          }
  
          [HttpPost]
          public ActionResult MakeNewDiv(int id, string name)
          {
              var d = new Division { Name = name, ProgId = id };
              d.ProgDivs.Add(new ProgDiv { ProgId = id });
              CurrentDatabase.Divisions.InsertOnSubmit(d);
              CurrentDatabase.SubmitChanges();
              var m = new OrgSearchModel(CurrentDatabase) { ProgramId = id, TagDiv = d.Id };
              return View("DivisionIds", m);
          }
  
          [HttpPost]
          public ActionResult DefaultMeetingDate(int id)
          {
              var dt = OrgSearchModel.DefaultMeetingDate(id);
              return Json(new { date = dt.Date.ToShortDateString(), time = dt.ToShortTimeString() });
          }
          [HttpPost]
          public ActionResult ExportExcel(OrgSearchModel m)
          {
              return m.OrganizationExcelList();
          }
          [HttpPost]
          public ActionResult ExportMembersExcel(OrgSearchModel m)
          {
              return m.OrgsMemberList();
          }
          [HttpPost]
          public ActionResult RegOptions(OrgSearchModel m)
          {
              return m.RegOptionsList();
          }
          [HttpPost]
          public ActionResult RegQuestionsUsage(OrgSearchModel m)
          {
              return m.RegQuestionsUsage();
          }
          [HttpPost]
          public ActionResult RegSettingUsages(OrgSearchModel m)
          {
              return m.RegSettingUsages();
          }
          [HttpPost]
          public ActionResult RegSettingsXml(OrgSearchModel m)
          {
              Response.ContentType = "text/xml";
              m.RegSettingsXml(Response.OutputStream);
              return new EmptyResult();
          }
  
          [HttpPost]
          public ActionResult RegMessages(OrgSearchModel m, Settings.Messages messages)
          {
              Response.ContentType = "text/xml";
              m.RegMessagesXml(Response.OutputStream, messages);
              return new EmptyResult();
          }
          [HttpPost]
          public ContentResult Edit(string id, string value)
          {
              var a = id.Split('-');
              var c = new ContentResult();
              c.Content = value;
              var org = CurrentDatabase.LoadOrganizationById(a[1].ToInt());
              if (org == null)
              {
                  return c;
              }
  
              switch (a[0])
              {
                  case "bs":
                      org.BirthDayStart = value.ToDate();
                      break;
                  case "be":
                      org.BirthDayEnd = value.ToDate();
                      break;
                  case "rs":
                      org.RegStart = value.ToDate();
                      break;
                  case "re":
                      org.RegEnd = value.ToDate();
                      break;
                  case "ck":
                      org.CanSelfCheckin = value == "yes";
                      break;
                  case "reg2":
                      org.UseRegisterLink2 = value == "yes";
                      c.Content = org.UseRegisterLink2 == true ? "Family" : "Individual";
                      break;
                  case "so":
                      org.PublicSortOrder = value.HasValue() ? value : null;
                      break;
                  case "ac":
                      if (value == "Other")
                      {
                          value = null;
                      }
  
                      org.AppCategory = value.HasValue() ? value : null;
                      break;
              }
              CurrentDatabase.SubmitChanges();
              return c;
          }
  
          [HttpPost, ValidateInput(false)]
          public ActionResult SetDescription(string id, string description)
          {
              var a = id.Split('-');
              var org = CurrentDatabase.LoadOrganizationById(a[1].ToInt());
              org.Description = description;
              CurrentDatabase.SubmitChanges();
              return Content("ok");
          }
  
          [HttpPost]
          [Route("SqlReport/{report}")]
          public ActionResult SqlReport(OrgSearchModel m, string report, DateTime? dt1 = null, DateTime? dt2 = null)
          {
              try
              {
                  var orgs = m.FetchOrgs();
                  var oids = string.Join(",", orgs.Select(oo => oo.OrganizationId));
                  ViewBag.ExcelUrl = $"/OrgSearch/SqlReportExcel/{report}";
                  ViewBag.DisplayName = report.SpaceCamelCase();
                  ViewBag.OrgIds = oids;
                  ViewBag.dt1 = dt1;
                  ViewBag.dt2 = dt2;
                  var content = CurrentDatabase.ContentOfTypeSql(report);
                  if (content.Contains("pagebreak", ignoreCase: true))
                  {
                      var p = m.GetSqlParameters(oids, dt1, dt2, content);
                      ViewBag.Results = PythonModel.PageBreakTables(CurrentDatabase, content, p);
                      return View();
                  }
                  ViewBag.Results = m.SqlTable(report, oids, dt1, dt2);
                  return View();
              }
              catch (Exception ex)
              {
                  return Message(ex);
              }
          }
          [HttpPost]
          [Route("SqlReportExcel/{report}")]
          public ActionResult SqlReportExcel(string report, string orgIds, DateTime? dt1 = null, DateTime? dt2 = null)
          {
              try
              {
                  var m = new OrgSearchModel(CurrentDatabase);
                  return m.SqlTableExcel(report, orgIds, dt1, dt2);
              }
              catch (Exception ex)
              {
                  return Message(ex);
              }
          }
          [HttpPost]
          public ActionResult ToggleTag(int id, int tagdiv)
          {
              //var Db = Db;
  
gt:             var organization = CurrentDatabase.LoadOrganizationById(id);