public void PopulateItemList(DataTable dtItem)
        {
            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Value = 1;
            progressBar1.Maximum = dtItem.Rows.Count;

            GeneralInfo pipline = new GeneralInfo();
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            int storeId = (cboStores.SelectedValue != null)?Convert.ToInt32(cboStores.SelectedValue):1;
            lstItem.Items.Clear();
            int col = 0;
            int count = 1;
            Balance bal = new Balance();
            Items itmIssues = new Items();
            int year = Convert.ToInt32(cboYear.SelectedItem);
            foreach (DataRow dr in dtItem.Rows)
            {
                int itemId = Convert.ToInt32(dr["ID"]);
                string itemName = dr["ItemName"].ToString() + " - " + dr["DosageForm"].ToString() + " - " + dr["Strength"].ToString();
                int yer = (dtCurrent.Month < 11) ? year : year - 1;// (dtCurrent.Month < 11) ? Convert.ToInt32(cboYear.SelectedItem) : Convert.ToInt32(cboYear.SelectedItem) - 1;
                Int64 SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, dtCurrent.Month, yer);

                int[] mon = {11,12,1,2,3,4,5,6,7,8,9,10};

                long[] cons = new long[12];
                for (int i = 0; i < mon.Length;i++ )
                {
                    int yr = (mon[i] < 11) ? year : year - 1;
                    cons[i] = itmIssues.GetQuantityIssuedByItemPerMonth(mon[i], itemId, storeId, yr);

                }
                string[] str = { count.ToString(), itemName, ((SOH != 0) ? SOH.ToString("#,###") : "0"), ((cons[0] != 0) ? cons[0].ToString("#,###") : "0"), ((cons[1] != 0) ? cons[1].ToString("#,###") : "0"), ((cons[2] != 0) ? cons[2].ToString("#,###") : "0"), ((cons[3] != 0) ? cons[3].ToString("#,###") : "0"), ((cons[4] != 0) ? cons[4].ToString("#,###") : "0"), ((cons[5] != 0) ? cons[5].ToString("#,###") : "0"), ((cons[6] != 0) ? cons[6].ToString("#,###") : "0"), ((cons[7] != 0) ? cons[7].ToString("#,###") : "0"), ((cons[8] != 0) ? cons[8].ToString("#,###") : "0"), ((cons[9] != 0) ? cons[9].ToString("#,###") : "0"), ((cons[10] != 0) ? cons[10].ToString("#,###") : "0"), ((cons[11] != 0) ? cons[11].ToString("#,###") : "0") };
                ListViewItem listItem = new ListViewItem(str);
                listItem.ToolTipText = itemName;
                listItem.Tag = dr["ID"];
                if (col != 0)
                {
                    listItem.BackColor = Color.FromArgb(233, 247, 248);
                    col = 0;
                }
                else
                {
                    col++;
                }
                lstItem.Items.Add(listItem);
                count++;
                progressBar1.PerformStep();
            }
            progressBar1.Visible = false;
        }
        public DataTable GetECLSItemsStockOut(int storeId, int month, int year)
        {
            Items itm = new Items();
            Programs prog = new Programs();
            prog.GetProgramByName("Family Planning");
            DataTable dtItem = itm.GetItemsByProgram(prog.ID);
            GeneralInfo pipline = new GeneralInfo();
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            double eop = pipline.EOP;

            DataTable dt = new DataTable();
            string[] cols = { "ID", "FullItemName", "DosageForm", "Strength", "Unit", "StockCode" };
            foreach (string st in cols)
            {
                dt.Columns.Add(st);
            }
            Balance bal = new Balance();
            foreach (DataRow dr in dtItem.Rows)
            {
                Int64 AMC = bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, month, year);
                Int64 MinCon = AMC * min;
                Int64 maxCon = AMC * max;
                double eopCon = AMC * (eop + 0.25);
                Int64 SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, year);
                decimal MOS = (AMC != 0) ? (SOH / AMC) : 0;
                Int64 reorder = (maxCon > SOH) ? maxCon - SOH : 0;

                if (SOH == 0)
                {
                    object[] obb = { dr["ID"], dr["ItemName"], dr["DosageForm"], dr["Strength"], dr["Unit"], dr["StockCode"] };
                    dt.Rows.Add(obb);
                }
                //string status = (SOH <= eopCon && SOH > 0) ? "Near EOP" : ((SOH > maxCon) ? "Excess Stock" : ((SOH <= 0) ? "Stock Out" : "Normal"));
            }
            return dt;
        }
 public int CountVitalItemsStockOut(int storeId, int month, int year)
 {
     Items itm = new Items();
     DataTable dtItem = itm.GetVitalItems();
     GeneralInfo pipline = new GeneralInfo();
     pipline.LoadAll();
     int min = pipline.Min;
     int max = pipline.Max;
     double eop = pipline.EOP;
     int count = 0;
     Balance bal = new Balance();
     foreach (DataRow dr in dtItem.Rows)
     {
         Int64 AMC = bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, month, year);
         Int64 minCon = AMC * min;
         Int64 maxCon = AMC * max;
         double eopCon = AMC * (eop + 0.25);
         Int64 SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, year);
         decimal MOS = (AMC != 0) ? (SOH / AMC) : 0;
         Int64 reorder = (maxCon > SOH) ? maxCon - SOH : 0;
         if (SOH == 0)
             count++;
         //string status = (SOH <= eopCon && SOH > 0) ? "Near EOP" : ((SOH > maxCon) ? "Excess Stock" : ((SOH <= 0) ? "Stock Out" : "Normal"));
     }
     return count;
 }
 public int CountBelowMin(int storeId, int month, int year)
 {
     Items itm = new Items();
     DataTable dtItem = itm.GetAllItems(1);
     GeneralInfo pipline = new GeneralInfo();
     pipline.LoadAll();
     int min = pipline.Min;
     int max = pipline.Max;
     double eop = pipline.EOP;
     int count = 0;
     Balance bal = new Balance();
     if (storeId == 0)
     {
         count += (from DataRow dr in dtItem.Rows
                   let AMC = bal.CalculateAMCAll(Convert.ToInt32(dr["ID"]), month, year)
                   let MinCon = AMC * min
                   let maxCon = AMC * max
                   let eopCon = AMC * (eop + 0.25)
                   let SOH = bal.GetSOHAll(Convert.ToInt32(dr["ID"]), month, year)
                   let MOS = (AMC != 0) ? (SOH / AMC) : 0
                   let reorder = (maxCon > SOH) ? maxCon - SOH : 0
                   where SOH > eopCon && (SOH <= MinCon)
                   select MinCon).Count();
     }
     else
     {
         count += (from DataRow dr in dtItem.Rows
                   let AMC = bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, month, year)
                   let MinCon = AMC * min
                   let maxCon = AMC * max
                   let eopCon = AMC * (eop + 0.25)
                   let SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, year)
                   let MOS = (AMC != 0) ? (SOH / AMC) : 0
                   let reorder = (maxCon > SOH) ? maxCon - SOH : 0
                   where SOH > eopCon && (SOH <= MinCon)
                   select MinCon).Count();
     }
     return count;
 }
        public DataTable OverStockedItems(int storeId, int year, int month, string selectedType, BackgroundWorker bw)
        {
            DataTable dtBal = new DataTable();
            GeneralInfo pipline = new GeneralInfo();
            Items itm = new Items();
            Balance bal = new Balance();
            IssueDoc iss = new IssueDoc();
            ReceiveDoc rec = new ReceiveDoc();
            string[] str = { "FullItemName", "SOH", "AMC", "MOS", "Min", "Max", "ExcessQty", "ExcessAmount", "CategoryId", "SubCategoryID", "ID" };
            foreach (string s in str)
            {
                dtBal.Columns.Add(s);
            }
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            double eop = pipline.EOP;
            DataTable dtItem = new DataTable();

            dtItem = ((selectedType == "Drug") ? itm.GetAllItems(1) : itm.GetAllSupply());
            int i = 1;
            foreach (DataRow dr in dtItem.Rows)
            {

                string itemName = dr["FullItemName"].ToString();
                int yer = (month < 11) ? year : year - 1;
                Int64 AMC = bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, month, yer);
                Int64 MinCon = AMC * min;
                Int64 maxCon = AMC * max;
                Int64 SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, yer);
                if (SOH > maxCon)
                {
                    decimal MOS = (AMC != 0) ? (Convert.ToDecimal(SOH) / Convert.ToDecimal(AMC)) : 0;
                    MOS = Decimal.Round(MOS, 1);

                    Int64 excessQty = SOH - maxCon;
                    double price = rec.GetLastReceivedCost(Convert.ToInt32(dr["ID"]), storeId);
                    double excessAmount = price * excessQty;
                    object[] obj = { itemName, SOH, AMC, MOS, MinCon, maxCon, excessQty, excessAmount, Convert.ToInt32(dr["CategoryId"]), Convert.ToInt32(dr["SubCategoryID"]), Convert.ToInt32(dr["ID"]) };
                    dtBal.Rows.Add(obj);
                }
                bw.ReportProgress(Convert.ToInt32((Convert.ToDouble(i++) / dtItem.Rows.Count) * 100));
            }
            return dtBal;
        }
        private void PopulateSStatusByCategoryAndYear()
        {
            if (curMont != 0 && curYear != 0)
            {
                storeId = Convert.ToInt32(cboStores.SelectedValue);
                curYear = Convert.ToInt32(cboYear.EditValue);

                Balance blnc = new Balance();
                DataTable dtbl = blnc.GetSOH(storeId, curMont, curYear);

                Items itm = new Items();
                Balance bal = new Balance();
                ReceiveDoc rec = new ReceiveDoc();

                Programs prog = new Programs();
                prog.GetProgramByName("Family Planning");
                DataTable dtItm = itm.GetItemsByProgram(prog.ID);
                int totalECLS = dtItm.Rows.Count;
                lblNoECLS.Text = totalECLS.ToString();
                int neverRec = rec.CountNeverReceivedItemsByCateogryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue));
                int stockin = (from m in dtbl.AsEnumerable()
                               where m["Status"].ToString() == "Normal" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                               && ((ckExclude.Checked)? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                               select m).Count();
                if (stockin == 0)
                {
                    listInStock.Visible = false;
                }
                else
                {
                    listInStock.Visible = true;
                }

                //progressBar1.PerformStep();
                int stockout = (from m in dtbl.AsEnumerable()
                                where m["Status"].ToString() == "Stock Out" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                                && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                select m).Count();
                if (stockout == 0)
                {
                    listStockOut.Visible = false;
                }
                else
                {
                    listStockOut.Visible = true;
                }
                //((ckExclude.Checked)? (bal.CountStockOut(storeId, curMont, curYear)- neverRec) : bal.CountStockOut(storeId, curMont, curYear));
                //progressBar1.PerformStep();
                int overstock = (from m in dtbl.AsEnumerable()
                                 where m["Status"].ToString() == "Over Stocked" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                                 && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                 select m).Count();
                if (overstock == 0)
                {
                    listOverstock.Visible = false;
                }
                else
                {
                    listOverstock.Visible = true;
                }
                // progressBar1.PerformStep();
                int nearEOP = (from m in dtbl.AsEnumerable()
                               where m["Status"].ToString() == "Near EOP" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                               && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                               select m).Count();
                if (nearEOP == 0)
                {
                    listNearEOP.Visible = false;
                }
                else
                {
                    listNearEOP.Visible = true;
                }
                //progressBar1.PerformStep();
                int belowEOP = (from m in dtbl.AsEnumerable()
                                where m["Status"].ToString() == "Below EOP" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                                && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                select m).Count();
                if (belowEOP == 0)
                {
                    listBelowEOP.Visible = false;
                }
                else
                {
                    listNearEOP.Visible = true;
                }
                // progressBar1.PerformStep();
                int belowMin = 0;//bal.CountBelowMin(storeId, curMont, curYear);
                // progressBar1.PerformStep();
                int freeStockOut = (from m in dtbl.AsEnumerable()
                                    where m["Status"].ToString() == "Stock Out" && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue)
                                    && ((ckExclude.Checked) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                    select m).Count();
                if (freeStockOut == 0)
                {
                    lblFreeStockedout.Visible = false;
                }
                else
                {
                    lblFreeStockedout.Visible = true;
                }
                // progressBar1.PerformStep();
                int vitalStockOut = bal.CountVitalItemsStockOut(storeId, curMont, curYear);
                //int eclsStockout = bal.CountECLSItemsStockOut(storeId, curMont, curYear);
                // progressBar1.PerformStep();
                object[] obj = { stockin, stockout, overstock, nearEOP, belowEOP };
                int totalItm = stockin + stockout + nearEOP + overstock;

                decimal percen = ((totalItm != 0) ? (Convert.ToDecimal(stockin) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblInStock.Text = stockin.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(stockout) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblStockOut.Text = stockout.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(overstock) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblOverStocked.Text = overstock.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(nearEOP) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblNearEOP.Text = nearEOP.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(belowEOP) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblBelowEOP.Text = belowEOP.ToString() + " (" + percen.ToString("#.0") + "%)";

                percen = ((totalItm != 0) ? (Convert.ToDecimal(belowMin) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblBelowMin.Text = belowMin.ToString() + " (" + percen.ToString("#.0") + "%)";

                lblFreeStockedout.Text = freeStockOut.ToString();
                if (freeStockOut == 0)
                {
                    linkLabel6.Visible = false;
                }
                else
                {
                    linkLabel6.Visible = true;
                }
                int totalFree = itm.CountFreeItems();
                percen = ((totalFree != 0) ? (Convert.ToDecimal(freeStockOut) / Convert.ToDecimal(totalFree)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblFreeStock.Text = freeStockOut.ToString() + " (" + percen.ToString("#.0") + "%)";

                lblVitalStockedout.Text = vitalStockOut.ToString();
                if (vitalStockOut == 0)
                {
                    linkLabel7.Visible = false;
                }
                else
                {
                    linkLabel7.Visible = true;
                }
                totalFree = itm.CountVitalItems();
                percen = ((totalFree != 0) ? (Convert.ToDecimal(vitalStockOut) / Convert.ToDecimal(totalFree)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                lblVitalStock.Text = vitalStockOut.ToString() + " (" + percen.ToString("#.0") + "%)";

                //totalFree = itm.CountVitalItems();
                //percen = ((totalECLS != 0)?(Convert.ToDecimal(eclsStockout) / Convert.ToDecimal(totalECLS)) * 100:0);
                //percen = Decimal.Round(percen, 0);
                //lblEclsStock.Text = eclsStockout.ToString() + " (" + percen.ToString("#.0") + "%)";

                GenerateStockStatusPieChart(obj);
            }
        }
        private void PopulateSStatusReport()
        {
            if (curMont != 0 && curYear != 0)
            {
                var storeId = Convert.ToInt32(cboStores.EditValue);
                curYear = Convert.ToInt32(cboYear.EditValue);

                Balance blnc = new Balance();
                DataTable dtbl = new DataTable();
                if (storeId == 0)
                {
                    dtbl = blnc.GetSOHForAllStores(curMont, Convert.ToInt32(cboYear.EditValue));
                }
                else
                {
                    dtbl = blnc.GetSOH(storeId, curMont, Convert.ToInt32(cboYear.EditValue));
                }

                Items itm = new Items();
                Balance bal = new Balance();
                ReceiveDoc rec = new ReceiveDoc();

                Programs prog = new Programs();
                prog.GetProgramByName("Family Planning");
                DataTable dtItm = itm.GetItemsByProgram(prog.ID);
                int totalECLS = dtItm.Rows.Count;
                int stockin, stockout, overstock, nearEOP, belowEOP, freeStockOut;

                if (Convert.ToInt32(lkCategory.EditValue) != 0)
                {
                    stockin = (from m in dtbl.AsEnumerable()
                                   where m["Status"].ToString() == "Normal"
                                   && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                   select m).Count();

                    stockout = (from m in dtbl.AsEnumerable()
                                    where m["Status"].ToString() == "Stock Out"
                                    && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                    select m).Count();

                    overstock = (from m in dtbl.AsEnumerable()
                                     where m["Status"].ToString() == "Over Stocked"
                                     && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                     select m).Count();

                    nearEOP = (from m in dtbl.AsEnumerable()
                                   where m["Status"].ToString() == "Near EOP"
                                   && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                   select m).Count();

                    belowEOP = (from m in dtbl.AsEnumerable()
                                    where m["Status"].ToString() == "Below EOP"
                                    && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                    select m).Count();

                    freeStockOut = (from m in dtbl.AsEnumerable()
                                        where m["Status"].ToString() == "Stock Out"
                                        && Convert.ToInt32(m["TypeID"]) == Convert.ToInt32(lkCategory.EditValue) && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                        select m).Count();
                }
                else
                {
                    stockin = (from m in dtbl.AsEnumerable()
                               where m["Status"].ToString() == "Normal"
                               && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                               select m).Count();

                    stockout = (from m in dtbl.AsEnumerable()
                                where m["Status"].ToString() == "Stock Out"
                                && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                select m).Count();

                    overstock = (from m in dtbl.AsEnumerable()
                                 where m["Status"].ToString() == "Over Stocked"
                                 && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                 select m).Count();

                    nearEOP = (from m in dtbl.AsEnumerable()
                               where m["Status"].ToString() == "Near EOP"
                               && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                               select m).Count();

                    belowEOP = (from m in dtbl.AsEnumerable()
                                where m["Status"].ToString() == "Below EOP"
                                && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                select m).Count();

                    freeStockOut = (from m in dtbl.AsEnumerable()
                                    where m["Status"].ToString() == "Stock Out"
                                    && ((!ckExclude.Checked) || Convert.ToInt32(m["EverReceived"]) == 1)
                                    select m).Count();
                }

                object[] obj = { stockin, stockout, overstock, nearEOP, belowEOP };
                int totalItm = stockin + stockout + nearEOP + overstock;

                decimal percen = ((totalItm != 0) ? (Convert.ToDecimal(stockin) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);

                percen = ((totalItm != 0) ? (Convert.ToDecimal(stockout) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                percen = ((totalItm != 0) ? (Convert.ToDecimal(overstock) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                percen = ((totalItm != 0) ? (Convert.ToDecimal(nearEOP) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                percen = ((totalItm != 0) ? (Convert.ToDecimal(belowEOP) / Convert.ToDecimal(totalItm)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                int totalFree = itm.CountFreeItems();
                percen = ((totalFree != 0) ? (Convert.ToDecimal(freeStockOut) / Convert.ToDecimal(totalFree)) * 100 : 0);
                percen = Decimal.Round(percen, 0);
                totalFree = itm.CountVitalItems();
                GenerateStockStatusPieChart(obj);
            }
        }
        private void DetailMos()
        {
            //dtDate.Value = DateTime.Now;
            //dtDate.CustomFormat = "MM/dd/yyyy";
            // DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);

            ReceivingUnits du = new ReceivingUnits();
            DataTable dtDus = du.GetApplicableDUsAll(_itemId);
            int col = 0;
            Balance bal = new Balance();
            IssueDoc iss = new IssueDoc();
            Stores stor = new Stores();
            stor.GetActiveStores();
            DataTable dtStores = stor.DefaultView.ToTable();
            //  lstTrendMos.Items.Clear();
            foreach (DataRow drStr in dtStores.Rows)
            {
                int storeId = Convert.ToInt32(drStr["ID"]);
                //Int64 soh = bal.GetSOH(itemId, storeId, dtCurrent.Month, dtCurrent.Year);
                //Int64 amc = bal.CalculateAMC(itemId, storeId, dtCurrent.Month, dtCurrent.Year);
                //Int64 issue = iss.GetIssuedQuantityByMonth(itemId, storeId, dtCurrent.Month, dtCurrent.Year);
                //decimal mos = ((amc > 0) ? Convert.ToDecimal(soh) / Convert.ToDecimal(amc) : 0);
                //mos = Decimal.Round(mos, 1);

                int[] mon = { 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                decimal[] cons = new decimal[12];
                for (int i = 0; i < mon.Length; i++)
                {
                    int yr = (mon[i] > 10) ? _dtCurrent.Year - 1 : _dtCurrent.Year;
                    if (!(yr == _dtCurrent.Year && mon[i] > _dtCurrent.Month && mon[i] < 11))
                    {
                        Int64 soh = bal.GetSOH(_itemId, storeId, mon[i], yr);
                        double amc = Builder.CalculateAverageConsumption(_itemId, _storeId,
                                                                        _dtCurrent.Subtract(TimeSpan.FromDays(180)), _dtCurrent,
                                                                        CalculationOptions.Monthly);
                        decimal mos = ((amc != 0) ? Convert.ToDecimal(soh) / Convert.ToDecimal(amc) : 0);
                        cons[i] = Decimal.Round(mos, 1);
                    }
                    else
                        cons[i] = 0;
                }

                string[] str = { drStr["StoreName"].ToString(), ((cons[0] != 0) ? cons[0].ToString() : "0"), ((cons[1] != 0) ? cons[1].ToString() : "0"), ((cons[2] != 0) ? cons[2].ToString() : "0"), ((cons[3] != 0) ? cons[3].ToString() : "0"), ((cons[4] != 0) ? cons[4].ToString() : "0"), ((cons[5] != 0) ? cons[5].ToString() : "0"), ((cons[6] != 0) ? cons[6].ToString() : "0"), ((cons[7] != 0) ? cons[7].ToString() : "0"), ((cons[8] != 0) ? cons[8].ToString() : "0"), ((cons[9] != 0) ? cons[9].ToString() : "0"), ((cons[10] != 0) ? cons[10].ToString() : "0"), ((cons[11] != 0) ? cons[11].ToString() : "0") };
                ListViewItem lstItm = new ListViewItem(str);

                if (col != 0)
                {
                    lstItm.BackColor = Color.FromArgb(233, 247, 248);

                    col = 0;
                }
                else
                {
                    col++;
                }
                //  lstTrendMos.Items.Add(lstItm);
            }
            //  lstTrendMos.Items.Add(new ListViewItem());
            foreach (DataRow drDus in dtDus.Rows)
            {
                int duid = Convert.ToInt32(drDus["ID"]);
                //Int64 soh = bal.GetDUSOH(itemId, duid, dtCurrent.Month, dtCurrent.Year);
                //Int64 amc = bal.CalculateDUAMC(itemId, duid, dtCurrent.Month, dtCurrent.Year, 0);
                //Int64 issue = iss.GetDUIssueByMonth(itemId, duid, dtCurrent.Month, dtCurrent.Year);
                //decimal mos = ((amc > 0) ? Convert.ToDecimal(soh) / Convert.ToDecimal(amc) : 0);
                //mos = Decimal.Round(mos, 1);
                int[] mon = { 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                decimal[] cons = new decimal[12];
                for (int i = 0; i < mon.Length; i++)
                {
                    int yr = (mon[i] > 10) ? _dtCurrent.Year - 1 : _dtCurrent.Year;
                    Int64 soh = bal.GetDUSOH(_itemId, duid, mon[i], yr);
                    double amc = Builder.CalculateAverageConsumption(_itemId, duid, _dtCurrent.Subtract(TimeSpan.FromDays(180)), _dtCurrent, CalculationOptions.Monthly);//bal.CalculateDUAMC(_itemId, duid, mon[i], yr, 0);
                    decimal mos = ((amc != 0) ? Convert.ToDecimal(soh) / Convert.ToDecimal(amc) : 0);
                    cons[i] = Decimal.Round(mos, 1);
                }

                string[] str = { drDus["Name"].ToString(), ((cons[0] != 0) ? cons[0].ToString() : "0"), ((cons[1] != 0) ? cons[1].ToString() : "0"), ((cons[2] != 0) ? cons[2].ToString() : "0"), ((cons[3] != 0) ? cons[3].ToString() : "0"), ((cons[4] != 0) ? cons[4].ToString() : "0"), ((cons[5] != 0) ? cons[5].ToString() : "0"), ((cons[6] != 0) ? cons[6].ToString() : "0"), ((cons[7] != 0) ? cons[7].ToString() : "0"), ((cons[8] != 0) ? cons[8].ToString() : "0"), ((cons[9] != 0) ? cons[9].ToString() : "0"), ((cons[10] != 0) ? cons[10].ToString() : "0"), ((cons[11] != 0) ? cons[11].ToString() : "0") };
                ListViewItem lstItm = new ListViewItem(str);

                if (col != 0)
                {
                    lstItm.BackColor = Color.FromArgb(233, 247, 248);
                    col = 0;
                }
                else
                {
                    col++;
                }
                // lstTrendMos.Items.Add(lstItm);
            }
        }
        private void DetailSoh()
        {
            //CALENDAR:
            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            DateTime dtCurrent = new DateTime();// Convert.ToDateTime(dtDate.Text);
            try
            {
                dtCurrent = Convert.ToDateTime(dtDate.Text);
            }
            catch
            {
                string dtValid = "";
                string yer = "";
                if (Convert.ToInt32(dtDate.Text.Substring(0, 2)) == 13)
                {
                    dtValid = dtDate.Text;
                    yer = dtValid.Substring(dtValid.Length - 4, 4);
                    dtCurrent = Convert.ToDateTime("12/30/" + yer);
                }
                else if (Convert.ToInt32(dtDate.Text.Substring(0, 2)) == 2)
                {
                    dtValid = dtDate.Text;
                    yer = dtValid.Substring(dtValid.Length - 4, 4);
                    dtCurrent = Convert.ToDateTime("2/28/" + yer);
                }
            }

            ReceivingUnits du = new ReceivingUnits();
            DataTable dtDus = du.GetApplicableDUsAll(_itemId);
            int col = 0;
            Balance bal = new Balance();
            IssueDoc iss = new IssueDoc();
            Stores stor = new Stores();
            stor.GetActiveStores();
            DataTable dtStores = stor.DefaultView.ToTable();

            foreach (DataRow drStr in dtStores.Rows)
            {
                int storeId = Convert.ToInt32(drStr["ID"]);
                //Int64 soh = bal.GetSOH(itemId, storeId, dtCurrent.Month, dtCurrent.Year);
                //Int64 amc = bal.CalculateAMC(itemId, storeId, dtCurrent.Month, dtCurrent.Year);
                //Int64 issue = iss.GetIssuedQuantityByMonth(itemId, storeId, dtCurrent.Month, dtCurrent.Year);
                //decimal mos = ((amc > 0) ? Convert.ToDecimal(soh) / Convert.ToDecimal(amc) : 0);
                //mos = Decimal.Round(mos, 1);

                int[] mon = { 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                long[] cons = new long[12];
                for (int i = 0; i < mon.Length; i++)
                {
                    int yr = (mon[i] > 10) ? dtCurrent.Year - 1 : dtCurrent.Year;
                    if (!(yr == dtCurrent.Year && mon[i] > dtCurrent.Month && mon[i] < 11))
                    {

                        cons[i] = bal.GetSOH(_itemId, storeId, mon[i], yr);
                    }
                    else
                        cons[i] = 0;
                }

                string[] str = { drStr["StoreName"].ToString(), ((cons[0] != 0) ? cons[0].ToString("#,###") : "0"), ((cons[1] != 0) ? cons[1].ToString("#,###") : "0"), ((cons[2] != 0) ? cons[2].ToString("#,###") : "0"), ((cons[3] != 0) ? cons[3].ToString("#,###") : "0"), ((cons[4] != 0) ? cons[4].ToString("#,###") : "0"), ((cons[5] != 0) ? cons[5].ToString("#,###") : "0"), ((cons[6] != 0) ? cons[6].ToString("#,###") : "0"), ((cons[7] != 0) ? cons[7].ToString("#,###") : "0"), ((cons[8] != 0) ? cons[8].ToString("#,###") : "0"), ((cons[9] != 0) ? cons[9].ToString("#,###") : "0"), ((cons[10] != 0) ? cons[10].ToString("#,###") : "0"), ((cons[11] != 0) ? cons[11].ToString("#,###") : "0") };
                ListViewItem lstItm = new ListViewItem(str);

                if (col != 0)
                {
                    lstItm.BackColor = Color.FromArgb(233, 247, 248);

                    col = 0;
                }
                else
                {
                    col++;
                }
                //lstTrendSoh.Items.Add(lstItm);
            }
            //lstTrendSoh.Items.Add(new ListViewItem());
            foreach (DataRow drDus in dtDus.Rows)
            {
                int duid = Convert.ToInt32(drDus["ID"]);
                //Int64 soh = bal.GetDUSOH(itemId, duid, dtCurrent.Month, dtCurrent.Year);
                //Int64 amc = bal.CalculateDUAMC(itemId, duid, dtCurrent.Month, dtCurrent.Year, 0);
                //Int64 issue = iss.GetDUIssueByMonth(itemId, duid, dtCurrent.Month, dtCurrent.Year);
                //decimal mos = ((amc > 0) ? Convert.ToDecimal(soh) / Convert.ToDecimal(amc) : 0);
                //mos = Decimal.Round(mos, 1);
                int[] mon = { 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

                long[] cons = new long[12];
                for (int i = 0; i < mon.Length; i++)
                {
                    int yr = (mon[i] > 10) ? dtCurrent.Year - 1 : dtCurrent.Year;
                    cons[i] = bal.GetDUSOH(_itemId, duid, mon[i], yr);
                }

                string[] str = { drDus["Name"].ToString(), ((cons[0] != 0) ? cons[0].ToString("#,###") : "0"), ((cons[1] != 0) ? cons[1].ToString("#,###") : "0"), ((cons[2] != 0) ? cons[2].ToString("#,###") : "0"), ((cons[3] != 0) ? cons[3].ToString("#,###") : "0"), ((cons[4] != 0) ? cons[4].ToString("#,###") : "0"), ((cons[5] != 0) ? cons[5].ToString("#,###") : "0"), ((cons[6] != 0) ? cons[6].ToString("#,###") : "0"), ((cons[7] != 0) ? cons[7].ToString("#,###") : "0"), ((cons[8] != 0) ? cons[8].ToString("#,###") : "0"), ((cons[9] != 0) ? cons[9].ToString("#,###") : "0"), ((cons[10] != 0) ? cons[10].ToString("#,###") : "0"), ((cons[11] != 0) ? cons[11].ToString("#,###") : "0") };
                ListViewItem lstItm = new ListViewItem(str);

                if (col != 0)
                {
                    lstItm.BackColor = Color.FromArgb(233, 247, 248);
                    col = 0;
                }
                else
                {
                    col++;
                }
                // lstTrendSoh.Items.Add(lstItm);
            }
        }
        private void ItemStockStatus()
        {
            GeneralInfo info = new GeneralInfo();
            info.LoadAll();
            Balance bal = new Balance();
            Items itm = new Items();
            //dtDate.Value = DateTime.Now;
            //DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);

            // int yr = ()?dtCurrent.Year : dtCurrent.Year -1;
            DataTable dtItm = itm.GetItemById(_itemId);
            string dosage = lblBUnit.Text;
            double amc = Builder.CalculateAverageConsumption(_itemId, _storeId, _dtCurrent.Subtract(TimeSpan.FromDays(180)), _dtCurrent, CalculationOptions.Monthly);//bal.CalculateAMC(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);
            Int64 soh = bal.GetSOH(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);
            double sohPrice = bal.GetSOHAmount(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);
            string sohPriStr = ((sohPrice != 0) ? sohPrice.ToString("C") + " ETB" : "0 ETB");
            // this can not be done cuz it works only for current year
            // Int64 soh = itm.GetSOHQtyAmount(itemId, storeId);

            double min = (amc * info.Min); //Int64 min = (amc * info.Min);
            double max = (amc * info.Max);  //Int64 max = (amc * info.Max);
            double eop = amc * (info.EOP + 0.25);
            double beloweop = amc * (info.EOP - 0.25);
            double reorder = max - soh;
            double mos = (amc > 0) ? (Convert.ToDouble(soh) / Convert.ToDouble(amc)) : 0;
            object[] obj = itm.GetExpiredQtyAmountItemsByID(_itemId, _storeId);
            Int64 expAmount = Convert.ToInt64(obj[0]);
            Double expCost = Convert.ToDouble(obj[1]);
            string expBirr = ((expCost != 0) ? " in ETB " + expCost.ToString("C") : " Price NA");
            object[] nearObj = itm.GetNearlyExpiredQtyAmountItemsByID(_itemId, _storeId);
            Int64 nearExpAmount = Convert.ToInt64(nearObj[0]);
            double nearExpCost = Convert.ToDouble(nearObj[1]);
            string nearExpBirr = ((nearExpCost != 0) ? " in ETB " + nearExpCost.ToString("C") : " Price NA");
            txtSOH.Text = (soh != 0) ? soh.ToString("#,###") + " - " + dosage + ", " + sohPriStr : "0 - " + dosage;
            txtAMC.Text = (amc != 0) ? amc.ToString("#,###") + " - " + dosage : "0" + " - " + dosage;
            txtMin.Text = (min != 0) ? min.ToString("#,###") + " - " + dosage : "0" + " - " + dosage;
            txtMax.Text = (max != 0) ? max.ToString("#,###") + " - " + dosage : "0" + " - " + dosage;
            txtMOS.Text = mos.ToString("#,###.0#");
            txtReorderAmount.Text = (reorder <= 0) ? "0 - " + dosage : reorder.ToString("#,###") + " - " + dosage;
            txtExpiredAmount.Text = (expAmount != 0) ? "Qty: " + expAmount.ToString("#,###") + " - " + dosage + expBirr : "0";
            txtNearExp.Text = (nearExpAmount != 0) ? nearExpAmount.ToString("#,###") + " - " + dosage + nearExpBirr : "0";

            DateTime dtTran = new DateTime();
            //dtDate.Value = DateTime.Now;
            //dtDate.CustomFormat = "MM/dd/yyyy";

            TimeSpan tt = new TimeSpan();
            if (soh == 0)
            {
                lblstat.Text = "Stocked Out";
                lblStatus.Text = "Stocked Out";
                lblCurStatus.Text = "Stocked Out";
                dtTran = itm.GetLastIssuedDate(_itemId, _storeId);
                tt = new TimeSpan(_dtCurrent.Ticks - dtTran.Ticks);
                lblTime.Text = " For the past " + tt.TotalDays.ToString() + " Days";
            }
            else if (soh > max && max != 0)
            {
                lblstat.Text = "Over Stock";
                lblStatus.Text = "Over Stock";
                lblCurStatus.Text = "Over Stock";
                dtTran = itm.GetLastReceiveDate(_itemId, _storeId);
                tt = new TimeSpan(_dtCurrent.Ticks - dtTran.Ticks);
                lblTime.Text = " For the past " + tt.TotalDays.ToString() + " Days";
            }
            else if (soh > beloweop && soh <= eop)
            {
                lblstat.Text = "Near EOP";
                lblStatus.Text = "Near EOP";
                lblCurStatus.Text = "Near EOP";
                dtTran = itm.GetLastIssuedDate(_itemId, _storeId);
                tt = new TimeSpan(_dtCurrent.Ticks - dtTran.Ticks);
                lblTime.Text = " For the past " + tt.TotalDays.ToString() + " Days";
            }
            else if (soh > 0 && soh <= beloweop)
            {
                lblstat.Text = "Below EOP";
                lblStatus.Text = "Below EOP";
                lblCurStatus.Text = "Below EOP";
                dtTran = itm.GetLastIssuedDate(_itemId, _storeId);
                tt = new TimeSpan(_dtCurrent.Ticks - dtTran.Ticks);
                lblTime.Text = " For the past " + tt.TotalDays.ToString() + " Days";
            }
            else if (soh > eop && soh <= min)
            {
                lblstat.Text = "Below Min";
                lblStatus.Text = "Below Min";
                lblCurStatus.Text = "Below Min";
                dtTran = itm.GetLastIssuedDate(_itemId, _storeId);
                tt = new TimeSpan(_dtCurrent.Ticks - dtTran.Ticks);
                lblTime.Text = " For the past " + tt.TotalDays.ToString() + " Days";
            }
            else //if (soh> min && soh <= max)
            {
                lblstat.Text = "Normal";
                lblStatus.Text = "Normal";
                lblCurStatus.Text = "Normal";

            }
            //}
            //else
            //{
            //    lblCurStatus.Text = "Stocked Out";

            //    lblTime.Text = " Never been received!";
            //}
        }
        private void PopulateLogisticSummary()
        {
            //dtDate.Value = DateTime.Now;
            //    dtDate.CustomFormat = "MM/dd/yyyy";
            //DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);

            ReceivingUnits du = new ReceivingUnits();
            DataTable dtDus = du.GetApplicableDUsAll(_itemId);
            Balance bal = new Balance();
            IssueDoc iss = new IssueDoc();
            Stores stor = new Stores();
            stor.GetActiveStores();
            DataTable dtStores = stor.DefaultView.ToTable();

            DataTable dtbl = new DataTable();
            dtbl.Columns.Add("StoreName");
            dtbl.Columns.Add("SOH");
            dtbl.Columns.Add("AMC");
            dtbl.Columns.Add("Issue");
            dtbl.Columns.Add("MOS");

            foreach (DataRow drStr in dtStores.Rows)
            {
                int storeId = Convert.ToInt32(drStr["ID"]);
                Int64 soh = bal.GetSOH(_itemId, storeId, _dtCurrent.Month, _dtCurrent.Year);
                double amc = Builder.CalculateAverageConsumption(_itemId, storeId, _dtCurrent.Subtract(TimeSpan.FromDays(180)), _dtCurrent, CalculationOptions.Monthly); //bal.CalculateAMC(_itemId, storeId, _dtCurrent.Month, _dtCurrent.Year); //Builder.CalculateAverageConsumption(_itemId, storeId,dtCurrent.Subtract(TimeSpan.FromDays(180)),dtCurrent,CalculationOptions.Monthly);
                //bal.CalculateAMC(_itemId, storeId, _dtCurrent.Month, _dtCurrent.Year);
                Int64 issue = iss.GetIssuedQuantityByMonth(_itemId, storeId, _dtCurrent.Month, _dtCurrent.Year);
                decimal mos = ((amc > 0) ? Convert.ToDecimal(soh) / Convert.ToDecimal(amc) : 0);
                mos = Decimal.Round(mos, 1);

                string[] str = { drStr["StoreName"].ToString(), ((soh != 0) ? soh.ToString("#,###") : "0"), ((amc != 0) ? amc.ToString("#,###") : "0"), ((issue != 0) ? issue.ToString("#,###") : "0"), mos.ToString() };
                dtbl.Rows.Add(str);
            }

            foreach (DataRow drDus in dtDus.Rows)
            {
                int duid = Convert.ToInt32(drDus["ID"]);
                Int64 soh = bal.GetDUSOH(_itemId, duid, _dtCurrent.Month, _dtCurrent.Year);
                double amc = Builder.CalculateAverageConsumption(_itemId, duid, _dtCurrent.Subtract(TimeSpan.FromDays(180)), _dtCurrent, CalculationOptions.Monthly);//bal.CalculateDUAMC(_itemId, duid, _dtCurrent.Month, _dtCurrent.Year, 0);
                Int64 issue = iss.GetDUIssueByMonth(_itemId, duid, _dtCurrent.Month, _dtCurrent.Year);
                decimal mos = ((amc > 0) ? Convert.ToDecimal(soh) / Convert.ToDecimal(amc) : 0);
                mos = Decimal.Round(mos, 1);

                string[] str = { drDus["Name"].ToString(), ((soh != 0) ? soh.ToString("#,###") : "0"), ((amc != 0) ? amc.ToString("#,###") : "0"), ((issue != 0) ? issue.ToString("#,###") : "0"), mos.ToString() };
                dtbl.Rows.Add(str);
            }

            gridDispensaryView.DataSource = dtbl;
        }
        /// <summary>
        /// Generates Past 12 Months charts
        /// </summary>
        private void GenerateChartsPastMonths()
        {
            Balance bal = new Balance();
            GeneralInfo info = new GeneralInfo();
            info.LoadAll();
            DataTable dtList = new DataTable();
            DataTable dtAmc = new DataTable();
            DataTable dtMOS = new DataTable();
            DataTable dtIss = new DataTable();
            DataTable dtRec = new DataTable();
            DataTable dtBB = new DataTable();

            //foreach(string s in co)
            //{
            dtList.Columns.Add("Month");
            dtList.Columns.Add("Value");
            dtList.Columns[1].DataType = typeof(Int64);

            dtMOS.Columns.Add("Month");
            dtMOS.Columns.Add("Value");
            dtMOS.Columns[1].DataType = typeof(Int32);

            dtAmc.Columns.Add("Month");
            dtAmc.Columns.Add("Value");
            dtAmc.Columns[1].DataType = typeof(Int64);

            dtIss.Columns.Add("Month");
            dtIss.Columns.Add("Value");
            dtIss.Columns[1].DataType = typeof(Int64);

            dtRec.Columns.Add("Month");
            dtRec.Columns.Add("Value");
            dtRec.Columns[1].DataType = typeof(Int64);

            dtBB.Columns.Add("Month");
            dtBB.Columns.Add("Value");
            dtBB.Columns[1].DataType = typeof(Int64);

            //dtDate.Value = DateTime.Now;
            //dtDate.CustomFormat = "MM/dd/yyyy";
            //DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
            DateTime dtPast = _dtCurrent.AddMonths(-11);
            //CALENDAR:
            string[] wer = { "Mes", "Tek", "Hed", "Tah", "Tir", "Yek", "Meg", "Miz", "Gen", "Sen", "Ham", "Neh" };
            string[] co = new string[12];
            int[] mon = new int[12];
            int[] yr = new int[12];
            int intialM = dtPast.Month;
            int j = 0;
            while (dtPast <= _dtCurrent && j < 12)
            {
                //mon[j] = intialM;
                //co[j] = wer[intialM-1];
                //yr[j] = (intialM < 11)?dtPast.Year: dtPast.Year +1;
                //dtPast = dtPast.AddMonths(1);
                //intialM = dtPast.Month;
                mon[j] = dtPast.Month;
                co[j] = wer[intialM - 1];
                yr[j] = dtPast.Year;
                dtPast = dtPast.AddMonths(1);
                intialM = dtPast.Month;
                j++;
            }
            //{ 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            long[] cons = new long[12];
            long[] amc = new long[12];
            DataTable dtBal = new DataTable();
            IssueDoc issd = new IssueDoc();
            Items recd = new Items();

            YearEnd yEnd = new YearEnd();
            Int64 bb = yEnd.GetBBalance(_year, _storeId, _itemId, 10);
            object[] objBB = { "Ham", bb };
            dtBB.Rows.Add(objBB);

            for (int i = 0; i < mon.Length; i++)
            {
                Int64 con = bal.GetSOH(_itemId, _storeId, mon[i], yr[i]);
                object[] str = { co[i], con };
                amc[i] = bal.CalculateAMC(_itemId, _storeId, mon[i], yr[i]);
                object[] objAmc = { co[i], amc[i] };
                decimal mos = (amc[i] > 0) ? (Convert.ToDecimal(con) / Convert.ToDecimal(amc[i])) : 0;
                mos = Decimal.Round(mos, 1);

                object[] objMos = { co[i], mos };
                Int64 issval = issd.GetIssuedQuantityByMonth(_itemId, _storeId, mon[i], yr[i]);
                object[] objIss = { co[i], issval };

                Int64 recVal = recd.GetQuantityReceiveByItemPerMonth(mon[i], _itemId, _storeId, yr[i]);
                object[] objrec = { co[i], recVal };

                dtList.Rows.Add(str);
                dtAmc.Rows.Add(objAmc);
                dtMOS.Rows.Add(objMos);
                dtIss.Rows.Add(objIss);
                dtRec.Rows.Add(objrec);
                //}
            }
            // string[] str = { ((cons[0] != 0) ? cons[0].ToString("") : "0"), ((cons[1] != 0) ? cons[1].ToString() : "0"), ((cons[2] != 0) ? cons[2].ToString() : "0"), ((cons[3] != 0) ? cons[3].ToString() : "0"), ((cons[4] != 0) ? cons[4].ToString() : "0"), ((cons[5] != 0) ? cons[5].ToString() : "0"), ((cons[6] != 0) ? cons[6].ToString() : "0"), ((cons[7] != 0) ? cons[7].ToString() : "0"), ((cons[8] != 0) ? cons[8].ToString() : "0"), ((cons[9] != 0) ? cons[9].ToString() : "0"), ((cons[10] != 0) ? cons[10].ToString() : "0"), ((cons[11] != 0) ? cons[11].ToString() : "0")};
            chartAmc.Series.Clear();
            chartComp.Series.Clear();
            chartBar.Series.Clear();
            chartMOS.Series.Clear();
            consuTrend.Series.Clear();

            Series ser = new Series("Stock On Hand", ViewType.Line);
            ser.DataSource = dtList;
            ser.ArgumentScaleType = ScaleType.Qualitative;
            ser.ArgumentDataMember = "Month";
            ser.ValueScaleType = ScaleType.Numerical;
            ser.ValueDataMembers.AddRange(new string[] { "Value" });
            chartBar.Series.Add(ser);

            Series serB = new Series("Begining Balance", ViewType.Bar);
            serB.DataSource = dtBB;
            serB.ArgumentScaleType = ScaleType.Qualitative;
            serB.ArgumentDataMember = "Month";
            serB.ValueScaleType = ScaleType.Numerical;
            serB.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serB.PointOptions.ValueNumericOptions.Precision = 0;
            serB.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serB);

            Series serRec = new Series("Received Qty", ViewType.Bar);
            serRec.DataSource = dtRec;
            serRec.ArgumentScaleType = ScaleType.Qualitative;
            serRec.ArgumentDataMember = "Month";
            serRec.ValueScaleType = ScaleType.Numerical;
            serRec.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serRec);

            Series serAmc = new Series("Average Monthly Consumption", ViewType.Line);
            serAmc.DataSource = dtAmc;
            serAmc.ArgumentScaleType = ScaleType.Qualitative;
            serAmc.ArgumentDataMember = "Month";
            serAmc.ValueScaleType = ScaleType.Numerical;
            serAmc.ValueDataMembers.AddRange(new string[] { "Value" });
            chartAmc.Series.Add(serAmc);

            Series serIss = new Series("Issue Qty", ViewType.Bar);
            serIss.DataSource = dtIss;
            serIss.ArgumentScaleType = ScaleType.Qualitative;
            serIss.ArgumentDataMember = "Month";
            serIss.ValueScaleType = ScaleType.Numerical;
            serIss.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serIss);

            Series serSOH = new Series("SOH", ViewType.Bar);
            serSOH.DataSource = dtList;
            serSOH.ArgumentScaleType = ScaleType.Qualitative;
            serSOH.ArgumentDataMember = "Month";
            serSOH.ValueScaleType = ScaleType.Numerical;
            serSOH.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serSOH);

            Series sercons = new Series("Consumption Trend", ViewType.Line);
            sercons.DataSource = dtIss;
            sercons.ArgumentScaleType = ScaleType.Qualitative;
            sercons.ArgumentDataMember = "Month";
            sercons.ValueScaleType = ScaleType.Numerical;
            sercons.ValueDataMembers.AddRange(new string[] { "Value" });
            consuTrend.Series.Add(sercons);

            Series serMos = new Series("Month Of Stock", ViewType.Line);
            serMos.DataSource = dtMOS;
            serMos.ArgumentScaleType = ScaleType.Qualitative;
            serMos.ArgumentDataMember = "Month";
            serMos.ValueScaleType = ScaleType.Numerical;
            serMos.ValueDataMembers.AddRange(new string[] { "Value" });

            chartMOS.Series.Add(serMos);
            ((XYDiagram)chartMOS.Diagram).AxisY.Range.MaxValue = 12;

            Int64 amcCurent = bal.CalculateAMC(_itemId, _storeId, _dtCurrent.Month, _year);
            //Int64 soh = bal.GetSOH(itemId,storeId,dtCurrent.Month,year);
            //if (bal.RowCount > 0)
            //{
            Int64 min = info.Min * amcCurent;
            Int64 max = info.Max * amcCurent;
            ConstantLine target = new ConstantLine();
            target.AxisValue = min;
            //which min and max to show month
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Clear();
            target.Visible = true;
            target.Title.Text = "Current Min value is " + target.AxisValue.ToString() + " " + lblBUnit.Text;
            target.Color = Color.Red;
            target.LineStyle.Thickness = 2;
            // ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(target);

            ConstantLine targetMax = new ConstantLine();
            targetMax.AxisValue = max;
            //which min and max to show month
            targetMax.Visible = true;
            targetMax.Title.Text = "Current Max value is " + targetMax.AxisValue.ToString() + " " + lblBUnit.Text;
            targetMax.Color = Color.Blue;
            targetMax.LineStyle.Thickness = 2;
            //((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(targetMax);
            //}
        }
        /// <summary>
        /// Generates the charts one by one.
        /// </summary>
        /// <param name="du"></param>
        private void GenerateCharts(int du)
        {
            Balance bal = new Balance();
            GeneralInfo info = new GeneralInfo();
            info.LoadAll();
            DataTable dtList = new DataTable();
            DataTable dtAmc = new DataTable();
            DataTable dtMOS = new DataTable();
            DataTable dtIss = new DataTable();
            DataTable dtRec = new DataTable();
            DataTable dtBB = new DataTable();
            //CALENDAR:
            //  DataTable dtCons = new DataTable();
            string[] co = { "Ham", "Neh", "Mes", "Tek", "Hed", "Tah", "Tir", "Yek", "Meg", "Miz", "Gen", "Sen" };

            //foreach(string s in co)
            //{
            dtList.Columns.Add("Month");
            dtList.Columns.Add("Value");
            dtList.Columns[1].DataType = typeof(Int64);

            dtMOS.Columns.Add("Month");
            dtMOS.Columns.Add("Value");
            dtMOS.Columns[1].DataType = typeof(decimal);

            dtAmc.Columns.Add("Month");
            dtAmc.Columns.Add("Value");
            dtAmc.Columns[1].DataType = typeof(Int64);

            dtIss.Columns.Add("Month");
            dtIss.Columns.Add("Value");
            dtIss.Columns[1].DataType = typeof(Int64);

            dtRec.Columns.Add("Month");
            dtRec.Columns.Add("Value");
            dtRec.Columns[1].DataType = typeof(Int64);

            dtBB.Columns.Add("Month");
            dtBB.Columns.Add("Value");
            dtBB.Columns[1].DataType = typeof(Int64);

            int[] mon = { 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            long[] cons = new long[12];
            double[] amc = new double[12];
            long[] con = new long[12];
            long[] issval = new long[12];
            DataTable dtBal = new DataTable();
            IssueDoc issd = new IssueDoc();
            Items recd = new Items();
            YearEnd yEnd = new YearEnd();
            Int64 bb = yEnd.GetBBalance(_year, _storeId, _itemId, 10);
            object[] objBB = { "Ham", bb };
            dtBB.Rows.Add(objBB);
            //dtDate.Value = DateTime.Now;
            //dtDate.CustomFormat = "MM/dd/yyyy";
            //DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);

            for (int i = 0; i < mon.Length; i++)
            {
                int cMonth = _dtCurrent.Month;
                //if (!(year == dtCurrent.Year && mon[i] > dtCurrent.Month && mon[i] < 11))
                if (((mon[i] == 11 || mon[i] == 12) && (mon[i] <= cMonth || _year == _dtCurrent.Year)) || (mon[i] < 11 && mon[i] <= cMonth && _year == _dtCurrent.Year))
                {
                    int yr = (mon[i] < 11) ? _year : _year - 1;
                    // dtBal = bal.GetSOH(itemId,storeId,mon[i],yr);
                    con[i] = ((du == 0) ? bal.GetSOH(_itemId, _storeId, mon[i], yr) : bal.GetDUSOH(_itemId, du, mon[i], yr));
                    object xSOH = null;
                    if (con[i] == 0)
                    {
                        for (int li = i; li >= 0; li--)
                        {
                            if (con[li] != 0)
                            {
                                xSOH = 0;
                                break;
                            }
                        }
                    }
                    else
                        xSOH = con[i];
                    object[] str = { co[i], xSOH };
                    amc[i] = ((du == 0) ? Builder.CalculateAverageConsumption(_itemId, _storeId, _dtCurrent.Subtract(TimeSpan.FromDays(180)), _dtCurrent, CalculationOptions.Monthly) : bal.CalculateDUAMC(_itemId, du, mon[i], yr, 0));//bal.CalculateAMC(_itemId, _storeId, mon[i], yr)
                    object xAmc = null;
                    if (amc[i] == 0)
                    {
                        for (int li = i; li >= 0; li--)
                        {
                            if (amc[li] != 0)
                            {
                                xAmc = 0;
                                break;
                            }
                        }
                    }
                    else
                        xAmc = amc[i];
                    object[] objAmc = { co[i], xAmc };

                    // for mos check the diff b/n null and zero
                    // And also mos = soh/amc right???
                    decimal mos = (amc[i] > 0) ? (Convert.ToDecimal(con[i]) / Convert.ToDecimal(amc[i])) : 0;
                    object[] objMos = { co[i], mos };
                    int fYear = (mon[i] < 11) ? yr : yr - 1;

                    issval[i] = ((du == 0) ? issd.GetIssuedQuantityByMonth(_itemId, _storeId, mon[i], yr) : issd.GetDUConsumptionByMonth(_itemId, du, mon[i], yr));
                    object xIss = null;
                    if (issval[i] == 0)
                    {
                        for (int li = i; li >= 0; li--)
                        {
                            if (issval[li] != 0)
                            {
                                xIss = 0;
                                break;
                            }
                        }
                    }
                    else
                        xIss = issval[i];
                    object[] objIss = { co[i], xIss };

                    Int64 recVal = ((du == 0) ? recd.GetQuantityReceiveByItemPerMonth(mon[i], _itemId, _storeId, yr) : issd.GetDUReceiveByMonth(_itemId, du, mon[i], yr));
                    object[] objrec = { co[i], recVal };

                    dtList.Rows.Add(str);
                    dtAmc.Rows.Add(objAmc);
                    dtMOS.Rows.Add(objMos);
                    dtIss.Rows.Add(objIss);
                    dtRec.Rows.Add(objrec);
                }
            }

            // string[] str = { ((cons[0] != 0) ? cons[0].ToString("") : "0"), ((cons[1] != 0) ? cons[1].ToString() : "0"), ((cons[2] != 0) ? cons[2].ToString() : "0"), ((cons[3] != 0) ? cons[3].ToString() : "0"), ((cons[4] != 0) ? cons[4].ToString() : "0"), ((cons[5] != 0) ? cons[5].ToString() : "0"), ((cons[6] != 0) ? cons[6].ToString() : "0"), ((cons[7] != 0) ? cons[7].ToString() : "0"), ((cons[8] != 0) ? cons[8].ToString() : "0"), ((cons[9] != 0) ? cons[9].ToString() : "0"), ((cons[10] != 0) ? cons[10].ToString() : "0"), ((cons[11] != 0) ? cons[11].ToString() : "0")};
            chartAmc.Series.Clear(); //AMC
            chartComp.Series.Clear();//Activity
            chartBar.Series.Clear(); //SOH
            chartMOS.Series.Clear(); // MOS
            consuTrend.Series.Clear();

            Series ser = new Series("Stock On Hand", ViewType.Line);
            ser.DataSource = dtList;
            ser.ArgumentScaleType = ScaleType.Qualitative;
            ser.ArgumentDataMember = "Month";
            ser.ValueScaleType = ScaleType.Numerical;
            ser.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            ser.PointOptions.ValueNumericOptions.Precision = 0;
            ser.ValueDataMembers.AddRange(new string[] { "Value" });

            chartBar.Series.Add(ser);
            ((XYDiagram)chartBar.Diagram).AxisY.NumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)chartBar.Diagram).AxisY.NumericOptions.Precision = 0;

            Series serB = new Series("Begining Balance", ViewType.Bar);
            serB.DataSource = dtBB;
            serB.ArgumentScaleType = ScaleType.Qualitative;
            serB.ArgumentDataMember = "Month";
            serB.ValueScaleType = ScaleType.Numerical;
            serB.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serB.PointOptions.ValueNumericOptions.Precision = 0;
            serB.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serB);

            Series serRec = new Series("Received Qty", ViewType.Bar);
            serRec.DataSource = dtRec;
            serRec.ArgumentScaleType = ScaleType.Qualitative;
            serRec.ArgumentDataMember = "Month";
            serRec.ValueScaleType = ScaleType.Numerical;
            serRec.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serRec.PointOptions.ValueNumericOptions.Precision = 0;
            serRec.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serRec);

            Series serAmc = new Series("AMC", ViewType.Line);
            serAmc.DataSource = dtAmc;
            serAmc.ArgumentScaleType = ScaleType.Qualitative;
            serAmc.ArgumentDataMember = "Month";
            serAmc.ValueScaleType = ScaleType.Numerical;
            serAmc.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serAmc.PointOptions.ValueNumericOptions.Precision = 0;
            serAmc.ValueDataMembers.AddRange(new string[] { "Value" });
            chartAmc.Series.Add(serAmc);
            ((XYDiagram)chartAmc.Diagram).AxisY.NumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)chartAmc.Diagram).AxisY.NumericOptions.Precision = 0;

            Series serIss = new Series("Issue Qty", ViewType.Bar);
            serIss.DataSource = dtIss;
            serIss.ArgumentScaleType = ScaleType.Qualitative;
            serIss.ArgumentDataMember = "Month";
            serIss.ValueScaleType = ScaleType.Numerical;
            serIss.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            serIss.PointOptions.ValueNumericOptions.Precision = 0;
            serIss.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serIss);

            //Int64 amcCurent = bal.CalculateAMC(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);
            double amcCurent = Builder.CalculateAverageConsumption(_itemId, _storeId,
                                                                   _dtCurrent.Subtract(TimeSpan.FromDays(180)),
                                                                   _dtCurrent, CalculationOptions.Monthly);
            double min = info.Min * amcCurent;
            double max = info.Max * amcCurent;
            Int64 nearEOP = Convert.ToInt64(amcCurent * (info.EOP + 0.25));
            ConstantLine target = new ConstantLine();
            ConstantLine targetEOP = new ConstantLine();
            target.AxisValue = min;
            //which min and max to show month
            ((XYDiagram)chartComp.Diagram).AxisY.ConstantLines.Clear();
            target.Visible = true;
            target.Title.Text = "Current Min value is " + Convert.ToInt64(target.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            target.Color = Color.Red;
            target.LineStyle.Thickness = 2;
            target.LegendText = "Min";
            ((XYDiagram)chartComp.Diagram).AxisY.ConstantLines.Add(target);

            targetEOP = new ConstantLine();
            targetEOP.AxisValue = nearEOP;
            //which min and max to show month
            //((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Clear();
            targetEOP.Visible = true;
            targetEOP.Title.Text = "Current EOP value is " + Convert.ToInt64(targetEOP.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            targetEOP.Color = Color.Yellow;
            targetEOP.LineStyle.Thickness = 2;
            targetEOP.LegendText = "EOP";
            ((XYDiagram)chartComp.Diagram).AxisY.ConstantLines.Add(targetEOP);

            ConstantLine targetMax = new ConstantLine();
            targetMax.AxisValue = max;
            //which min and max to show month
            targetMax.Visible = true;
            targetMax.Title.Text = "Current Max value is " + Convert.ToInt64(targetMax.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            targetMax.Color = Color.Blue;
            targetMax.LineStyle.Thickness = 2;
            targetMax.LegendText = "Max";
            ((XYDiagram)chartComp.Diagram).AxisY.ConstantLines.Add(targetMax);

            Series sercons = new Series("Consumption", ViewType.Line);
            sercons.DataSource = dtIss;
            sercons.ArgumentScaleType = ScaleType.Qualitative;
            sercons.ArgumentDataMember = "Month";
            sercons.ValueScaleType = ScaleType.Numerical;
            sercons.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            sercons.PointOptions.ValueNumericOptions.Precision = 0;
            sercons.ValueDataMembers.AddRange(new string[] { "Value" });
            consuTrend.Series.Add(sercons);
            ((XYDiagram)consuTrend.Diagram).AxisY.NumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)consuTrend.Diagram).AxisY.NumericOptions.Precision = 0;

            Series serSOH = new Series("SOH", ViewType.Bar);
            serSOH.DataSource = dtList;
            serSOH.ArgumentScaleType = ScaleType.Qualitative;
            serSOH.ArgumentDataMember = "Month";
            serSOH.ValueScaleType = ScaleType.Numerical;
            serSOH.PointOptions.ValueNumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)chartComp.Diagram).AxisY.NumericOptions.Format = NumericFormat.Number;
            ((XYDiagram)chartComp.Diagram).AxisY.NumericOptions.Precision = 0;
            serSOH.PointOptions.ValueNumericOptions.Precision = 0;

            serSOH.ValueDataMembers.AddRange(new string[] { "Value" });
            chartComp.Series.Add(serSOH);

            Series serMos = new Series("Month Of Stock", ViewType.Line);
            serMos.DataSource = dtMOS;
            serMos.ArgumentScaleType = ScaleType.Qualitative;
            serMos.ArgumentDataMember = "Month";
            serMos.ValueScaleType = ScaleType.Numerical;
            serMos.PointOptions.ValueNumericOptions.Format = NumericFormat.FixedPoint;
            serMos.PointOptions.ValueNumericOptions.Precision = 1;
            serMos.ValueDataMembers.AddRange(new string[] { "Value" });

            chartMOS.Series.Add(serMos);
            if (Convert.ToInt32(((XYDiagram)chartMOS.Diagram).AxisY.Range.MaxValue) <= 12)
            {
                ((XYDiagram)chartMOS.Diagram).AxisY.Range.MaxValue = 12;
            }

            //Int64 soh = bal.GetSOH(itemId,storeId,dtCurrent.Month,year);
            //if (bal.RowCount > 0)
            //{
            //Int64 amcCurent = bal.CalculateAMC(_itemId, _storeId, _dtCurrent.Month, _year);
            amcCurent = Builder.CalculateAverageConsumption(_itemId, _storeId,
                                                                  _dtCurrent.Subtract(TimeSpan.FromDays(180)),
                                                                  _dtCurrent, CalculationOptions.Monthly);
            min = info.Min * amcCurent;
            max = info.Max * amcCurent;
            nearEOP = Convert.ToInt64(amcCurent * (info.EOP + 0.25));
            target = new ConstantLine();
            target.AxisValue = min;
            //which min and max to show month
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Clear();
            target.Visible = true;
            target.Title.Text = "Current Min value is " + Convert.ToInt64(target.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            target.Color = Color.Red;
            target.LineStyle.Thickness = 2;
            target.LegendText = "Min";
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(target);

            targetEOP = new ConstantLine();
            targetEOP.AxisValue = nearEOP;
            //which min and max to show month
            //((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Clear();
            targetEOP.Visible = true;
            targetEOP.Title.Text = "Current EOP value is " + Convert.ToInt64(targetEOP.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            targetEOP.Color = Color.Yellow;
            targetEOP.LineStyle.Thickness = 2;
            targetEOP.LegendText = "EOP";
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(targetEOP);

            targetMax = new ConstantLine();
            targetMax.AxisValue = max;
            //which min and max to show month
            targetMax.Visible = true;
            targetMax.Title.Text = "Current Max value is " + Convert.ToInt64(targetMax.AxisValue).ToString("#,###") + " " + lblBUnit.Text;
            targetMax.Color = Color.Blue;
            targetMax.LineStyle.Thickness = 2;
            targetMax.LegendText = "Max";
            ((XYDiagram)chartBar.Diagram).AxisY.ConstantLines.Add(targetMax);

            ConstantLine targetMos = new ConstantLine();
            ConstantLine targetMosMin = new ConstantLine();
            ((XYDiagram)chartMOS.Diagram).AxisY.ConstantLines.Clear();
            targetMos = new ConstantLine();
            targetMos.AxisValue = info.Max;
            //which min and max to show month
            targetMos.Visible = true;
            targetMos.Title.Text = "Current Max is " + info.Max.ToString() + " months";
            targetMos.Color = Color.Blue;
            targetMos.LineStyle.Thickness = 2;
            targetMos.LegendText = "Max";
            ((XYDiagram)chartMOS.Diagram).AxisY.ConstantLines.Add(targetMos);

            targetMosMin = new ConstantLine();
            targetMosMin.AxisValue = info.Min;
            //which min and max to show month
            targetMosMin.Visible = true;
            targetMosMin.Title.Text = "Current Min is " + info.Min.ToString() + " months";
            targetMosMin.Color = Color.Red;
            targetMosMin.LineStyle.Thickness = 2;
            targetMosMin.LegendText = "Max";
            ((XYDiagram)chartMOS.Diagram).AxisY.ConstantLines.Add(targetMosMin);
            //}

            // Generate the pie Chart for the Current SOH and EXpired Drugs

            ReceiveDoc rec = new ReceiveDoc();
            chartPie.Series.Clear();
            Items itm = new Items();
            object[] objExp = itm.GetExpiredQtyAmountItemsByID(_itemId, _storeId);
            Int64 expAmount = Convert.ToInt64(objExp[0]);
            Double expCost = Convert.ToDouble(objExp[1]);

            object[] nearObj = itm.GetNearlyExpiredQtyAmountItemsByID(_itemId, _storeId);
            Int64 nearExpAmount = Convert.ToInt64(nearObj[0]);
            double nearExpCost = Convert.ToDouble(nearObj[1]);

            Int64 soh = bal.GetSOH(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);
            double sohPrice = bal.GetSOHAmount(_itemId, _storeId, _dtCurrent.Month, _dtCurrent.Year);

            Int64 normal = (soh - nearExpAmount - expAmount);
            Int64 nearExpiry = nearExpAmount;
            Int64 expired = expAmount;

            object[] obj = { normal, nearExpiry, expired };

            DataTable dtSOHList = new DataTable();
            dtSOHList.Columns.Add("Type");
            dtSOHList.Columns.Add("Value");
            dtSOHList.Columns[1].DataType = typeof(Int64);
            double normalPrice = (sohPrice - nearExpCost - expAmount);

            object[] oo = { "Normal : " + normalPrice.ToString("C"), obj[0] };
            dtSOHList.Rows.Add(oo);

            object[] oo3 = { "Expired : " + expCost.ToString("C"), obj[2] };
            dtSOHList.Rows.Add(oo3);

            object[] oo2 = { "Near Expiry : " + nearExpCost.ToString("C"), obj[1] };
            dtSOHList.Rows.Add(oo2);

            Series serExpired = new Series("pie", ViewType.Pie3D);
            if (!(Convert.ToInt32(obj[0]) == 0 && Convert.ToInt32(obj[1]) == 0 && Convert.ToInt32(obj[2]) == 0))
            {
                serExpired.DataSource = dtSOHList;

                serExpired.ArgumentScaleType = ScaleType.Qualitative;
                serExpired.ArgumentDataMember = "Type";
                serExpired.ValueScaleType = ScaleType.Numerical;
                serExpired.ValueDataMembers.AddRange(new string[] { "Value" });
                serExpired.PointOptions.PointView = PointView.ArgumentAndValues;
                serExpired.LegendText = "Key";
                serExpired.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
                serExpired.PointOptions.ValueNumericOptions.Precision = 0;
                ((PieSeriesLabel)serExpired.Label).Position = PieSeriesLabelPosition.TwoColumns;
                // ((PieSeriesLabel)serExpired.Label).ColumnIndent = 2;
                ((PiePointOptions)serExpired.PointOptions).PointView = PointView.ArgumentAndValues;
                // ((PiePointOptions)serExpired.PointOptions).Separator = " , ";
                chartPie.Series.Add(serExpired);
                chartPie.Size = new System.Drawing.Size(1000, 500);
            }
        }
        public void PopulateItemListByMonth(DataTable dtItem,int month,int year)
        {
            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Value = 1;
            progressBar1.Maximum = dtItem.Rows.Count;

            GeneralInfo pipline = new GeneralInfo();
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            double eop = pipline.EOP;
            int storeId = (cboStores.SelectedValue != null)?Convert.ToInt32(cboStores.SelectedValue):1;

            lstItem.Items.Clear();

            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            DateTime dtCurrent = new DateTime();// Convert.ToDateTime(dtDate.Text);
            try
            {
                dtCurrent = Convert.ToDateTime(dtDate.Text);
            }
            catch
            {
                string dtValid = "";
                string yer = "";
                if (Convert.ToInt32(dtDate.Text.Substring(0, 2)) == 13)
                {
                    dtValid = dtDate.Text;
                    yer = dtValid.Substring(dtValid.Length - 4, 4);
                    dtCurrent = Convert.ToDateTime("12/30/" + yer);
                }
                else if (Convert.ToInt32(dtDate.Text.Substring(0, 2)) == 2)
                {
                    dtValid = dtDate.Text;
                    yer = dtValid.Substring(dtValid.Length - 4, 4);
                    dtCurrent = Convert.ToDateTime("2/28/" + yer);
                }
            }
            month = (month < 11)? month +2: ((month ==11)?1:2);
            int yyr = (month < 11)? dtCurrent.Year: dtCurrent.Year -1;

            int count = 1;
            Balance bal = new Balance();
            IssueDoc iss = new IssueDoc();
            foreach (DataRow dr in dtItem.Rows)
            {
                string itemName = dr["ItemName"].ToString() + " - " + dr["DosageForm"].ToString() + " - " + dr["Strength"].ToString();

                int yer = (month < 11) ? year : year - 1;
                double AMC = Builder.CalculateAverageConsumption(Convert.ToInt32(dr["ID"]), storeId,dtCurrent.Subtract(TimeSpan.FromDays(180)),dtCurrent,CalculationOptions.Monthly);//bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, month, yer);
                double MinCon = AMC * min;
                double maxCon = AMC * max;
                double eopCon = AMC * (eop + 0.25);
                Int64 SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, yer);
                decimal MOS = (AMC != 0) ? (Convert.ToDecimal(SOH) / Convert.ToDecimal(AMC)) : 0;
                MOS = Decimal.Round(MOS, 1);

                double reorder = (maxCon > SOH) ? maxCon - SOH : 0;
                string status = (SOH <= eopCon && SOH > 0) ? "Near EOP" : ((SOH > maxCon && maxCon != 0) ? "Excess Stock" : ((SOH <= 0) ? "Stock Out" : "Normal"));
                //Int64 issuedQuant = iss.GetIssuedQuantityByMonth(Convert.ToInt32(dr["ID"]),storeId, month,yer);
                Int64 issuedQuant = iss.GetIssuedQuantity(Convert.ToInt32(dr["ID"]), storeId, yer);
                string[] str = { count.ToString(), itemName, ((SOH != 0)?SOH.ToString("#,###"): "0"), ((AMC != 0)?AMC.ToString("#,###"):"0"), MOS.ToString(), ((MinCon != 0)?MinCon.ToString("#,###"): "0"), ((maxCon != 0)?maxCon.ToString("#,###"):"0"), ((issuedQuant!= 0)?issuedQuant.ToString("#,###"):"0"), status, ((reorder!= 0)?reorder.ToString("#,###"):"0") };
                ListViewItem listItem = new ListViewItem(str);
                listItem.Tag = dr["ID"];
                //if (col != 0)
                //{
                //    listItem.BackColor = Color.FromArgb(233, 247, 248);
                //    col = 0;
                //}
                //else
                //{
                //    col++;
                //}

                string stat = "";
                if(cboStatus.SelectedItem != null)
                    stat = cboStatus.SelectedItem.ToString();

                switch (stat)
                {
                    case "Near EOP":
                        if (SOH <= eopCon && SOH > 0)
                        {
                            listItem.BackColor = Color.FromArgb(255, 255, 153);
                            lstItem.Items.Add(listItem);
                            count++;
                        }
                        break;
                    case "Normal":
                        if (SOH > eopCon && SOH < maxCon)
                        {
                            lstItem.Items.Add(listItem);
                            count++;
                        }
                        break;
                    case "Stock Out":
                        if (SOH <= 0)
                        {
                            listItem.BackColor = Color.FromArgb(246, 168, 168);
                            lstItem.Items.Add(listItem);
                            count++;
                        }
                        break;
                    case "Excess Stock":
                        if (SOH > maxCon && maxCon != 0)
                        {
                            listItem.BackColor = Color.FromArgb(163, 209, 255);
                            lstItem.Items.Add(listItem);
                            count++;
                        }
                        break;
                    default:
                        if (SOH <= eopCon && SOH > 0)
                            listItem.BackColor = Color.FromArgb(255, 255, 153);
                        else if (SOH > maxCon && maxCon != 0)
                            listItem.BackColor = Color.FromArgb(163, 209, 255);
                        else if (SOH <= 0)
                            listItem.BackColor = Color.FromArgb(246, 168, 168);
                        lstItem.Items.Add(listItem);
                        count++;
                        break;
                }
                progressBar1.PerformStep();

            }
            progressBar1.Visible = false;
        }
        /// <summary>
        /// Populates the grid based on the selection.
        /// </summary>
        private void PopulateGridList()
        {
            if (issueGrid.DataSource != null)
            {
                var dt = new DataTable();
                issueGrid.DataSource = dt;
                _dtRecGrid.Rows.Clear();
                _dtRecGrid.Columns.Clear();
            }

            var itm = new Items();
            var itmB = new Items();
            var bal = new Balance();
            _tabPage = 1;
            tabControl1.SelectedTabPageIndex = 1;

            if (_dtRecGrid.Columns.Count == 0)
            {
                string[] str = { "ID", "Stock Code", "Item Name", "Unit", "Store SOH", "Dispatchable", "MR Issue Qty",
                                   "DU Remaining SOH", "DU AMC", "Recommended Qty", "Pack Qty", "Qty Per Pack",
                                   "Requested Qty", "MR DU SOH","UnitID"};
                foreach (string col in str)
                {
                    _dtRecGrid.Columns.Add(col);
                }
            }

            int count = 1;
            Int64 quantity = 0;
            dtIssueDate.Value = DateTime.Now;
            dtIssueDate.CustomFormat = "MM/dd/yyyy";
            var dtCurrent = ConvertDate.DateConverter(dtIssueDate.Text);
            if (_dtSelectedTable != null)
                foreach (DataRow lst in _dtSelectedTable.Rows)//(ListViewItem lst in lstItem.Items)
                {
                    var itmID = Convert.ToInt32(lst["ID"]);
                    var dtExp = itm.GetExpiredItemsByID(Convert.ToInt32(cboStores.EditValue), itmID);
                    var dtItm = itm.GetItemById(itmID);
                    Int64 expAmount = 0;
                    foreach (DataRow dr in dtExp.Rows)
                    {
                        expAmount = itmB.GetExpiredQtyItemsByID(Convert.ToInt32(dr["ID"]), Convert.ToInt32(cboStores.EditValue));
                        quantity = Convert.ToInt64(dr["Quantity"]) - expAmount;//+ adjQuant - issuedQuant - lostQuant
                    }
                    Int64 soh = 0;
                    Int64 dispatchable = Convert.ToInt64(lst["Dispatchable"]);

                    object[] obj;
                    string itemName = lst["FullItemName"].ToString();
                    switch (VisibilitySetting.HandleUnits)
                    {
                        case 1:
                            soh = bal.GetSOH(itmID, Convert.ToInt32(cboStores.EditValue), dtCurrent.Month, dtCurrent.Year);
                            obj = new object[] {itmID.ToString(), dtItm.Rows[0]["StockCode"].ToString(), itemName, dtItm.Rows[0]["Unit"].ToString(),
                                                soh, dispatchable, 0, 0, 0, 0, 0, 0, 0, 0, 0};
                            break;
                        case 2:
                            soh = bal.GetSOHByUnit(itmID, Convert.ToInt32(cboStores.EditValue), dtCurrent.Month, dtCurrent.Year, Convert.ToInt32(lst["UnitID"]));
                            obj = new object[]{ itmID.ToString(), dtItm.Rows[0]["StockCode"].ToString(),
                                                itemName, dtItm.Rows[0]["Unit"].ToString(),
                                                soh, dispatchable, 0, 0, 0, 0, 0, 0, 0, 0, Convert.ToInt32(lst["UnitID"])};
                            break;
                        default:
                            soh = bal.GetSOHByUnit(itmID, Convert.ToInt32(cboStores.EditValue), dtCurrent.Month, dtCurrent.Year, Convert.ToInt32(lst["UnitID"]));
                            obj = new object[]{ itmID.ToString(), dtItm.Rows[0]["StockCode"].ToString(),
                                                itemName, dtItm.Rows[0]["Unit"].ToString(),
                                                soh, dispatchable, 0, 0, 0, 0, 0, 0, 0, 0, Convert.ToInt32(lst["UnitID"])};
                            break;
                    }

                    //if (expAmount < soh && quantity < soh || dispatchable > 0)
                    //{
                    //    _dtRecGrid.Rows.Add(obj);
                    //    count++;
                    //}

                    if (expAmount < soh && dispatchable > 0)
                    {
                        _dtRecGrid.Rows.Add(obj);
                        count++;
                    }
                    else if(soh >0 && dispatchable==0)
                    {
                        XtraMessageBox.Show(String.Format("{0} Is Expired!", itemName), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        ResetValues();
                        tabControl1.TabIndex = 0;
                        break;
                    }
                    else if (soh == 0)
                    {
                      XtraMessageBox.Show(String.Format("{0} is stocked out!", itemName), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        break;
                    }
                    else if (expAmount == soh && expAmount != 0)
                    {
                        XtraMessageBox.Show(String.Format("{0} Is Expired!",itemName), "Warning", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        ResetValues();
                        tabControl1.TabIndex = 0;
                        break;
                    }
                    else if( dispatchable>0 )
                    {
                        _dtRecGrid.Rows.Add(obj);
                        count++;
                    }
                    else
                    {
                        ResetValues();
                        XtraMessageBox.Show("You are trying to issue an Expired item!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                        tabControl1.TabIndex = 0;
                        break;
                    }
                }

            issueGrid.DataSource = _dtRecGrid;
            cboStoreConf.EditValue = cboStores.EditValue;
            dtIssueDate.CustomFormat = "MMM dd,yyyy";

            var recUnit = new ReceivingUnits();
            recUnit.GetActiveDispensaries();
            cboReceivingUnits.Properties.DataSource = recUnit.DefaultView;
            cboReceivingUnits.Properties.DisplayMember = "Name";
            cboReceivingUnits.Properties.ValueMember = "ID";
        }
        public void PopulateItemList(DataTable dtItem)
        {
            lstItem.Items.Clear();
            GeneralInfo pipline = new GeneralInfo();
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            double eop = pipline.EOP;

            int storeId = (cboStores.SelectedValue != null)?Convert.ToInt32(cboStores.SelectedValue):1;

            int count = 1;
            Balance bal = new Balance();
            DataTable dtList = new DataTable();
               // string[] co = {"No","Item Name", "Ham","HamAmc","Neh","NehAmc","Mes","MesAmc","Tek","TekAmc","Hed","HedAmc","Tah","TahAmc","Tir","TirAmc","Yek","YekAmc","Meg","MegAmc","Miz","MizAmc","Gen","GenAmc","Sen","SenAmc","ItemID" };

            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            DateTime dtCurrent = ConvertDate.DateConverter(dtDate.Text);
            int year =Convert.ToInt32(cboYear.SelectedItem);
            int col = 0;
            progressBar1.Visible = true;
            progressBar1.Minimum = 1;
            progressBar1.Maximum = dtItem.Rows.Count;

            foreach (DataRow dr in dtItem.Rows)
            {
                int itemId = Convert.ToInt32(dr["ID"]);
                string itemName = dr["ItemName"].ToString() + " - " + dr["DosageForm"].ToString() + " - " + dr["Strength"].ToString();

                int[] mon = {11,12,1,2,3,4,5,6,7,8,9,10};
                long[] cons = new long[12];
                long[] amc = new long[12];
                DataTable dtBal = new DataTable();

                for (int i = 0; i < mon.Length;i++ )
                {
                   // if (!(year == dtCurrent.Year && mon[i] > dtCurrent.Month && mon[i] < 11))
                   if (((mon[i] == 11 || mon[i] == 12) && (mon[i] <= dtCurrent.Month || year == dtCurrent.Year)) || (mon[i] < 11 && mon[i] <= dtCurrent.Month && year == dtCurrent.Year))
                    {
                        int y = ((mon[i] < 11) ? year : year - 1);
                        cons[i] = bal.GetSOH(itemId, storeId, mon[i], y);
                       // amc[i] = bal.CalculateAMC(itemId, storeId, mon[i], year);
                    }

                }
                //string[] str = { count.ToString(), itemName, ((cons[0] != 0) ? cons[0].ToString("") : "0"), amc[0].ToString(), ((cons[1] != 0) ? cons[1].ToString() : "0"), amc[1].ToString(), ((cons[2] != 0) ? cons[2].ToString() : "0"), amc[2].ToString(), ((cons[3] != 0) ? cons[3].ToString() : "0"), amc[3].ToString(), ((cons[4] != 0) ? cons[4].ToString() : "0"), amc[4].ToString(), ((cons[5] != 0) ? cons[5].ToString() : "0"), amc[5].ToString(), ((cons[6] != 0) ? cons[6].ToString() : "0"), amc[6].ToString(), ((cons[7] != 0) ? cons[7].ToString() : "0"), amc[7].ToString(), ((cons[8] != 0) ? cons[8].ToString() : "0"), amc[8].ToString(), ((cons[9] != 0) ? cons[9].ToString() : "0"), amc[9].ToString(), ((cons[10] != 0) ? cons[10].ToString() : "0"), amc[10].ToString(), ((cons[11] != 0) ? cons[11].ToString() : "0"), amc[11].ToString(), dr["ID"].ToString() };
                string[] str = { count.ToString(), itemName, ((cons[0] != 0) ? cons[0].ToString("#,###") : "0"), ((cons[1] != 0) ? cons[1].ToString("#,###") : "0"), ((cons[2] != 0) ? cons[2].ToString("#,###") : "0"), ((cons[3] != 0) ? cons[3].ToString("#,###") : "0"), ((cons[4] != 0) ? cons[4].ToString("#,###") : "0"), ((cons[5] != 0) ? cons[5].ToString("#,###") : "0"), ((cons[6] != 0) ? cons[6].ToString("#,###") : "0"), ((cons[7] != 0) ? cons[7].ToString("#,###") : "0"), ((cons[8] != 0) ? cons[8].ToString("#,###") : "0"), ((cons[9] != 0) ? cons[9].ToString("#,###") : "0"), ((cons[10] != 0) ? cons[10].ToString("#,###") : "0"), ((cons[11] != 0) ? cons[11].ToString("#,###") : "0") };
              // dtList.Rows.Add(str);
                ListViewItem listItem = new ListViewItem(str);
                listItem.ToolTipText = itemName;
                listItem.Tag = dr["ID"];
                if (col != 0)
                {
                    listItem.BackColor = Color.FromArgb(233, 247, 248);
                    col = 0;
                }
                else
                {
                    col++;
                }

                lstItem.Items.Add(listItem);
                count++;
                progressBar1.PerformStep();
                //SOHGrid.Rows.Add(dRow);
            }

               progressBar1.Visible = false;
        }
        /// <summary>
        /// Populates the picklist based on the selected issue configuration
        /// </summary>
        private void PopulatePickList()
        {
            var valid = ValidateFields();

            if (valid == "true")
            {
                var iss = new IssueDoc();
                var rec = new ReceiveDoc();
                var bal = new Balance();
                var itmB = new Items();
                var DUs = new ReceivingUnits();

                var dtIssueConf = new DataTable();
                string[] strr = { "No", "Stock Code", "Item Name", "Quantity", "BatchNo", "Expiry Date", "Pack Price", "Total Price",
                                    "ItemId", "RecId", "Unit Price", "No of Pack", "Qty per pack",
                                    "DUSOH", "DUAMC", "Near Expiry", "DURecomended","SOH Left","UnitID" };
                foreach (string col in strr)
                {
                    dtIssueConf.Columns.Add(col);
                }

                DUs.LoadByPrimaryKey(Convert.ToInt32(cboReceivingUnits.EditValue));
                double duMax = 0.5;
                try
                {
                    duMax = DUs.Max;
                }
                catch { }
                double duMaxDays = duMax * 30;
                lblNearExpiryComment.Text = "*Near Expiry means items that has expiry in the next " + duMaxDays.ToString() + " Days.";

                DateTime xx = dtIssueDate.Value;
                dtIssueDate.CustomFormat = "MM/dd/yyyy";
                DateTime dtIss = ConvertDate.DateConverter(dtIssueDate.Text);
                dtIssueDate.Value = DateTime.Now;

                DateTime dtCurrent = new DateTime();// Convert.ToDateTime(dtIssueDate.Text);
                dtCurrent = ConvertDate.DateConverter(dtIssueDate.Text);
                dtIssueDate.Value = xx;
                dtIssueDate.CustomFormat = "MMM dd,yyyy";
                var dtIssueGrid = (DataTable)issueGrid.DataSource;
                for (int i = 0; i < dtIssueGrid.Rows.Count; i++)
                {
                    var unitid = Convert.ToInt32(dtIssueGrid.Rows[i]["UnitID"]);
                    Int64 expAmount = itmB.GetExpiredQtyItemsByID(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(cboStores.EditValue));
                    Int64 sohQty = 0;
                    try
                    {

                        switch (VisibilitySetting.HandleUnits)
                        {

                            case 1:
                                sohQty = bal.GetSOH(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(cboStores.EditValue), dtIss.Month, dtIss.Year) - expAmount;
                                break;
                            case 2:
                                sohQty = bal.GetSOHByUnit(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(cboStores.EditValue), dtIss.Month, dtIss.Year, unitid) - expAmount;
                                break;
                            case 3:
                                sohQty = bal.GetSOHByUnit(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(cboStores.EditValue), dtIss.Month, dtIss.Year, unitid) - expAmount;
                                break;
                        }
                    }
                    catch
                    {
                        XtraMessageBox.Show("Please check all the information you have input into the form including the issue date.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (sohQty >= Convert.ToInt64(dtIssueGrid.Rows[i]["Requested Qty"]))
                    {
                        var itm = new Items();
                        itm.LoadByPrimaryKey(Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]));
                        if (itm.IsColumnNull("NeedExpiryBatch"))
                        {
                            itm.NeedExpiryBatch = true;
                            itm.Save();
                        }
                        if (itm.NeedExpiryBatch && VisibilitySetting.HandleUnits == 1)
                        {
                            _dtRec = rec.GetBatchToIssue(Convert.ToInt32(cboStores.EditValue),
                                                         Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), dtIss);
                        }
                        else if (itm.NeedExpiryBatch && VisibilitySetting.HandleUnits == 2)
                        {
                            _dtRec = rec.GetBatchToIssueByUnit(Convert.ToInt32(cboStores.EditValue),
                                                        Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), dtIss ,unitid);
                        }
                        else if (itm.NeedExpiryBatch && VisibilitySetting.HandleUnits == 3)
                        {
                            _dtRec = rec.GetBatchToIssueByUnit(Convert.ToInt32(cboStores.EditValue),
                                                        Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), dtIss, unitid);
                        }
                        else
                            _dtRec = rec.GetSupplyToIssueWithOutBatch(Convert.ToInt32(cboStores.EditValue),
                                                                      Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]),
                                                                      dtIssueDate.Value);

                        // Extream measures:
                        // This has tobe properly mitigated
                        // if there is the balance an there is no batch to be issued, just select the last batch and add the balance to it.

                        if (rec.RowCount > 0)
                        {
                            int j = 0;
                            Int64 quantity = 0;
                            double sohbalance = 0;
                            switch (VisibilitySetting.HandleUnits)
                            {
                                case 1:
                                    quantity = Convert.ToInt64(dtIssueGrid.Rows[i]["Requested Qty"]);
                                    sohbalance = sohQty - quantity;
                                    break;
                                case 2:
                                    quantity = Convert.ToInt64(dtIssueGrid.Rows[i]["Pack Qty"]);
                                    sohbalance = sohQty - quantity;
                                    break;
                                default:
                                    quantity = Convert.ToInt64(dtIssueGrid.Rows[i]["Pack Qty"]);
                                    sohbalance = sohQty - quantity;
                                    break;
                            }

                            while (quantity >=0 && rec.RowCount > j)
                            {
                                var batch = itm.NeedExpiryBatch ? _dtRec.Rows[j]["BatchNo"].ToString() : "";
                                Int64 qu = ((quantity > Convert.ToInt32(_dtRec.Rows[j]["QuantityLeft"])) ? Convert.ToInt64(_dtRec.Rows[j]["QuantityLeft"]) : quantity);
                                double qtyPerPack = Convert.ToDouble(_dtRec.Rows[j]["QtyPerPack"]);
                                double unitPrice = Convert.ToDouble(_dtRec.Rows[j]["Cost"]);
                                double packPrice = unitPrice * qtyPerPack; //Convert.ToDouble(dtIssueGrid.Rows[i]["Qty Per Pack"]);
                                double reqPackQty = Convert.ToDouble(dtIssueGrid.Rows[i]["Pack Qty"]);
                                double totPrice = unitPrice * qu;
                                bool nearExp = false;
                                DateTime? dtx = new DateTime();

                                switch (VisibilitySetting.HandleUnits)
                                {
                                    case 1:
                                        rec.UnitID = 0;
                                        rec.QtyPerPack = Convert.ToInt32(dtIssueGrid.Rows[i]["Qty Per Pack"]);
                                        break;
                                    case 2:
                                        rec.UnitID = Convert.ToInt32(dtIssueGrid.Rows[i]["UnitID"]);
                                        rec.QtyPerPack = 1;
                                        break;
                                    case 3:
                                        rec.UnitID = Convert.ToInt32(dtIssueGrid.Rows[i]["UnitID"]);
                                        rec.QtyPerPack = 1;
                                        break;
                                }

                                if (itm.NeedExpiryBatch)
                                {
                                    dtx = Convert.ToDateTime(_dtRec.Rows[j]["ExpDate"]);
                                    if (dtx <= DateTime.Now.AddDays(duMaxDays))
                                        nearExp = true;
                                }
                                else if (!itm.NeedExpiryBatch)
                                {
                                    dtx = null;
                                    // nearExp = false;
                                }
                                int rowNo = j + 1;

                                object[] obj = { rowNo, dtIssueGrid.Rows[i]["Stock Code"],
                                                     dtIssueGrid.Rows[i]["Item Name"], qu, batch,dtx,
                                                     packPrice.ToString("#,##0.#0"), ((totPrice != double.NaN) ? totPrice.ToString("#,##0.#0") : "0"),
                                                     Convert.ToInt32(dtIssueGrid.Rows[i]["ID"]), Convert.ToInt32(_dtRec.Rows[j]["ID"]), unitPrice.ToString("#,##0.00"),
                                                     dtIssueGrid.Rows[i]["Pack Qty"], dtIssueGrid.Rows[i]["Qty Per Pack"], dtIssueGrid.Rows[i]["DU Remaining SOH"],
                                                     dtIssueGrid.Rows[i]["DU AMC"], ((nearExp) ? "Yes" : "No"), dtIssueGrid.Rows[i]["Recommended Qty"],
                                                     sohbalance,dtIssueGrid.Rows[i]["UnitID"]};
                                dtIssueConf.Rows.Add(obj);

                                quantity = quantity - Convert.ToInt64(_dtRec.Rows[j]["QuantityLeft"]);
                                j++;
                            }
                        }
                        else
                        {
                            XtraMessageBox.Show("There is no enough Quantity in the store OR It has expired. Please check the issue date, quantity and try again!");
                        }
                    }
                    else
                    {
                        XtraMessageBox.Show("There is not enough Quantity in the store OR It has expired. Please check the issue date, quantity and try again!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                if (dtIssueConf.Rows.Count > 0)
                {
                    _tabPage = 2;

                    tabControl1.SelectedTabPageIndex = 2;
                    txtConfRef.Text = txtRefNo.Text;
                    txtIssuedDate.Value = dtIssueDate.Value;
                    txtIssuedTo.Text = cboReceivingUnits.Text;

                    txtStore.Text = cboStores.Text;
                    txtConIssuedBy.Text = txtIssuedBy.Text;
                    txtConRemark.Text = txtRemark.Text;
                    txtConRecipientName.Text = txtRecipientName.Text;
                    gridConfirmation.DataSource = dtIssueConf;
                }
            }
            else
            {
                tabControl1.SelectedTabPageIndex = 1;
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }
        public DataTable GetVitalItemsStockOut(int storeId, int month, int year)
        {
            Items itm = new Items();
            DataTable dtItem = itm.GetVitalItems();
            GeneralInfo pipline = new GeneralInfo();
            pipline.LoadAll();

            DataTable dt = new DataTable();
            string[] cols = { "ID", "ItemName", "DosageForm", "Strength", "Unit", "StockCode" };
            foreach (string st in cols)
            {
                dt.Columns.Add(st);
            }

            int min = pipline.Min;
            int max = pipline.Max;
            double eop = pipline.EOP;

            Balance bal = new Balance();
            foreach (DataRow dr in dtItem.Rows)
            {
                Int64 AMC = bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, month, year);
                Int64 MinCon = AMC * min;
                Int64 maxCon = AMC * max;
                double eopCon = AMC * (eop + 0.25);
                Int64 SOH = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, month, year);
                decimal MOS = (AMC != 0) ? (SOH / AMC) : 0;
                Int64 reorder = (maxCon > SOH) ? maxCon - SOH : 0;
                if (SOH == 0)
                {
                    object[] obb = { dr["ID"], dr["ItemName"], dr["DosageForm"], dr["Strength"], dr["Unit"], dr["StockCode"] };
                    dt.Rows.Add(obb);
                }
            }
            return dt;
        }
        private void repositoryItemButtonEdit1_Click(object sender, EventArgs e)
        {
            DataRow dr = grdViewYearEnd.GetDataRow(grdViewYearEnd.GetSelectedRows()[0]);
            if (dr != null)
            {
                string batchNo = dr["Batch No."].ToString();
                int recID = int.Parse(dr["RecID"].ToString());
                BLL.ReceiveDoc rec = new ReceiveDoc();

                if (recID == -1)
                {
                    XtraMessageBox.Show("Use this button only on invalid batches", "Nothing to Remove",
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                rec.LoadByPrimaryKey(recID);
                int itemID = rec.ItemID;

                //Do another validation here (Make sure that the items that they try to remove have issues like the Total SOH not being equal to the sum of the listed batches and so forth.
                int storeId = (cboStores.EditValue != null) ? Convert.ToInt32(cboStores.EditValue) : 1;
                int month = EthiopianDate.EthiopianDate.Now.Month;
                int year = EthiopianDate.EthiopianDate.Now.Year;

                BLL.Balance bal = new Balance();
                BLL.Items itm = new Items();
                itm.LoadByPrimaryKey(itemID);

                long currentBalance = bal.GetSOH(itemID, storeId, month, year);
                long totalQuantityLeftInBatches = itm.TotalQuantityLeftInAllBatches(storeId);

                if (currentBalance == totalQuantityLeftInBatches)
                {
                    XtraMessageBox.Show(
                        "You do not have to use this button to remove this batch.  Please set the physical inventory 0 instead.  Use this button only for items with discrepancies.",
                        "Unapplicable", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (XtraMessageBox.Show("This will make the quantity left for this received batch zero and remove it from this list.  Are you sure you want to continue?", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (BLL.ReceiveDoc.MarkReceivedBatchAsEmpty(recID))
                    {
                        dr.Delete();

                    }
                }
            }
        }
        //SupplyListToIssue
        public DataTable ItemListToIssue(int storeId, DateTime dtCurrent, string selectedType)
        {
            GeneralInfo pipline = new GeneralInfo();
            DataTable dtList = new DataTable();
            string[] str = { "No", "Stock Code", "FullItemName", "Unit", "SOH", "AMC", "Expired", "CategoryId", "SubCategoryID", "ID", "Status", "IsSelected" };
            foreach (string s in str)
            {
                dtList.Columns.Add(s);
            }
            dtList.Columns[11].DataType = typeof(bool);
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            double eop = pipline.EOP;
            // int storeId = (cboStores.SelectedValue != null) ? Convert.ToInt32(cboStores.SelectedValue) : 1;

            int count = 1;
            Balance bal = new Balance();
            Items itmB = new Items();
            DataTable dtItem = ((selectedType == "Drug") ? itmB.GetAllItems(1) : itmB.GetAllSupply());
            int curYear = dtCurrent.Year;
            int curMonth = dtCurrent.Month;
            foreach (DataRow dr in dtItem.Rows)
            {
                int yer = (curMonth < 11) ? curYear : curYear - 1;
                Int64 AMC = bal.CalculateAMC(Convert.ToInt32(dr["ID"]), storeId, curMonth, curYear);
                Int64 MinCon = AMC * min;
                Int64 maxCon = AMC * max;
                double eopCon = AMC * (eop + 0.25);
                double beloweopCon = AMC * (eop - 0.25);
                Int64 soh = bal.GetSOH(Convert.ToInt32(dr["ID"]), storeId, curMonth, curYear);
                string status = (soh <= eopCon && soh > beloweopCon) ? "Near EOP" : ((soh > 0 && soh <= beloweopCon) ? "Below EOP" : ((soh > maxCon && maxCon != 0) ? "Excess Stock" : ((soh <= 0) ? "Stock Out" : "Normal")));//((SOH > beloweopCon && SOH <= MinCon) ? "Below Min" : ((SOH > maxCon && maxCon != 0) ? "Excess Stock" : ((SOH <= 0) ? "Stock Out" : "Normal"));
                string itemName = dr["FullItemName"].ToString();
                Int64 expAmount = itmB.GetExpiredQtyItemsByID(Convert.ToInt32(dr["ID"]), storeId);
                object[] obj = { count.ToString(), dr["StockCode"].ToString(), itemName, dr["Unit"].ToString(), soh, AMC, expAmount, Convert.ToInt32(dr["CategoryId"]), Convert.ToInt32(dr["SubCategoryID"]), Convert.ToInt32(dr["ID"]), status, DBNull.Value };
                dtList.Rows.Add(obj);
                count++;
            }
            return dtList;
        }
        public decimal GetMOS(int itemId, int storeId, DateTime dtCurrent)
        {
            GeneralInfo pipline = new GeneralInfo();
            pipline.LoadAll();
            int min = pipline.Min;
            int max = pipline.Max;
            double eop = pipline.EOP;
            Items itmB = new Items();
            Balance bal = new Balance();
               //Int64 AMC= bal.CalculateAMC(itemId, storeId, dtCurrent.Month, dtCurrent.Year);
            double AMC = Builder.CalculateAverageConsumption(itemId,storeId,DateTime.Today.Subtract(TimeSpan.FromDays(180)), dtCurrent, CalculationOptions.Monthly);
                //bal.CalculateAMC(itemId, storeId, dtCurrent.Month, dtCurrent.Year);//dtBal.Rows.Count <= 0) ? 0 : ((dtBal.Rows[0]["AMC"].ToString() != "") ? Convert.ToInt64(dtBal.Rows[0]["AMC"]) : 0);
            double MinCon = AMC * min;
            double maxCon = AMC * max;
            double eopCon = AMC * (eop + 0.25);

            Int64 SOH = bal.GetSOH(itemId, storeId, dtCurrent.Month, dtCurrent.Year);

            decimal MOS = (AMC != 0) ? (SOH / Convert.ToDecimal(AMC)) : 0;
            MOS = Decimal.Round(MOS, 1);
            return MOS;
        }
        private void PopulateStockStatusByYear()
        {
            // progressBar1.Visible = true;

            if (curMont != 0 && curYear != 0)
            {
                IssueDoc iss = new IssueDoc();
                ReceiveDoc rec = new ReceiveDoc();
                Balance blnc = new Balance();

                DataTable dtbl = blnc.GetSOH(storeId, curMont, curYear);

                DateTime lastRec = rec.GetLastReceivedDateByCategoryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue));
                DateTime lastIss = iss.GetLastIssuedDateByCategoryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue));
               //time here
                TimeSpan tt = new TimeSpan();
                string noDays = "";
                tt = new TimeSpan(dtCurrent.Ticks - lastRec.Ticks);
                noDays = (tt.TotalDays < 30000) ? tt.TotalDays.ToString() + " Days" : "Never";

                lblLastReceived.Text = (tt.TotalDays < 30000) ? lastRec.ToString("MM dd,yyyy") : "Never";
                lblRecDays.Text = noDays;
                //progressBar1.PerformStep();
                tt = new TimeSpan(dtCurrent.Ticks - lastIss.Ticks);
                noDays = (tt.TotalDays < 30000) ? tt.TotalDays.ToString() + " Days" : "Never";
                lblLastIssued.Text = (tt.TotalDays < 30000) ? lastIss.ToString("MM dd,yyyy") : "Never";
                lblIssuedDays.Text = noDays;

                DataTable dtAllItems;
                try
                {
                    dtAllItems = (from m in dtbl.AsEnumerable()
                                            where ((ckExclude.Checked == true) ? Convert.ToInt32(m["EverReceived"]) == 1 : true)
                                            select m).CopyToDataTable();
                }
                catch (InvalidOperationException)
                {
                    dtAllItems = null;
                }

                PopulateList(dtAllItems, listStatused);

                DataTable dtRec = rec.GetTopReceivedItemsByCategoryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue));
               // groupRecSummary.Text = "Top 10 Most Received Items";
                PopulateList(dtRec, listReceiveSum);
                lblNeverRecived.Text = rec.CountNeverReceivedItemsByCateogryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue)).ToString();
                if (rec.CountNeverReceivedItems(storeId) == 0)
                {
                    linkLabel10.Visible = false;
                }
                else
                {
                    linkLabel10.Visible = true;
                }
                lblNeverIssued.Text = rec.CountReceivedNotIssuedItemsByCategoryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue)).ToString();
                if (rec.CountReceivedNotIssuedItemsByCategoryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue)) == 0)
                {
                    linkLabel21.Visible = false;
                }
                else
                {
                    linkLabel21.Visible = true;
                }
               // progressBar1.PerformStep();
                DataTable dtIss = iss.GetTopIssuedItemsByCategoryAndYear(storeId, Convert.ToInt32(lkCategory.EditValue), Convert.ToInt32(cboYear.EditValue));
               // groupIssued.Text = "Top 10 Most Issued Items";
                PopulateList(dtIss, listIssued);

                //Balance bal = new Balance();
                GeneralInfo info = new GeneralInfo();
                info.LoadAll();
                DataTable dtList = new DataTable();
                DataTable dtCons = new DataTable();
                string[] co = { "Ham", "Neh", "Mes", "Tek", "Hed", "Tah", "Tir", "Yek", "Meg", "Miz", "Gen", "Sen" };

                //foreach(string s in co)
                //{
                dtList.Columns.Add("Month");
                dtList.Columns.Add("Value");
                dtList.Columns[1].DataType = typeof(Int64);

                dtCons.Columns.Add("Month");
                dtCons.Columns.Add("Value");
                dtCons.Columns[1].DataType = typeof(Int64);

                int[] mon = { 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
                double[] cos = new double[12];
                DataTable dtBal = new DataTable();
                Items recd = new Items();
               //time here
                int year = dtCurrent.Year;

                chartReceiveCost.Series.Clear();

                Series ser = new Series("Received Cost In Birr", ViewType.Line);
                ser.DataSource = dtList;
                ser.ArgumentScaleType = ScaleType.Qualitative;
                ser.ArgumentDataMember = "Month";
                ser.ValueScaleType = ScaleType.Numerical;

                ser.ValueDataMembers.AddRange(new string[] { "Value" });
                chartReceiveCost.Series.Add(ser);

                chartIssueCost.Series.Clear();

                Series serIss = new Series("Issued Cost In Birr", ViewType.Line);
                serIss.DataSource = dtCons;
                serIss.ArgumentScaleType = ScaleType.Qualitative;
                serIss.ArgumentDataMember = "Month";
                serIss.ValueScaleType = ScaleType.Numerical;

                serIss.ValueDataMembers.AddRange(new string[] { "Value" });
                chartIssueCost.Series.Add(serIss);

            }
        }