/// <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";
        }
        /// <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);
            }
        }
        //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;
        }