public ActionResult NewIdps(HRDPSNPPlan hrdpsnpPlan,FormCollection collection)
        {
            Plan plan = null;

            var reasonTypeID = int.Parse(collection["ReasonType"].ToString(CultureInfo.InvariantCulture));

            DateTime startDate = DateTime.Now.Date;
            DateTime endDate = DateTime.Now.Add(new TimeSpan(DateTime.Now.Year));
            string planName = string.Format("IDPS - {0}", startDate.Date.Year.ToString(CultureInfo.InvariantCulture) + endDate.Date.Year.ToString(CultureInfo.InvariantCulture));
            try
            {
                _planService.AddPlan(planName, startDate, endDate);
                plan = _planService.Get(p => p.PlanName == planName).Single();
            }
            catch (Exception)
            {
            }

            HRDPSNPPlanInfo psnphrdPlanInfo = _regionalRequestService.PlanToRequest(hrdpsnpPlan);
            RegionalRequest req = CreateRegionalRequest(psnphrdPlanInfo, collection, plan.PlanID, reasonTypeID);

            return RedirectToAction("Allocation", new { id = req.RegionalRequestID });
        }
        public ActionResult New(HRDPSNPPlan hrdpsnpPlan, FormCollection formCollection)
        {
            if (ModelState.IsValid)
            {
                HRDPSNPPlanInfo psnphrdPlanInfo = _regionalRequestService.PlanToRequest(hrdpsnpPlan);
                if (psnphrdPlanInfo != null)
                {
                    var exisiting = _regionalRequestService.FindBy(r => r.PlanID == psnphrdPlanInfo.HRDPSNPPlan.PSNPPlanID
                                                                        &&
                                                                        r.ProgramId ==
                                                                        psnphrdPlanInfo.HRDPSNPPlan.ProgramID && r.RegionID==psnphrdPlanInfo.HRDPSNPPlan.RegionID
                                                                        && r.Year == psnphrdPlanInfo.HRDPSNPPlan.Year
                                                                        && r.Month == psnphrdPlanInfo.HRDPSNPPlan.Month)
                        .Count;

                    if (exisiting == 0)
                    {
                        RegionalRequest req = CretaeRegionalRequest(psnphrdPlanInfo);
                        var model = getRequestDetai(req.RegionalRequestID);
                        ViewBag.message = "Request Created";
                        //RedirectToAction(@)
                        return RedirectToAction("Details" + "/" + req.RegionalRequestID);
                    }
                    else
                    {
                        ModelState.AddModelError("Errors", @"A request with the same parameters has already been made");
                    }

                }
                else
                {
                    ModelState.AddModelError("Errors", @"Can Not Create Request! Duration of Assistance for this region is Completed ");
                }

            }
            ViewBag.SeasonID = new SelectList(_commonService.GetSeasons(), "SeasonID", "Name");
            PopulateLookup();
            return View(hrdpsnpPlan);
        }
        private bool CheckDurationOfAssisstance(HRDPSNPPlan plan)
        {
            if (plan.ProgramID == (int) Programs.Releif)
            {

                var hrd = _unitOfWork.HRDRepository.FindBy(m => m.PlanID == plan.PlanID).LastOrDefault();
                //var woredas=new List<>();
                if (hrd != null)
                {
                    var requests = _unitOfWork.RegionalRequestRepository.FindBy(r => r.RegionID == plan.RegionID && r.ProgramId == (int) Programs.Releif && r.PlanID == plan.PlanID);

                    var hrdDetails = (from region in hrd.HRDDetails
                                      where region.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID == plan.RegionID
                                      select new
                                          {
                                              region.WoredaID,
                                              region.DurationOfAssistance
                                          }).ToList();

                    if (requests.Count >= hrdDetails.Max(m => m.DurationOfAssistance))
                        return false;
                    return true;
                }

            }
            else if (plan.ProgramID== (int)Programs.PSNP)
            {
                var psnpPlan = _unitOfWork.RegionalPSNPPlanRepository.FindBy(m => m.PlanId == plan.PSNPPlanID).LastOrDefault();
                if (psnpPlan !=null)
                {
                    var psnpRequests =_unitOfWork.RegionalRequestRepository.FindBy( r => r.RegionID == plan.RegionID && r.ProgramId == (int) Programs.PSNP && r.PlanID == plan.PSNPPlanID);
                    var psnpPlanDetails = (from detail in psnpPlan.RegionalPSNPPlanDetails
                                           where detail.PlanedWoreda.AdminUnit2.AdminUnit2.AdminUnitID == plan.RegionID
                                           select new
                                               {
                                                   detail.PlanedWoredaID,
                                                   detail.FoodRatio
                                               }).ToList();
                    if (psnpPlanDetails.Count!=0)
                    {
                        if (psnpRequests.Count >= psnpPlanDetails.Max(m => m.FoodRatio))
                            return false;
                    }

                    return true;
                }

            }
            return true;
        }
        public HRDPSNPPlanInfo PlanToRequest(HRDPSNPPlan plan)
        {
            //if (CheckDurationOfAssisstance(plan))
            //{
                HRDPSNPPlanInfo result = new HRDPSNPPlanInfo();
                List<BeneficiaryInfo> beneficiaryInfos = new List<BeneficiaryInfo>();
                result.HRDPSNPPlan = plan;
                if (plan.ProgramID == (int)Programs.PSNP)
                {
                    RegionalPSNPPlan psnpplan =
                        _unitOfWork.RegionalPSNPPlanRepository.FindBy(r => r.PlanId == plan.PSNPPlanID).FirstOrDefault();

                    if (psnpplan != null)
                    {
                        //TODO:Uncomment this (if PSNP case team Users change their mind and want to get previous request information instead of planned information)

                        var lastPsnpRequest = _unitOfWork.RegionalRequestRepository.FindBy(r => r.RegionID == plan.RegionID && r.ProgramId == (int)Programs.PSNP && r.PlanID == plan.PSNPPlanID).LastOrDefault();
                        if (lastPsnpRequest != null)
                        {
                            result.HRDPSNPPlan.RationID = psnpplan.RationID;
                            result.HRDPSNPPlan.Contingency = lastPsnpRequest.Contingency;
                            var noOfPsnprequests = _unitOfWork.RegionalRequestRepository.FindBy(r => r.RegionID == plan.RegionID && r.ProgramId == (int)Programs.PSNP && r.PlanID == plan.PSNPPlanID).Count;
                            var psnpApplicationWoredas = (from psnpDetail in psnpplan.RegionalPSNPPlanDetails
                                                          where
                                                              psnpDetail.PlanedWoreda.AdminUnit2.AdminUnit2.AdminUnitID ==
                                                              plan.RegionID
                                                              && psnpDetail.FoodRatio > noOfPsnprequests
                                                          select psnpDetail.PlanedWoredaID).ToList();
                            beneficiaryInfos = LastReliefRequest(lastPsnpRequest, psnpApplicationWoredas);
                        }
                        else
                        {
                            result.HRDPSNPPlan.RationID = psnpplan.RationID;
                            result.HRDPSNPPlan.Contingency =
                                psnpplan.RegionalPSNPPlanDetails.Any(
                                    t => t.StartingMonth == result.HRDPSNPPlan.Month && t.Contingency);
                            beneficiaryInfos = PSNPToRequest(psnpplan, plan.RegionID, plan.Month);
                        }

                    }
                }
                else if (plan.ProgramID == (int)Programs.Releif)
                {
                    HRD hrd = _unitOfWork.HRDRepository.FindBy(r => r.PlanID == plan.PlanID).LastOrDefault();

                    if (hrd != null)
                    {

                        var lastRequest =
                            _unitOfWork.RegionalRequestRepository.FindBy(
                                r => r.RegionID == plan.RegionID && r.ProgramId == (int)Programs.Releif && r.PlanID == plan.PlanID).
                                LastOrDefault();
                        if (lastRequest != null)
                        {
                            result.HRDPSNPPlan.RationID = hrd.RationID;
                            var requests =
                                _unitOfWork.RegionalRequestRepository.FindBy(
                                    r => r.RegionID == plan.RegionID && r.ProgramId == 1 && r.PlanID == plan.PlanID);
                            var numberOfRequestsPerRegion = requests.Count;
                            var applicableWoredas = (from detail in hrd.HRDDetails
                                                     where detail.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID == plan.RegionID //&& detail.DurationOfAssistance > numberOfRequestsPerRegion
                                                     select detail.WoredaID).ToList();
                            beneficiaryInfos = LastReliefRequest(lastRequest, applicableWoredas);
                            // var lastRequestDetail = LastReliefRequest(lastRequest);

                        }
                        else
                        {
                            result.HRDPSNPPlan.RationID = hrd.RationID;
                            List<HRDDetail> hrddetail =
                                (from woreda in hrd.HRDDetails
                                 where
                                     woreda.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID == plan.RegionID &&
                                     woreda.DurationOfAssistance > 0
                                 select woreda).ToList();
                            beneficiaryInfos = HRDToRequest(hrddetail);
                        }
                    }
                }
                else
                {
                    //if program is IDPS
                    List<BeneficiaryInfo> benficiaries = new List<BeneficiaryInfo>();
                    List<AdminUnit> woredas = new List<AdminUnit>();
                    var zones =
                        _unitOfWork.AdminUnitRepository.FindBy(
                            w => w.AdminUnitTypeID == 3 && w.ParentID == plan.RegionID);
                    foreach (var zone in zones)
                    {
                        AdminUnit zone1 = zone;
                        woredas.AddRange(_unitOfWork.AdminUnitRepository.FindBy(w => w.ParentID == zone1.AdminUnitID));
                    }
                    //var
                    foreach (var woreda in woredas)
                    {
                        AdminUnit woreda1 = woreda;
                        List<FDP> WoredaFDPs =
                            _unitOfWork.FDPRepository.FindBy(w => w.AdminUnitID == woreda1.AdminUnitID);
                        ICollection<BeneficiaryInfo> woredabeneficiaries =
                            (from FDP fdp in WoredaFDPs
                             select new BeneficiaryInfo { FDPID = fdp.FDPID, FDPName = fdp.Name, Beneficiaries = 0 }).
                                ToList();
                        benficiaries.AddRange(woredabeneficiaries);
                    }

                    //beneficiaryInfos = benficiaries;
                    //beneficiaryInfos = null;
                }
                result.BeneficiaryInfos = beneficiaryInfos;
                return result;
            //}
            //return null;
        }
        private bool CheckDurationOfAssisstance(HRDPSNPPlan plan)
        {
            if (plan.ProgramID == 1)
            {

                var hrd = _unitOfWork.HRDRepository.FindBy(m => m.PlanID == plan.PlanID).LastOrDefault();
                //var woredas=new List<>();
                if (hrd != null)
                {
                    var requests =_unitOfWork.RegionalRequestRepository.FindBy(r => r.RegionID == plan.RegionID && r.ProgramId == 1 && r.PlanID == plan.PlanID);

                    var hrdDetails = (from region in hrd.HRDDetails
                                      where region.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID == plan.RegionID
                                      select new
                                          {
                                              region.WoredaID,
                                              region.DurationOfAssistance
                                          }).ToList();

                    if (requests.Count >= hrdDetails.Max(m => m.DurationOfAssistance))
                        return false;
                    return true;
                }

            }
            return true;
        }
        public HRDPSNPPlanInfo PlanToRequest(HRDPSNPPlan plan)
        {
            if (CheckDurationOfAssisstance(plan))
            {
                HRDPSNPPlanInfo result = new HRDPSNPPlanInfo();
                List<BeneficiaryInfo> beneficiaryInfos = new List<BeneficiaryInfo>();
                result.HRDPSNPPlan = plan;
                if (plan.ProgramID == 2)
                {
                    RegionalPSNPPlan psnpplan =
                        _unitOfWork.RegionalPSNPPlanRepository.FindBy(r=>r.PlanId == plan.PSNPPlanID).FirstOrDefault();

                    if (psnpplan != null)
                    {
                        result.HRDPSNPPlan.RationID = psnpplan.RationID;
                        beneficiaryInfos = PSNPToRequest(psnpplan,plan.RegionID);
                    }
                }
                else if (plan.ProgramID == 1)
                {
                    HRD hrd = _unitOfWork.HRDRepository.FindBy(r => r.PlanID == plan.PlanID).LastOrDefault();

                    var lastRequest =_unitOfWork.RegionalRequestRepository.FindBy(r => r.RegionID == plan.RegionID && r.ProgramId == 1 && r.PlanID == plan.PlanID).LastOrDefault();

                    if (lastRequest != null)
                    {
                        var requests = _unitOfWork.RegionalRequestRepository.FindBy(r => r.RegionID == plan.RegionID && r.ProgramId == 1 && r.PlanID == plan.PlanID);
                        var numberOfRequestsPerRegion = requests.Count;
                        var applicableWoredas = (from detail in hrd.HRDDetails
                                                 where
                                                     detail.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID == plan.RegionID &&
                                                     detail.DurationOfAssistance > numberOfRequestsPerRegion
                                                 select detail.WoredaID).ToList();
                        beneficiaryInfos = LastReliefRequest(lastRequest, applicableWoredas);
                       // var lastRequestDetail = LastReliefRequest(lastRequest);

                    }
                    else
                    {
                        result.HRDPSNPPlan.RationID = hrd.RationID;
                        List<HRDDetail> hrddetail =
                            (from woreda in hrd.HRDDetails
                             where woreda.AdminUnit.AdminUnit2.AdminUnit2.AdminUnitID == plan.RegionID && woreda.DurationOfAssistance>0
                             select woreda).ToList();
                        beneficiaryInfos = HRDToRequest(hrddetail);
                    }
                }
                else
                {
                    //if program is IDPS
                    List<BeneficiaryInfo> benficiaries = new List<BeneficiaryInfo>();
                    List<AdminUnit> woredas = new List<AdminUnit>();
                    var zones =
                        _unitOfWork.AdminUnitRepository.FindBy(
                            w => w.AdminUnitTypeID == 3 && w.ParentID == plan.RegionID);
                    foreach (var zone in zones)
                    {
                        AdminUnit zone1 = zone;
                        woredas.AddRange(_unitOfWork.AdminUnitRepository.FindBy(w => w.ParentID == zone1.AdminUnitID));
                    }
                    //var
                    foreach (var woreda in woredas)
                    {
                        AdminUnit woreda1 = woreda;
                        List<FDP> WoredaFDPs =
                            _unitOfWork.FDPRepository.FindBy(w => w.AdminUnitID == woreda1.AdminUnitID);
                        ICollection<BeneficiaryInfo> woredabeneficiaries =
                            (from FDP fdp in WoredaFDPs
                             select new BeneficiaryInfo {FDPID = fdp.FDPID, FDPName = fdp.Name, Beneficiaries = 0}).
                                ToList();
                        benficiaries.AddRange(woredabeneficiaries);
                    }

                    //beneficiaryInfos = benficiaries;
                    //beneficiaryInfos = null;
                }
                result.BeneficiaryInfos = beneficiaryInfos;
                return result;
            }
            return null;
        }