public ContentResult GetSummonReport()
        {
            List <DashboardViewModel> dbvm = new List <DashboardViewModel>();

            List <OfficialTerm> terms = entities.OfficialTerms.OrderBy(m => m.StartYear).ToList();

            foreach (var term in terms)
            {
                if (term.EndYear == null)
                {
                    term.EndYear = DateTime.Now.Year;
                }

                BarangayChairman chairman = entities.BarangayChairmen.Where(m => m.OfficialTermId == term.OfficialTermId).FirstOrDefault();

                dbvm.Add(new DashboardViewModel()
                {
                    ChairmanNames          = chairman.ResidentsInformation.LastName + ", " + chairman.ResidentsInformation.FirstName + ": " + term.StartYear + " to " + term.EndYear,
                    SettledReportsCounts   = entities.Summons.Where(m => m.IncidentDate.Year >= term.StartYear && m.IncidentDate.Year < term.EndYear && m.SummonStatu.Name.ToLower() == "settled").Count(),
                    UnsettledReportsCounts = entities.Summons.Where(m => m.IncidentDate.Year >= term.StartYear && m.IncidentDate.Year < term.EndYear && m.SummonStatu.Name.ToLower() == "unsettled").Count()// The end year is not included as a scope for the chairman
                });
            }

            return(Content(JsonConvert.SerializeObject(dbvm), "application/json"));
        }
        public ActionResult ElectCouncilors()
        {
            try
            {
                TempData["user-profile-photo"] = UserHelper.GetDisplayPicture(User.Identity.GetUserId(), entities);

                // obtain the record that has a null end year, meaning that is the latest term.
                OfficialTerm     officialTerm = entities.OfficialTerms.Where(m => m.EndYear == null).FirstOrDefault();
                BarangayChairman chairman     = entities.BarangayChairmen.Where(m => m.OfficialTermId == officialTerm.OfficialTermId).FirstOrDefault();

                BarangayCounselor chairmanCouncelor = entities.BarangayCounselors.Where(m => m.ChairmanId == chairman.ChairmanId).FirstOrDefault();
                if (chairmanCouncelor != null)
                {
                    TempData["alert-type"]   = "alert-warning";
                    TempData["alert-header"] = "Warning";
                    TempData["alert-msg"]    = "The current Chairman already has its councilors.";
                    return(RedirectToAction("Index", "Dashboard"));
                }

                // Verify first if skChairman has already elected councilors
                // update the view, display the current councilors

                TempData["ChairmanFN"] = chairman.ResidentsInformation.FirstName;
                TempData["ChairmanMN"] = chairman.ResidentsInformation.MiddleName;
                TempData["ChairmanLN"] = chairman.ResidentsInformation.LastName;

                List <string> skCouncilorsId = chairman.SKChairman.SKCouncelors.Select(m => m.ResidentId).ToList();

                int legalYear = DateTime.Now.Date.Year - 18;
                int day       = DateTime.Now.Date.Day;
                int month     = DateTime.Now.Month;
                var residents = entities.ResidentsInformations
                                .Where(m => m.Birthday <= new DateTime(legalYear, month, day) &&
                                       m.ResidentId != chairman.ResidentId &&
                                       !skCouncilorsId.Contains(m.ResidentId) &&
                                       m.ResidentId != chairman.SKChairman.ResidentId)
                                .ToList();

                return(View(residents));
            }
            catch (Exception e)
            {
                TempData["alert-type"]   = "alert-danger";
                TempData["alert-header"] = "Error";
                TempData["alert-msg"]    = "Something went wrong, please try again later.";
                return(View());
            }
        }
        public ActionResult AssignSpecialOfficials()
        {
            try
            {
                TempData["user-profile-photo"] = UserHelper.GetDisplayPicture(User.Identity.GetUserId(), entities);

                OfficialTerm term = null;

                term = entities.OfficialTerms.Where(m => m.EndYear == null).FirstOrDefault();
                // if there is no null endyear record, then retrieve the highest end year. It is the latest record
                if (term == null)
                {
                    term = entities.OfficialTerms.OrderByDescending(m => m.EndYear).FirstOrDefault();
                }

                BarangayChairman chairman = entities.BarangayChairmen.Where(m => m.OfficialTermId == term.OfficialTermId).FirstOrDefault();

                string        chairmanId     = chairman.ResidentId;
                List <string> councelorIds   = chairman.BarangayCounselors.Select(m => m.ResidentId).ToList();
                string        skChairmanId   = chairman.SKChairman.ResidentId;
                List <string> skCouncelorIds = chairman.SKChairman.SKCouncelors.Select(m => m.ResidentId).ToList();
                List <string> specialPos     = chairman.AssignedOfficials.Select(m => m.ResidentId).ToList();

                TempData["Positions"] = entities.AssignedPositions.ToList();

                int legalYear = DateTime.Now.Date.Year - 18;
                int day       = DateTime.Now.Date.Day;
                int month     = DateTime.Now.Month;
                var residents = entities.ResidentsInformations
                                .Where(m => m.Birthday <= new DateTime(legalYear, month, day) &&
                                       m.ResidentId != chairmanId &&
                                       !councelorIds.Contains(m.ResidentId) &&
                                       m.ResidentId != skChairmanId &&
                                       !skCouncelorIds.Contains(m.ResidentId) &&
                                       !specialPos.Contains(m.ResidentId))
                                .ToList();

                return(View(residents));
            }
            catch (Exception e)
            {
                TempData["alert-type"]   = "alert-danger";
                TempData["alert-header"] = "Error";
                TempData["alert-msg"]    = "Something went wrong, please try again later." + e.ToString();
                return(View());
            }
        }
        /*
         * A post method, but is only triggered by a button not a form.
         */
        public ActionResult ElectBrgyCaptain(string residentId)
        {
            try
            {
                OfficialTerm newTerm = new OfficialTerm()
                {
                    OfficialTermId = KeyGenerator.GenerateId(),
                    StartYear      = (int)DateTime.Now.Year
                };
                entities.OfficialTerms.Add(newTerm);
                entities.SaveChanges();

                // Get the newly elected SK Chairman, The record that is not in the BarangayCaptainTable means its the new record
                List <string> SK         = entities.BarangayChairmen.Select(m => m.SKChairmanId).ToList();
                SKChairman    skChairman = entities.SKChairmen.Where(m => !SK.Contains(m.SKChairmanId)).FirstOrDefault();

                // Now, elect the barangay Chairman
                BarangayChairman barangayCaptain = new BarangayChairman()
                {
                    ChairmanId     = KeyGenerator.GenerateId(residentId),
                    OfficialTermId = newTerm.OfficialTermId,
                    ResidentId     = residentId,
                    SKChairmanId   = skChairman.SKChairmanId,
                };
                entities.BarangayChairmen.Add(barangayCaptain);
                entities.SaveChanges();

                // Audit Trail
                string userId = User.Identity.GetUserId();
                ResidentsInformation tempResInfo = entities.ResidentsInformations.Where(m => m.ResidentId == residentId).FirstOrDefault();
                new AuditTrailer().Record("Elected " + tempResInfo.FirstName + " " + tempResInfo.LastName + " as Barangay Chairman.", AuditTrailer.BARANGAY_OFFICIAL_TYPE, userId);

                TempData["alert-type"]   = "alert-success";
                TempData["alert-header"] = "Success";
                TempData["alert-msg"]    = tempResInfo.FirstName + " " + tempResInfo.LastName + " was elected successfully as the Sinisian Barangay.";

                return(RedirectToAction("ElectCouncilors"));
            }
            catch (Exception e)
            {
                TempData["alert-type"]   = "alert-danger";
                TempData["alert-header"] = "Error";
                TempData["alert-msg"]    = "Unable to elect Barangay Captain, please try again later " + e.Message;
                return(RedirectToAction("ElectCaptain"));
            }
        }
        public ActionResult ElectCaptain()
        {
            try
            {
                TempData["user-profile-photo"] = UserHelper.GetDisplayPicture(User.Identity.GetUserId(), entities);

                // returns the barangaycaptain object that is elected but does not have elected councilors.
                List <BarangayChairman> chairmanWithCouncilors = entities.BarangayCounselors.Select(m => m.BarangayChairman).ToList();
                var ids = chairmanWithCouncilors.Select(m => m.ResidentId).ToList();

                BarangayChairman chairmanWithNoCouncilors = entities.BarangayChairmen.Where(m => !ids.Contains(m.ResidentId)).FirstOrDefault();

                if (chairmanWithNoCouncilors != null)
                {
                    TempData["alert-type"]   = "alert-info";
                    TempData["alert-header"] = "Information";
                    TempData["alert-msg"]    = "It appears that there is already an elected Barangay Chairman.";
                    return(RedirectToAction("ElectCouncilors"));
                }

                // Helps in filtering results.
                List <string> SK              = entities.BarangayChairmen.Select(m => m.SKChairmanId).ToList();
                SKChairman    skChairman      = entities.SKChairmen.Where(m => !SK.Contains(m.SKChairmanId)).FirstOrDefault();
                List <string> skcouncilorsIds = entities.SKCouncelors.Where(m => m.SKChairmanId == skChairman.SKChairmanId).Select(m => m.ResidentId).ToList();

                int legalYear = DateTime.Now.Date.Year - 18;
                int day       = DateTime.Now.Date.Day;
                int month     = DateTime.Now.Month;
                var residents = entities.ResidentsInformations
                                .Where(m => m.Birthday <= new DateTime(legalYear, month, day) &&
                                       m.ResidentId != skChairman.ResidentId &&
                                       !skcouncilorsIds.Contains(m.ResidentId))
                                .ToList();

                return(View(residents));
            }
            catch (Exception e)
            {
                TempData["alert-type"]   = "alert-danger";
                TempData["alert-header"] = "Error";
                TempData["alert-msg"]    = "Something went wrong, please try again later.";
                return(View());
            }
        }
        public ActionResult ElectCouncilors(string[] residentIds)
        {
            try
            {
                if (residentIds == null)
                {
                    TempData["alert-type"]   = "alert-warning";
                    TempData["alert-header"] = "Warning";
                    TempData["alert-msg"]    = "It appears that you have not selected any residents as Councilors.";
                    return(RedirectToAction("ElectCouncilors"));
                }

                if (residentIds.Length < BARANGAY_COUNCELOR_MAX_OFFICIAL || residentIds.Length > BARANGAY_COUNCELOR_MAX_OFFICIAL)
                {
                    TempData["alert-type"]   = "alert-warning";
                    TempData["alert-header"] = "Warning";
                    TempData["alert-msg"]    = "Elected councilors needs to be " + BARANGAY_COUNCELOR_MAX_OFFICIAL + ".";
                    return(RedirectToAction("ElectCouncilors"));
                }

                // obtain the record that has a null end year, meaning that is the latest term.
                OfficialTerm     officialTerm = entities.OfficialTerms.Where(m => m.EndYear == null).FirstOrDefault();
                BarangayChairman chairman     = entities.BarangayChairmen.Where(m => m.OfficialTermId == officialTerm.OfficialTermId).FirstOrDefault();

                //Audit Trail
                string userId = User.Identity.GetUserId();

                for (int i = 0; i < residentIds.Length; i++)
                {
                    entities.BarangayCounselors.Add(new BarangayCounselor()
                    {
                        BarangayCounselorId = KeyGenerator.GenerateId(residentIds[i]),
                        ResidentId          = residentIds[i],
                        ChairmanId          = chairman.ChairmanId
                    });
                    entities.SaveChanges();

                    //Audit Trail
                    string resId = residentIds[i];
                    ResidentsInformation tempResInformation = entities.ResidentsInformations.Where(m => m.ResidentId == resId).FirstOrDefault();
                    new AuditTrailer().Record("Elected " + tempResInformation.FirstName + " " + tempResInformation.LastName + " as Barangay Councelor.", AuditTrailer.BARANGAY_OFFICIAL_TYPE, userId);
                }

                List <string> ids = new List <string>();
                for (int i = 0; i < residentIds.Length; i++)
                {
                    ids.Add(residentIds[i]);
                }
                TempData["Ids"] = ids;

                TempData["alert-type"]   = "alert-success";
                TempData["alert-header"] = "Success";
                TempData["alert-msg"]    = "New batch of Councilors have been elected.";

                return(RedirectToAction("Index", "Dashboard"));
            }
            catch (Exception e)
            {
                TempData["alert-type"]   = "alert-danger";
                TempData["alert-header"] = "Error";
                TempData["alert-msg"]    = "Something went wrong, please try again later " + e.Message;
                return(RedirectToAction("ElectCouncilors"));
            }
        }
        public ActionResult ElectSKChairman()
        {
            try
            {
                TempData["user-profile-photo"] = UserHelper.GetDisplayPicture(User.Identity.GetUserId(), entities);

                // Check first if a barangay captain was elected already
                // returns the barangaycaptain object that is elected but does not have elected councilors
                List <BarangayChairman> chairmanWithCouncilors = entities.BarangayCounselors.Select(m => m.BarangayChairman).ToList();
                var ids = chairmanWithCouncilors.Select(m => m.ResidentId).ToList();

                BarangayChairman chairmanWithNoCouncilors = entities.BarangayChairmen.Where(m => !ids.Contains(m.ResidentId)).FirstOrDefault();

                if (chairmanWithNoCouncilors != null)
                {
                    TempData["alert-type"]   = "alert-info";
                    TempData["alert-header"] = "Information";
                    TempData["alert-msg"]    = "It appears that there is already an elected Barangay Chairman.";
                    return(RedirectToAction("ElectCouncilors"));
                }

                if (entities.OfficialTerms.Where(m => m.EndYear == null).FirstOrDefault() != null)
                {
                    TempData["alert-type"]   = "alert-info";
                    TempData["alert-header"] = "Information";
                    TempData["alert-msg"]    = "It appears that the last recorded official term's end year has not beend updated. Please update the record first before starting election.";
                    return(RedirectToAction("EditOfficialTerm"));
                }
                else
                {
                    OfficialTerm latestTerm = entities.OfficialTerms.OrderByDescending(m => m.EndYear).FirstOrDefault();
                    if (latestTerm.EndYear != DateTime.Now.Year)
                    {
                        TempData["alert-type"]   = "alert-info";
                        TempData["alert-header"] = "Information";
                        TempData["alert-msg"]    = "It appears that the last recorded official term has not ended yet.";
                        return(RedirectToAction("OfficialsChart"));
                    }
                }

                // Get the newly elected SK Chairman, The record that is not in the BarangayCaptainTable means its the new record
                List <string> SK         = entities.BarangayChairmen.Select(m => m.SKChairmanId).ToList();
                SKChairman    sKChairman = entities.SKChairmen.Where(m => !SK.Contains(m.SKChairmanId)).FirstOrDefault();

                if (sKChairman != null)
                {
                    TempData["alert-type"]   = "alert-info";
                    TempData["alert-header"] = "Information";
                    TempData["alert-msg"]    = "It appears that you have already elected an SK Chairman.";
                    return(RedirectToAction("ElectSKCouncilors"));
                }

                int legalYear = DateTime.Now.Date.Year - 18;
                int day       = DateTime.Now.Date.Day;
                int month     = DateTime.Now.Month;
                var residents = entities.ResidentsInformations.Where(m => m.Birthday <= new DateTime(legalYear, month, day)).ToList();

                return(View(residents));
            }
            catch (Exception e)
            {
                TempData["alert-type"]   = "alert-danger";
                TempData["alert-header"] = "Error";
                TempData["alert-msg"]    = "Something went wrong, please try again later.";
                return(View());
            }
        }