/// <summary>
        /// Saves the receiving unit related information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnIssueSave_Click(object sender, EventArgs e)
        {
            if(txtReceivingUnit.Text=="")
            {
                XtraMessageBox.Show("Please enter the name of the receiving unit", "Error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                return;
            }

            ReceivingUnits recUnit = new ReceivingUnits();
            if (_receivingUnitId != 0)
            {
                recUnit.LoadByPrimaryKey(_receivingUnitId);
                recUnit.Name = txtReceivingUnit.Text;
                recUnit.Phone = txtPhone.Text;
                recUnit.Description = memoEdit1.Text;
                recUnit.IsActive = chkIsDispensaryActive.Checked;
                recUnit.Min = Convert.ToDouble(cboDUMin.SelectedValue);
                recUnit.Max = Convert.ToDouble(cboDUMax.SelectedValue);
                recUnit.Woreda = txtWoreda.Text;
                recUnit.Region = txtRegion.Text;
                recUnit.Zone = txtZone.Text;
                recUnit.FacilityType = txtType.Text;
                recUnit.Save();

                //recUnit.Save();

                XtraMessageBox.Show("Issue Location Record Updated.", "Confirmation", MessageBoxButtons.OK,
                            MessageBoxIcon.Information);
            }
            else
            {
                recUnit.AddNew();
                recUnit.Name = txtReceivingUnit.Text;
                recUnit.Phone = txtPhone.Text;
                recUnit.Description = memoEdit1.Text;
                recUnit.IsActive = chkIsDispensaryActive.Checked;
                recUnit.Min = Convert.ToDouble(cboDUMin.SelectedValue);
                recUnit.Max = Convert.ToDouble(cboDUMax.SelectedValue);
                recUnit.Woreda = txtWoreda.Text;
                recUnit.Region = txtRegion.Text;
                recUnit.Zone = txtZone.Text;
                recUnit.FacilityType = txtType.Text;
                recUnit.Save();
                recUnit.LoadAll();
                PopulateReceivingUnit(recUnit);
                ResetIssuesLocation();
                XtraMessageBox.Show("Issue Location Record Saved.", "Confirmation", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
            }
        }
        /// <summary>
        /// Loads the form and loads the lookups and the grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManageItems_Load(object sender, EventArgs e)
        {
            //CALENDAR:
            PopulateCatTree(_selectedType);

            lkCommodityTypes.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCommodityTypes.ItemIndex = 0;

            Stores stor = new Stores();
            stor.GetActiveStores();
            cboStores.Properties.DataSource = stor.DefaultView;
            cboStores.EditValue = 0;

            string[] arr = new string[] {"All", "Stock Out", "Below EOP", "Near EOP", "Normal", "Over Stocked"};
            cboIssuedTo.Properties.DataSource = arr;

            DataTable dtMonths = new DataTable();
            dtMonths.Columns.Add("Value");
            dtMonths.Columns.Add("Month");
            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            _dtCur = ConvertDate.DateConverter(dtDate.Text);
            int currentMont = _dtCur.Month;
            //int year = ((currentMont < 11) ? _dtCur.Year : _dtCur.Year + 1);
            int year = _dtCur.Year;
            // this is just a try
            //if (currentMont >= 11)
            //{
            //    currentMont -= 11;
            //}

            DataTable dtyears = Items.AllYears();
            //if (year == _dtCur.Year + 1)
            //{
            //    object[] objYear = { year };
            //    dtyears.Rows.Add(objYear);
            //}
            cboYear.Properties.DataSource = dtyears;
            cboYear.EditValue = year;
            if(cboYear.Properties.Columns.Count > 0)
                cboYear.Properties.Columns[0].Alignment = DevExpress.Utils.HorzAlignment.Near;

            //Programs prog = new Programs();
            //DataTable dtProg = prog.GetSubPrograms();
            //object[] objProg = { 0, "All Programs", "", 0, "" };
            //dtProg.Rows.Add(objProg);
            //cboSubProgram.Properties.DataSource = dtProg;
            //cboSubProgram.ItemIndex = -1;
            //cboSubProgram.Text = "Select Program";

            ReceivingUnits rec = new ReceivingUnits();
            DataTable drRec = rec.GetAllApplicableDU();
            cboDUnits.Properties.DataSource = drRec;
            cboDUnits.Properties.DisplayMember = "Name";
            cboDUnits.Properties.ValueMember = "ID";
            cboDUnits.EditValue = 1;

            this._isReady = true;
            PopulateGrid();
        }
        /// <summary>
        /// Saves the item policy
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            var itm = new Items();
            var itmSup = new ItemSupplier();
            if (_itemId != 0)
                itm.LoadByPrimaryKey(_itemId);
            else
            {
                itm.AddNew();
                var prodCate = new ProductsCategory();
                prodCate.AddNew();
                prodCate.ItemId = itm.ID;
                prodCate.SubCategoryID = Convert.ToInt32(_categoryId);
                prodCate.Save();
            }
            //if (rdA.Checked || rdB.Checked || rdC.Checked)
            //    itm.ABC = ((rdA.Checked) ? 1 : (rdB.Checked) ? 2 : 3);

            //if (rdV.Checked || rdE.Checked || rdN.Checked)
            //    itm.VEN = ((rdV.Checked) ? 1 : (rdE.Checked) ? 2 : 3);

                itm.IsInHospitalList = ckExculed.Checked;
                //itm.NeedExpiryBatch = chkNeedExpiryBatch.Checked;

            string valid = ValidateFields();
            if (valid == "true")
            {
                itm.NeedExpiryBatch = chkNeedExpiryBatch.Checked;
                itm.StockCodeDACA = txtText.Text;
                itm.Cost = txtQuantityPerPack.Text;
                itm.Save();
            }

            else
            {
                XtraMessageBox.Show(valid, "Validation", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }

            //TODO: To add categories
            //Needs some modification on edit

            // this will only add the suppliers
            //do some thing on edit

            itmSup.DeleteAllSupForItem(itm.ID);
            Supplier sup = new Supplier();
            foreach (object t in lstSuppliers.CheckedItems)
            {
                sup.GetSupplierByName(t.ToString());
                itmSup.AddNew();
                itmSup.ItemID = itm.ID;
                itmSup.SupplierID = sup.ID;
                itmSup.Save();
            }

            var progItm = new ProgramProduct();
            progItm.DeleteAllProgramsForItem(_itemId);

            var prog = new Programs();
            //prog.AddNew();
            //prog.Name = cboPrograms.Text;
            //prog.Save();

            foreach (object t in lstPrograms.CheckedItems)
            {
                prog.GetProgramByName(t.ToString());
                progItm.AddNew();
                progItm.ItemID = itm.ID;
                progItm.ProgramID = prog.ID;
                progItm.Save();
            }

            var duItem = new DUsItemList();
            var dus = new ReceivingUnits();

            foreach (object t in lstDUs.CheckedItems)
            {
                dus.GetDUByName(t.ToString());
                duItem.AddNew();
                duItem.DUID = dus.ID;
                duItem.ItemID = _itemId;
                try
                {
                    duItem.Save();
                }
                catch
                {

                }
            }

            XtraMessageBox.Show("Item Detail is Saved Successfully!", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            this.Close();
        }
        /// <summary>
        /// Populates the fields based on the supplied itemID or categoryID
        /// </summary>
        private void PopulateFields()
        {
            if (_itemId == 0)
                return;

            Items itm = new Items();

            DataTable dtItem = itm.GetItemById(_itemId);
            txtItemName.Text = dtItem.Rows[0]["ItemName"].ToString() + " - " + dtItem.Rows[0]["DosageForm"].ToString() + " - " + dtItem.Rows[0]["Strength"].ToString();
            ckExculed.Checked =itm.IsInHospitalList;
            chkNeedExpiryBatch.Checked = itm.NeedExpiryBatch;
            txtText.Text = itm.StockCodeDACA ?? string.Empty;
            txtQuantityPerPack.Text = itm.Cost ?? string.Empty;

            try
            {
                if (dtItem.Rows[0]["ABC"].ToString() == "A")
                    rdA.Checked = true;
                else if (dtItem.Rows[0]["ABC"].ToString() == "B")
                    rdB.Checked = true;
                else if (dtItem.Rows[0]["ABC"].ToString() == "C")
                    rdC.Checked = true;
            }
            catch { }

            try
            {
                if (dtItem.Rows[0]["VEN"].ToString() == "V")
                    rdV.Checked = true;
                else if (dtItem.Rows[0]["VEN"].ToString() == "E")
                    rdE.Checked = true;
                else if (dtItem.Rows[0]["VEN"].ToString() == "N")
                    rdN.Checked = true;
            }
            catch { }

            //ItemShelf itmShelf = new ItemShelf();
            //DataTable dtSlf = itmShelf.GetLocationByItem(itm.ID);
            //lstBinLocation.DataSource = dtSlf;

            var unit = new ItemUnit();
            var itemunits= unit.LoadFromSQl(_itemId);
            itemunitbindingSource.DataSource = itemunits;

            if (VisibilitySetting.HandleUnits == 2)
            {
                listBox1.Visible = true;
            }
            else if(VisibilitySetting.HandleUnits == 3)
            {
                 listBox1.Visible = true;
            }
            else if(VisibilitySetting.HandleUnits == 1)
            {
                listBox1.Hide();
            }
            Supplier sup = new Supplier();
            sup.GetActiveSuppliers();

            ItemSupplier itmSup = new ItemSupplier();
            itm.GetItemsBySupplier(_itemId);
            foreach (DataRowView dv in sup.DefaultView)
            {
                bool check = false;
                check = itmSup.CheckIfExist(_itemId, Convert.ToInt32(dv["ID"]));
                object obj = dv["CompanyName"];
                lstSuppliers.Items.Add(obj, check);
            }

            Programs prog = new Programs();
            prog.GetSubPrograms();
            ProgramProduct progItem = new ProgramProduct();
            lstPrograms.Items.Clear();
            foreach (DataRowView dv in prog.DefaultView)
            {
                bool check = false;
                check = progItem.CheckIfExists(_itemId, Convert.ToInt32(dv["ID"]));
                lstPrograms.Items.Add(dv["Name"], check);
            }

            ReceivingUnits dus = new ReceivingUnits();
            dus.GetActiveDispensaries();
            lstDUs.Items.Clear();

            DUsItemList duItem = new DUsItemList();

            foreach (DataRowView drDus in dus.DefaultView)
            {
                bool check = false;
                check = duItem.CheckIfExsits(_itemId, Convert.ToInt32(drDus["ID"]));
                lstDUs.Items.Add(drDus["Name"], check);
            }
        }
        private void ManageItems_Load(object sender, EventArgs e)
        {
            lkCommodityTypes.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCommodityTypes.ItemIndex = 0;

            PopulateCatTree();
            ReceivingUnits recUnits = new ReceivingUnits();
            recUnits.GetActiveDispensaries();
            recId = new int[recUnits.RowCount];
            int i = 0;
            if (lstItem.Columns.Count <= 2)
            {
                foreach (DataRowView dv in recUnits.DefaultView)
                {
                    lstItem.Columns.Add(dv["Name"].ToString());
                    recId[i] = Convert.ToInt32(dv["ID"]);
                    i++;
                }
            }

            Stores stor = new Stores();
            stor.GetActiveStores();
            cboStores.DataSource = stor.DefaultView;
        }
        private void ManageItems_Load(object sender, EventArgs e)
        {
            PopulateCatTree(SelectedType);

            lkCommodityTypes.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCommodityTypes.ItemIndex = 0;

            var itemunit = new ItemUnit();
            var allunits = itemunit.GetAllUnits();
            unitBindingSource.DataSource = allunits.DefaultView;

            var stor = new Stores();
            stor.GetActiveStores();
            cboStores.Properties.DataSource = stor.DefaultView;

            string[] arr = {"All",
            "Stock Out",
            "Below EOP",
            "Near EOP",
            "Normal",
            "Over Stocked"};

            cboStatus.Properties.DataSource = arr;

            DataTable dtMonths = new DataTable();
            dtMonths.Columns.Add("Value");
            dtMonths.Columns.Add("Month");
            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            dtCur = ConvertDate.DateConverter(dtDate.Text);
            int currentMont = dtCur.Month;
            int year = ((currentMont < 11) ? dtCur.Year : dtCur.Year + 1);
            // this is just a try
            if (currentMont >= 11)
            {
                currentMont -= 11;
            }

            var dtyears = Items.AllYears();

            cboYear.Properties.DataSource = dtyears;
            cboYear.EditValue = year;
            if (cboYear.Properties.Columns.Count > 0)
                cboYear.Properties.Columns[0].Alignment = DevExpress.Utils.HorzAlignment.Near;
            var prog = new Programs();
            var dtProg = new DataTable();
            dtProg = prog.GetSubPrograms();
            object[] objProg = { 0, "All Programs", "", 0, "" };
            dtProg.Rows.Add(objProg);
            cboSubProgram.Properties.DataSource = dtProg;
            cboSubProgram.ItemIndex = -1;
            cboSubProgram.Text = "Select Program";

            var rec = new ReceivingUnits();
            var drRec = rec.GetAllApplicableDU();
            cboIssuedTo.Properties.DataSource = drRec;
            cboIssuedTo.ItemIndex = -1;
            cboIssuedTo.Text = "Select Issue Location";
            IsReady = true;

            var unitcolumn = ((GridView)gridItemsChoice.MainView).Columns[15];
            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    unitcolumn.Visible = false;
                    break;
                case 2:
                    unitcolumn.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    break;
            }
            PopulateGrid();
        }
        /// <summary>
        /// Populates receiving units
        /// </summary>
        /// <param name="recUnit"></param>
        private void PopulateReceivingUnit(ReceivingUnits recUnit)
        {
            int count = 1;
            int col = 0;
            lstReceivingUnit.Items.Clear();

            foreach (DataRowView dv in recUnit.DefaultView)
            {
                string dumin = "";
                string dumax = "";
                if (dv["Min"] != DBNull.Value)
                {
                    double min = Convert.ToDouble(dv["Min"]);
                    if (min == 0.25)
                        dumin = "1 Weeks";
                    else if (min == 0.5)
                        dumin = "2 Weeks";
                    else if (min == 0.75)
                        dumin = "3 Weeks";
                    else if (min == 1)
                        dumin = "1 Month";
                    else if (min == 2)
                        dumin = "2 Month";
                    else
                        dumin = "";
                }

                if (dv["Max"] != DBNull.Value)
                {
                    double max = Convert.ToDouble(dv["Max"]);
                    if (max == 0.25)
                        dumax = "1 Weeks";
                    else if (max == 0.5)
                        dumax = "2 Weeks";
                    else if (max == 0.75)
                        dumax = "3 Weeks";
                    else if (max == 1)
                        dumax = "1 Month";
                    else if (max == 2)
                        dumax = "2 Month";
                    else
                        dumax = "";
                }

                string[] str = { count.ToString(), dv["Name"].ToString(), dv["Phone"].ToString(), dumin, dumax };
                ListViewItem lst = new ListViewItem(str) {Tag = dv["ID"]};
                if (col != 0)
                {
                    lst.BackColor = Color.FromArgb(233, 247, 248);
                    col = 0;
                }
                else
                    col++;
                lstReceivingUnit.Items.Add(lst);
                count++;

            }
        }
 /// <summary>
 /// Handles sorting for the list box
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void lstReceivingUnit_ColumnClick(object sender, ColumnClickEventArgs e)
 {
     ReceivingUnits recUnit = new ReceivingUnits();
     recUnit.LoadAll();
     if (_sortIssueLoca == "ASC")
     {
         recUnit.Sort = "Name ASC";
         _sortIssueLoca = "DESC";
     }
     else
     {
         recUnit.Sort = "Name DESC";
         _sortIssueLoca = "ASC";
     }
     PopulateReceivingUnit(recUnit);
 }
        private void ManageItems_Load(object sender, EventArgs e)
        {
            ReceivingUnits rec = new ReceivingUnits();
            DataTable drRec = rec.GetAllApplicableDU();
            cboIssuedTo.Properties.DataSource = drRec;
            cboIssuedTo.ItemIndex = -1;//.SelectedIndex = -1;
            cboIssuedTo.Text = @"Select Issue Location";

            Stores stor = new Stores();
            stor.GetActiveStores();
            cboStores.Properties.DataSource = stor.DefaultView;
            cboStores.ItemIndex = 0;
        }
        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 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 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;
        }
        private void BinCardTransaction_Load(object sender, EventArgs e)
        {
            DataTable dtyears = Items.AllYears();

            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            _dtCurrent = ConvertDate.DateConverter(dtDate.Text);
            //CALENDAR:
            foreach (DataRow drYears in dtyears.Rows)
            {
                if (drYears["year"] != DBNull.Value)
                {
                    int yr = Convert.ToInt32(drYears["year"]);
                    cboYear.Items.Add(yr);
                }
            }
            bool added = true;
            for (int x = 0; x < cboYear.Items.Count; x++)//to check if the current year is included or not
            {
                if (Convert.ToInt64(cboYear.Items[x]) == _year)
                {
                    added = false;
                    break;
                }
            }
            if (added)
            {
                cboYear.Items.Add(_year);
            }
            cboYear.SelectedItem = _year;

            var itemunit = new ItemUnit();
            var allunits = itemunit.GetAllUnits();
            unitBindingSource.DataSource = allunits.DefaultView;

            var unitcolumn = ((GridView)gridItemsList.MainView).Columns[11];
            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    unitcolumn.Visible = false;
                    break;
                case 2:
                    unitcolumn.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    break;
            }

            PopulateBinCardYearCombo();
            cboFiscalYear.SelectedItem = _year;
            BLL.Items itm = new Items();
            DataTable dtItm = itm.GetItemById(_itemId);
            string itemName = dtItm.Rows[0]["ItemName"].ToString() + " - " + dtItm.Rows[0]["DosageForm"].ToString() + " - " + dtItm.Rows[0]["Strength"].ToString();
            txtItemName.Text = itemName;
            txtitmName.Text = itemName;
            toolTip1.SetToolTip(txtitmName, itemName);
            lblBUnit.Text = dtItm.Rows[0]["Unit"].ToString();
            this.Text = itemName + " Detail Report";

            ReceivingUnits dus = new ReceivingUnits();
            DataTable dtDU = dus.GetApplicableDUs(_itemId, _storeId);
            Stores stor = new Stores();
            stor.LoadByPrimaryKey(_storeId);
            object[] objS = { 0, stor.StoreName, "", "" };
            dtDU.Rows.Add(objS);
            cboDU.DataSource = dtDU;
            cboDU.SelectedIndex = (cboDU.Items.Count - 1);
            cboDU.Text = "Select DU";

            try
            {
                txtFreeItem.Text = (itm.IsFree) ? "Yes" : "No";
                txtRefrigerated.Text = (itm.Refrigeratored) ? "Yes" : "No";
                txtPediatric.Text = (itm.Pediatric) ? "Yes" : "No";

            }
            catch
            {
            }

            int du = ((cboDU.SelectedValue != null) ? Convert.ToInt32(cboDU.SelectedValue) : 0);
            GenerateCharts(0);
            ItemStockStatus();

            //GenerateBinCard();
            GenerateBinCardNew();
            PopulateTransaction();

            tabControl1.SelectedTabPageIndex = _tabInd;
            _first = 1;
            lblItemID.Text = _itemId.ToString();

            PopulateLogisticSummary();
        }
        /* private void GenerateBinCard()
         {
             ReceiveDoc rec = new ReceiveDoc();
             IssueDoc iss = new IssueDoc();
             Disposal dis = new Disposal();
             DisposalReasons res = new DisposalReasons();
             Balance bal = new Balance();
             GeneralInfo info = new GeneralInfo();
             YearEnd yEnd = new YearEnd();
             Items itm = new Items();
             info.LoadAll();
             year = Convert.ToInt32(cboYear.SelectedItem);

             DataTable dtRec = rec.GetAllTransaction(itemId,storeId,dtCurrent.Month,year);
             DataTable dtIss = iss.GetTransactionByItemId(storeId, itemId, year);
             DataTable dtDis = dis.GetTransactionByItemId(storeId, itemId, year);

             Int64[] cStockout = { 0, 0, 0 };
             Int64[] cOverStock = { 0, 0, 0 };
             Int64[] cNearStockOut = { 0, 0, 0 };
             Int64[] cBelowMin = { 0, 0, 0 };

             //DateTime dtThree = dtCurrent.AddMonths(3);

             DataTable dtbin = new DataTable();
             string[] col = { "Date", "Ref. No", "Receive", "Issue", "Unit Price", "Balance", "Batch No", "Expiry Date","To / From"};
             foreach (string str in col)
             {
                 dtbin.Columns.Add(str);
             }
             int i = 0;
             Int64 bBalance = 0;
             dtDate.Value = DateTime.Now;
             dtDate.CustomFormat = "MM/dd/yyyy";
             dtCurrent = ConvertDate.DateConverter(dtDate.Text);
             bBalance = yEnd.GetBBalance(year, storeId, itemId,dtCurrent.Month);
             Int64 balanceAmount = bBalance;
             Int64 mincon = 0;
             Int64 maxcon = 0;
             double eopcon = 0;

             DateTime dtT = new DateTime();
             string balanceAm = "";

             txtBBalance.Text = bBalance.ToString();
             string ddDate = "";
             string batNo = "";
                 foreach (DataRow dvRec in dtRec.Rows)
                 {
                     i++;
                     if (Convert.ToInt32(dvRec["Transact"]) == 1)
                     {
                         rec.LoadByPrimaryKey(Convert.ToInt32(dvRec["ID"]));
                         balanceAmount = balanceAmount + Convert.ToInt64(dvRec["Quantity"]);
                         balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                         itm.LoadByPrimaryKey(rec.ItemID);
                         if (itm.NeedExpiryBatch)
                         {
                             ddDate = rec.ExpDate.ToString("MMM dd,yyyy");
                             batNo = rec.BatchNo;
                         }
                         Supplier sup = new Supplier();
                         sup.LoadByPrimaryKey(rec.SupplierID);
                         object[] obj = { Convert.ToDateTime(dvRec["Date"]).ToString("MM dd,yyyy"), dvRec["RefNo"], Convert.ToInt64(dvRec["Quantity"]).ToString("#,###"), "", Convert.ToDouble(dvRec["Cost"]).ToString("C"), balanceAm, batNo, ddDate, sup.CompanyName};
                         dtbin.Rows.Add(obj);
                         //For stock Out
                         dtT = Convert.ToDateTime(dvRec["Date"]);
                         //int monb = (dtT.Month < 11) ? dtT.Month + 2 : ((dtT.Month == 11) ? 1 : 2);
                         //int yer = (dtT.Month < 11) ? dtT.Year : dtT.Year - 1;
                         Int64 bBal = bal.GetSOH(itemId, storeId, dtT.Month, dtT.Year);
                         Int64 bAmc = bal.CalculateAMC(itemId, storeId, dtT.Month, dtT.Year);

                         mincon = bAmc * info.Min;
                         maxcon = bAmc * info.Max;
                         eopcon = bAmc * info.EOP;

                         if (balanceAmount == 0)
                         {
                             if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                             {
                                 cStockout[0]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                             {
                                 cStockout[1]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                             {
                                 cStockout[2]++;
                             }
                         }
                         else if (balanceAmount > maxcon)
                         {
                             //For Over stock
                             if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                             {
                                 cOverStock[0]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                             {
                                 cOverStock[1]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                             {
                                 cOverStock[2]++;
                             }
                         }//For Below min
                         else if (balanceAmount > eopcon && balanceAmount <= mincon)
                         {
                             if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                             {
                                 cBelowMin[0]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                             {
                                 cBelowMin[1]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                             {
                                 cBelowMin[2]++;
                             }
                         }
                         else if (balanceAmount > 0 && balanceAmount < eopcon)
                         {
                             if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                             {
                                 cNearStockOut[0]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                             {
                                 cNearStockOut[1]++;
                             }
                             else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                             {
                                 cNearStockOut[2]++;
                             }
                         }
                     }else if(Convert.ToInt32(dvRec["Transact"]) == 0)
                     {
                         //DateTime dteIss = Convert.ToDateTime(drIss["Date"]);
                         //DateTime dteRec = Convert.ToDateTime(dvRec["Date"]);
                         //DateTime dTomorow = new DateTime(dtCurrent.Year, dtCurrent.Month, dtCurrent.Day + 1);
                         //DateTime dteNextRec = (i <= dtRec.Rows.Count - 1) ? Convert.ToDateTime(dtRec.Rows[i]["Date"]) : dTomorow;
                         iss.LoadByPrimaryKey(Convert.ToInt32(dvRec["ID"]));
                         try
                         {
                             rec.LoadByPrimaryKey(iss.RecievDocID);
                         }
                         catch
                         {
                             rec.GetTransactionByBatch(itemId, dvRec["BatchNo"].ToString(), storeId);
                         }

                         ReceivingUnits recUnit = new ReceivingUnits();
                         recUnit.LoadByPrimaryKey(iss.ReceivingUnitID);
                         string issuedTo = recUnit.Name;
                             balanceAmount = balanceAmount - Convert.ToInt64(dvRec["Quantity"]);

                         balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                         itm.LoadByPrimaryKey(iss.ItemID);
                         if (itm.NeedExpiryBatch)
                         {
                             ddDate = ((rec.RowCount > 0) ? rec.ExpDate.ToString("MMM dd,yyyy") : ""); ;
                             batNo = dvRec["BatchNo"].ToString(); //rec.BatchNo;
                         }
                         else
                         {
                             ddDate = "";
                             batNo = "";
                         }
                         object[] obj = { Convert.ToDateTime(dvRec["Date"]).ToString("MM dd,yyyy"), dvRec["RefNo"], "", Convert.ToInt64(dvRec["Quantity"]).ToString("#,###"), Convert.ToDouble(dvRec["Cost"]).ToString("C"), balanceAm,batNo, ddDate,issuedTo};
                         dtbin.Rows.Add(obj);
                         //For stock Out
                         dtT = Convert.ToDateTime(dvRec["Date"]);
                             //int monb1 = (dtT.Month < 11) ? dtT.Month + 2 : ((dtT.Month == 11) ? 1 : 2);
                             //int yer1 = (dtT.Month < 11) ? dtT.Year : dtT.Year - 1;
                            Int64 bBal = bal.GetSOH(itemId, storeId, dtT.Month, dtT.Year);
                             Int64 bAmc = bal.CalculateAMC(itemId, storeId, dtT.Month, dtT.Year);

                             mincon = bAmc * info.Min;
                             maxcon = bAmc * info.Max;
                             eopcon = bAmc * info.EOP;

                             if (balanceAmount == 0)
                             {
                                 if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                 {
                                     cStockout[0]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                 {
                                     cStockout[1]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                 {
                                     cStockout[2]++;
                                 }
                             }
                             else if (balanceAmount > maxcon)
                             {
                                 //For Over stock
                                 if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                 {
                                     cOverStock[0]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                 {
                                     cOverStock[1]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                 {
                                     cOverStock[2]++;
                                 }
                             }//For Below min
                             else if (balanceAmount > eopcon && balanceAmount <= mincon)
                             {
                                 if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                 {
                                     cBelowMin[0]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                 {
                                     cBelowMin[1]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                 {
                                     cBelowMin[2]++;
                                 }
                             }
                             else if (balanceAmount > 0 && balanceAmount < eopcon)
                             {
                                 if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                 {
                                     cNearStockOut[0]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                 {
                                     cNearStockOut[1]++;
                                 }
                                 else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                 {
                                     cNearStockOut[2]++;
                                 }
                             }

                         }

                         foreach (DataRow drDis in dtDis.Rows)
                         {
                             DateTime dteDis = Convert.ToDateTime(drDis["Date"]);
                             DateTime dteRec = Convert.ToDateTime(dvRec["Date"]);

                             res.LoadByPrimaryKey(Convert.ToInt32(drDis["ReasonId"]));
                             rec.GetTransactionByBatch(itemId,drDis["BatchNo"].ToString(),storeId);
                             DateTime dteNextRec = (i <= dtRec.Rows.Count - 1) ? Convert.ToDateTime(dtRec.Rows[i]["Date"]) : dtCurrent;
                             if ((dteRec <= dteDis) && (dteDis < dteNextRec))
                             {
                                 if (Convert.ToBoolean(drDis["Losses"]))
                                 {
                                     balanceAmount = balanceAmount - Convert.ToInt64(drDis["Quantity"]);
                                     balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                                     object[] objIss = { Convert.ToDateTime(drDis["Date"]).ToString("MM dd,yyyy"), drDis["RefNo"], "", Convert.ToInt64(drDis["Quantity"]).ToString("#,###"), Convert.ToDouble(drDis["Cost"]).ToString("C"), balanceAm, drDis["BatchNo"], rec.ExpDate.ToString("MMM dd,yyyy"), res.Reason};
                                     dtbin.Rows.Add(objIss);

                                 }
                                 else
                                 {
                                     balanceAmount = balanceAmount + Convert.ToInt64(drDis["Quantity"]);
                                     balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                                     object[] objIss2 = { Convert.ToDateTime(drDis["Date"]).ToString("MM dd,yyyy"), drDis["RefNo"], Convert.ToInt64(drDis["Quantity"]).ToString("#,###"), "", Convert.ToDouble(drDis["Cost"]).ToString("C"), balanceAm, drDis["BatchNo"], rec.ExpDate.ToString("MMM dd,yyyy"), res.Reason};
                                     dtbin.Rows.Add(objIss2);

                                 }

                                 dtT = Convert.ToDateTime(dvRec["Date"]);
                                 Int64 bAmc = bal.CalculateAMC(itemId, storeId, dtT.Month, dtT.Year);

                                 mincon = bAmc * info.Min;
                                 maxcon = bAmc * info.Max;
                                 eopcon = bAmc * info.EOP;
                                 if (balanceAmount == 0)
                                 {
                                     if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                     {
                                         cStockout[0]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                     {
                                         cStockout[1]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                     {
                                         cStockout[2]++;
                                     }
                                 }
                                 else if (balanceAmount > maxcon)
                                 {
                                     //For Over stock
                                     if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                     {
                                         cOverStock[0]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                     {
                                         cOverStock[1]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                     {
                                         cOverStock[2]++;
                                     }
                                 }//For Below min
                                 else if (balanceAmount > eopcon && balanceAmount <= mincon)
                                 {
                                     if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                     {
                                         cBelowMin[0]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                     {
                                         cBelowMin[1]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                     {
                                         cBelowMin[2]++;
                                     }
                                 }
                                 else if (balanceAmount > 0 && balanceAmount < eopcon)
                                 {
                                     if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(90)))
                                     {
                                         cNearStockOut[0]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(180)))
                                     {
                                         cNearStockOut[1]++;
                                     }
                                     else if (Convert.ToDateTime(dvRec["Date"]) <= dtCurrent && Convert.ToDateTime(dvRec["Date"]) >= dtCurrent.Subtract(TimeSpan.FromDays(360)))
                                     {
                                         cNearStockOut[2]++;
                                     }
                                 }

                             }
                         }

                     }
             transactionGrid.DataSource = dtbin;
             //Stock Out
             lblThreeStockout.Text = cStockout[0].ToString();
             lblSixStockOut.Text = (cStockout[0] + cStockout[1]).ToString();
             lblTwelveStockOut.Text = (cStockout[0] + cStockout[1] + cStockout[2]).ToString();
             //Over Stock
             lblThreeOverStock.Text = cOverStock[0].ToString();
             lblSixOverStock.Text = (cOverStock[0] + cOverStock[1]).ToString();
             lblTwelveOverStock.Text = (cOverStock[0] + cOverStock[1] + cOverStock[2]).ToString();
             //Near eop
             lblThreeNearStock.Text = cNearStockOut[0].ToString();
             lblSixNearStock.Text = (cNearStockOut[0] + cNearStockOut[1]).ToString();
             lblTwelveNear.Text = (cNearStockOut[0] + cNearStockOut[1] + cNearStockOut[2]).ToString();
             //Below Min
             lblThreeBelowMin.Text = cBelowMin[0].ToString();
             lblSixBelowMin.Text = (cBelowMin[0] + cBelowMin[1]).ToString();
             lblTwelveBelowMin.Text = (cBelowMin[0] + cBelowMin[1] + cBelowMin[2]).ToString();
         }
          */
        /// <summary>
        /// Generates the bin card transaction
        /// </summary>
        private void GenerateBinCard()
        {
            #region NewCode
            ////Get the beginning balance.
            //Int64 begBalance = 0;
            //YearEnd yearEnd = new YearEnd();
            //begBalance = yearEnd.GetBeginningBalance(_storeId, _itemId);
            //txtBBalance.Text = begBalance.ToString();

            ////Get the bin card.
            //Balance balance = new Balance();
            //gridItemsList.DataSource = balance.GetBinCard(_storeId, _itemId);
            //return;
            #endregion
            #region Old Code
            ReceiveDoc rec = new ReceiveDoc();
            IssueDoc iss = new IssueDoc();
            Disposal dis = new Disposal();
            DisposalReasons res = new DisposalReasons();
            Balance bal = new Balance();
            GeneralInfo info = new GeneralInfo();
            YearEnd yEnd = new YearEnd();
            Items itm = new Items();
            info.LoadAll();
            if (cboFiscalYear.SelectedItem == null)
                PopulateBinCardYearCombo();
            //_year =  Convert.ToInt32(cboFiscalYear.SelectedItem);
            _year = Convert.ToInt32(cboYear.SelectedItem);
            int yer = _year;
            //int mth = (_year > _dtCurrent.Year) ? _dtCurrent.Month : 10;
            int mth = _dtCurrent.Month;
            EthiopianDate.EthiopianDate ethioDate = new EthiopianDate.EthiopianDate(_year, 1, 1);

            //if (_dtCurrent.Month < 11)
            //{
            //    yer = _year;
            //}
            //else
            //{
            //    yer = _year - 1;
            //}
            //DataTable dtRec = rec.GetAllTransaction(_itemId, _storeId, ethioDate.Month,ethioDate.Year);
            DataTable dtRec = rec.GetAllTransaction(_itemId, _storeId, ethioDate.FiscalYear);
            DataTable dtIss = iss.GetTransactionByItemId(_storeId, _itemId, ethioDate.FiscalYear);
            DataTable dtDis = dis.GetTransactionByItemId(_storeId, _itemId, ethioDate.FiscalYear);

            Int64[] cStockout = { 0, 0, 0 };
            Int64[] cOverStock = { 0, 0, 0 };
            Int64[] cNearStockOut = { 0, 0, 0 };
            Int64[] cBelowMin = { 0, 0, 0 };

            //DateTime dtThree = dtCurrent.AddMonths(3);

            DataTable dtbin = new DataTable();
            string[] col = { "Date", "RefNo", "Receive", "Issue", "Unit Price", "Balance", "Batch No", "Expiry Date", "ToFrom" };
            foreach (string str in col)
            {
                dtbin.Columns.Add(str);
            }
            int i = 0;
            Int64 bBalance = 0;
            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            _dtCurrent = ConvertDate.DateConverter(dtDate.Text);
            //bBalance = yEnd.GetBBalance(_year, _storeId, _itemId, _dtCurrent.Month);
            bBalance = yEnd.GetBBalance(_year, _storeId, _itemId);
            Int64 balanceAmount = bBalance;

            DateTime dtT = new DateTime();
            string balanceAm = "";

            string ddDate = "";
            string batNo = "";
            foreach (DataRow dvRec in dtRec.Rows)
            {
                i++;
                if (Convert.ToInt32(dvRec["Transact"]) == 1)
                {
                    rec.LoadByPrimaryKey(Convert.ToInt32(dvRec["ID"]));
                    if (dvRec["Quantity"] == DBNull.Value)
                    {
                        dvRec["Quantity"] = 0;
                    }
                    balanceAmount = balanceAmount + Convert.ToInt64(dvRec["Quantity"]);
                    balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                    itm.LoadByPrimaryKey(rec.ItemID);
                    if (itm.NeedExpiryBatch)
                    {
                        if (!rec.IsColumnNull("ExpDate"))
                        {
                            ddDate = rec.ExpDate.ToString("MMM dd,yyyy");
                            batNo = rec.BatchNo;
                        }
                    }
                    Supplier sup = new Supplier();
                    sup.LoadByPrimaryKey(rec.SupplierID);
                    object[] obj = { Convert.ToDateTime(dvRec["Date"]).ToString("MM dd,yyyy"), dvRec["RefNo"], Convert.ToInt64(dvRec["Quantity"]).ToString("#,###"), "", Convert.ToDouble(dvRec["Cost"]).ToString("C"), balanceAm, batNo, ddDate, sup.CompanyName };
                    dtbin.Rows.Add(obj);
                    //For stock Out
                    dtT = Convert.ToDateTime(dvRec["Date"]);

                }
                else if (Convert.ToInt32(dvRec["Transact"]) == 0)
                {
                    iss.LoadByPrimaryKey(Convert.ToInt32(dvRec["ID"]));
                    try
                    {
                        rec.LoadByPrimaryKey(iss.RecievDocID);
                    }
                    catch
                    {
                        rec.GetTransactionByBatch(_itemId, dvRec["BatchNo"].ToString(), _storeId);
                    }

                    ReceivingUnits recUnit = new ReceivingUnits();
                    recUnit.LoadByPrimaryKey(iss.ReceivingUnitID);
                    string issuedTo = recUnit.Name;
                    balanceAmount = balanceAmount - Convert.ToInt64(dvRec["Quantity"]);

                    balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                    itm.LoadByPrimaryKey(iss.ItemID);
                    if (itm.NeedExpiryBatch)
                    {
                        ddDate = ((rec.RowCount > 0) ? rec.ExpDate.ToString("MMM dd,yyyy") : ""); ;
                        batNo = dvRec["BatchNo"].ToString(); //rec.BatchNo;
                    }
                    else
                    {
                        ddDate = "";
                        batNo = "";
                    }
                    object[] obj = { Convert.ToDateTime(dvRec["Date"]).ToString("MM dd,yyyy"), dvRec["RefNo"], "", Convert.ToInt64(dvRec["Quantity"]).ToString("#,###"), Convert.ToDouble(dvRec["Cost"]).ToString("C"), balanceAm, batNo, ddDate, issuedTo };
                    dtbin.Rows.Add(obj);
                    //For stock Out
                    dtT = Convert.ToDateTime(dvRec["Date"]);

                }

                foreach (DataRow drDis in dtDis.Rows)
                {
                    DateTime dteDis = Convert.ToDateTime(drDis["Date"]);
                    DateTime dteRec = Convert.ToDateTime(dvRec["Date"]);

                    res.LoadByPrimaryKey(Convert.ToInt32(drDis["ReasonId"]));
                    rec.GetTransactionByBatch(_itemId, drDis["BatchNo"].ToString(), _storeId);
                    DateTime dteNextRec = (i <= dtRec.Rows.Count - 1) ? Convert.ToDateTime(dtRec.Rows[i]["Date"]) : _dtCurrent;
                    if ((dteRec <= dteDis) && (dteDis < dteNextRec))
                    {
                        if (Convert.ToBoolean(drDis["Losses"]))
                        {
                            balanceAmount = balanceAmount - Convert.ToInt64(drDis["Quantity"]);
                            balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                            if (rec.RowCount > 0)
                            {
                                object[] objIss = { Convert.ToDateTime(drDis["Date"]).ToString("MM dd,yyyy"), drDis["RefNo"], "", Convert.ToInt64(drDis["Quantity"]).ToString("#,###"), Convert.ToDouble(drDis["Cost"]).ToString("C"), balanceAm, drDis["BatchNo"], rec.ExpDate.ToString("MMM dd,yyyy"), res.Reason };
                                dtbin.Rows.Add(objIss);
                            }
                        }
                        else
                        {
                            balanceAmount = balanceAmount + Convert.ToInt64(drDis["Quantity"]);
                            balanceAm = (balanceAmount > 0) ? balanceAmount.ToString("#,###") : "0";
                            object[] objIss2 = { Convert.ToDateTime(drDis["Date"]).ToString("MM dd,yyyy"), drDis["RefNo"], Convert.ToInt64(drDis["Quantity"]).ToString("#,###"), "", Convert.ToDouble(drDis["Cost"]).ToString("C"), balanceAm, drDis["BatchNo"], rec.ExpDate.ToString("MMM dd,yyyy"), res.Reason };
                            dtbin.Rows.Add(objIss2);

                        }

                        dtT = Convert.ToDateTime(dvRec["Date"]);

                    }
                }

            }

            gridItemsList.DataSource = dtbin;
            #endregion
        }
        private void EditIssue_Load(object sender, EventArgs e)
        {
            Stores str = new Stores();
            str.LoadAll();
            cboStores.DataSource = str.DefaultView;

            ReceivingUnits rUnit = new ReceivingUnits();
            rUnit.GetActiveDispensaries();
            cboReceivingUnit.DataSource = rUnit.DefaultView;

            if (_tranId != 0)
            {
                IssueDoc iss = new IssueDoc();
                Items itm = new Items();

                iss.LoadByPrimaryKey(_tranId);

                DataTable dtItm = itm.GetItemById(iss.ItemID);
                string itemName = dtItm.Rows[0]["ItemName"].ToString() + " - " + dtItm.Rows[0]["DosageForm"].ToString() + " - " + dtItm.Rows[0]["Strength"].ToString();

                txtRefNo.Text = iss.RefNo;
                txtBatchNo.Text = iss.BatchNo;
                try
                {
                    txtPack.Text = iss.NoOfPack.ToString();
                    txtQtyPack.Text = iss.QtyPerPack.ToString();
                    txtPrice.Text = (iss.Cost * iss.QtyPerPack).ToString();
                }
                catch
                {
                    txtPack.Text = "0";
                    txtQtyPack.Text = "0";
                    txtPrice.Text = (iss.Cost * 1).ToString();
                }
                txtQuantity.Text = iss.Quantity.ToString();
                DateTime dtDate = Convert.ToDateTime(iss.Date.ToString("MM/dd/yyyy"));
                txtDate.Text = dtDate.ToShortDateString();
                //dtIssDate.Value = DateTime.Now;
                //dtIssDate.CustomFormat = "MM/dd/yyyy";
                //DateTime dtCurrent = Convert.ToDateTime(dtIssDate.Text);

                //long tic = (DateTime.Now.Ticks - dtCurrent.Ticks);
                //DateTime dtIssG = dtDate.AddTicks(tic);

                //dtIssDate.Value = dtIssG;
                cboStores.SelectedValue = iss.StoreId;
                cboReceivingUnit.SelectedValue = iss.ReceivingUnitID;
                txtItemName.Text = itemName;
                txtReceivedBy.Text = iss.IssuedBy;
                txtRemark.Text = iss.Remark;

            }
        }
        /// <summary>
        /// Load the drop downs and tables
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HospitalSettings_Load(object sender, EventArgs e)
        {
            Supplier sup = new Supplier();
            sup.LoadAll();
            PopulateSupplier(sup);

            Stores str = new Stores();
            str.LoadAll();
            PopulateStores(str);

            Shelf slf = new Shelf();
            DataTable dtSlf = slf.GetShelves();
            PopulateShelves(dtSlf.DefaultView);

            ReceivingUnits recUnit = new ReceivingUnits();
            recUnit.LoadAll();
            PopulateReceivingUnit(recUnit);

            DataTable dtdumin = new DataTable();
            dtdumin.Columns.Add("Value");
            dtdumin.Columns.Add("Month");
            object[] objdumin01 = { 0.25, "1 Weeks" };
            dtdumin.Rows.Add(objdumin01);
            object[] objdumin0 = { 0.5, "2 Weeks" };
            dtdumin.Rows.Add(objdumin0);
            object[] objdumin1 = { 0.75, ("3 Weeks") };
            dtdumin.Rows.Add(objdumin1);
            object[] objdumin2 = { 1, (1 + " Month") };
            dtdumin.Rows.Add(objdumin2);
            object[] objdumin3 = { 2, (2 + " Month") };
            dtdumin.Rows.Add(objdumin3);
            cboDUMin.DataSource = dtdumin;

            DataTable dtdumax = new DataTable();
            dtdumax.Columns.Add("Value");
            dtdumax.Columns.Add("Month");
            object[] objdumax01 = { 0.25, "1 Weeks" };
            dtdumax.Rows.Add(objdumax01);
            object[] objdumax010 = { 0.5, "2 Weeks" };
            dtdumax.Rows.Add(objdumax010);
            object[] objdumax011 = { 0.75, ("3 Weeks") };
            dtdumax.Rows.Add(objdumax011);
            object[] objdumax012 = { 1, (1 + " Month") };
            dtdumax.Rows.Add(objdumax012);
            object[] objdumax013 = { 2, (2 + " Month") };
            dtdumax.Rows.Add(objdumax013);
            cboDUMax.DataSource = dtdumax;
        }
        private void cboReceivingUnits_SelectedValueChanged(object sender, EventArgs e)
        {
            DataTable issGrid = (DataTable)issueGrid.DataSource;
            if (issGrid != null)
            {
                if (cboReceivingUnits.EditValue != null && issGrid.Rows.Count > 0)
                {
                    DateTime xx = dtIssueDate.Value;
                    dtIssueDate.Value = DateTime.Now;
                    dtIssueDate.CustomFormat = "MM/dd/yyyy";
                    DateTime dtCurrent = ConvertDate.DateConverter(dtIssueDate.Text);
                    dtIssueDate.Value = xx;

                    var iss = new IssueDoc();
                    var bal = new Balance();
                    int receivingUnit = Convert.ToInt32(cboReceivingUnits.EditValue);
                    var DUs = new ReceivingUnits();
                    DUs.LoadByPrimaryKey(receivingUnit);
                    double dumax = 0.5;
                    try
                    {
                        dumax = DUs.Max;
                    }
                    catch(Exception EX)
                    {

                    }

                    for (int i = 0; i < issGrid.Rows.Count; i++)
                    {
                        int itmId = Convert.ToInt32(issGrid.Rows[i]["ID"]);
                        int lastIssueQty = iss.GetDULastIssueQty(itmId, receivingUnit);
                        int lastDUSOH = iss.GetDULastSOH(itmId, receivingUnit);
                        issGrid.Rows[i]["MR Issue Qty"] = lastIssueQty;
                        issGrid.Rows[i]["MR DU SOH"] = lastDUSOH;
                        const int lstSOH = 0;
                        issGrid.Rows[i]["DU Remaining SOH"] = 0;
                        int yer = (dtCurrent.Month < 11) ? dtCurrent.Year : dtCurrent.Year - 1;
                        Int64 duAmc = bal.CalculateDUAMC(itmId, receivingUnit, dtCurrent.Month, dtCurrent.Year, lstSOH);
                        issGrid.Rows[i]["DU AMC"] = duAmc;
                        double recQty = (duAmc * dumax) - Convert.ToInt32(issGrid.Rows[i]["DU Remaining SOH"]);
                        issGrid.Rows[i]["Recommended Qty"] = ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
                    }
                }
            }
        }
 /// <summary>
 /// Handles the Index Changed event of the receiving unit list box
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void lstReceivingUnit_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (lstReceivingUnit.SelectedItems.Count > 0)
     {
         int selected = Convert.ToInt32(lstReceivingUnit.SelectedItems[0].Tag);
         ReceivingUnits recUnit = new ReceivingUnits();
         recUnit.LoadByPrimaryKey(selected);
         txtReceivingUnit.Text = recUnit.Name;
         memoEdit1.Text = recUnit.Description;
         txtPhone.Text = recUnit.Phone;
         txtWoreda.Text = recUnit.Woreda;
         txtRegion.Text = recUnit.Region;
         txtZone.Text = recUnit.Zone;
         txtType.Text = recUnit.FacilityType;
         chkIsDispensaryActive.Checked = recUnit.IsColumnNull("IsActive") ? true : recUnit.IsActive;
         _receivingUnitId = recUnit.ID;
         try
         {
             cboDUMax.SelectedValue = recUnit.Max.ToString();
             cboDUMin.SelectedValue = recUnit.Min.ToString();
         }
         catch { }
         btnIssueSave.Text = "Update";
     }
 }
        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var view = sender as GridView;
            if (view == null) return;
            var iu = new ItemUnit();

            if ((view.FocusedColumn.FieldName == "Pack Qty") || (view.FocusedColumn.FieldName == "Qty Per Pack") || (view.FocusedColumn.FieldName == "DU Remaining SOH"))
            {
                DataRow dr = issueGridView.GetDataRow(issueGridView.GetSelectedRows()[0]);

                int qty = Convert.ToInt32(dr["Pack Qty"]);
                int qtyPerpack = Convert.ToInt32(dr["Qty Per Pack"]);
                switch (VisibilitySetting.HandleUnits)
                {
                    case 2:
                        {
                            iu.LoadByPrimaryKey(Convert.ToInt32(dr["UnitID"]));
                            var qtyperunit = iu.QtyPerUnit;
                            dr["Qty Per Pack"] = qtyperunit;
                            dr["Requested Qty"] = qty;
                        }
                        break;
                    case 3:
                        {
                            iu.LoadByPrimaryKey(Convert.ToInt32(dr["UnitID"]));
                            var qtyperunit = iu.QtyPerUnit;
                            dr["Qty Per Pack"] = qtyperunit;
                            dr["Requested Qty"] = qty;
                        }
                        break;
                    case 1:
                        dr["Qty Per Pack"] = qtyPerpack;
                        dr["Requested Qty"] = (qtyPerpack * qty);
                        break;
                }

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

                var bal = new Balance();
                var receivingUnit = Convert.ToInt32(cboReceivingUnits.EditValue);

                Int64 duAmc = 0;
                int itmId = Convert.ToInt32(dr["ID"]);
                int lstSOH = ((dr["DU Remaining SOH"] != null && dr["DU Remaining SOH"] != DBNull.Value) ? Convert.ToInt32(dr["DU Remaining SOH"]) : 0);
                duAmc = bal.CalculateDUAMC(itmId, receivingUnit, dtCurrent.Month, dtCurrent.Year, lstSOH);
                dr["DU AMC"] = duAmc;

                //recommend qty to du
                var DUs = new ReceivingUnits();
                DUs.LoadByPrimaryKey(receivingUnit);
                double dumax = 0.5;
                try
                {
                    dumax = DUs.Max;
                }
                catch
                { }
                double recQty = (Convert.ToInt32(dr["DU AMC"]) * dumax) - lstSOH;
                dr["Recommended Qty"] = ((recQty > 0) ? Convert.ToInt64(recQty) : 0);
            }
        }
        /// <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);
            }
        }
        private void ManageItems_Load(object sender, EventArgs e)
        {
            lkCommodityTypes.Properties.DataSource = BLL.Type.GetAllTypes();
            lkCommodityTypes.ItemIndex = 0;

            PopulateCatTree();

            Stores stor = new Stores();
            stor.GetActiveStores();
            cboStores.DataSource = stor.DefaultView;

            dtDate.Value = DateTime.Now;
            dtDate.CustomFormat = "MM/dd/yyyy";
            dtCurrent = ConvertDate.DateConverter(dtDate.Text);

            Programs prog = new Programs();
            DataTable dtProg = new DataTable();
            dtProg = prog.GetSubPrograms();
            object[] objProg = { 0, "All Programs", "", 0, "" };
            dtProg.Rows.Add(objProg);
            cboSubProgram.DataSource = dtProg;
            cboSubProgram.SelectedIndex = -1;
            cboSubProgram.Text = "Select Program";

            ReceivingUnits rec = new ReceivingUnits();
            DataTable drRec = rec.GetAllApplicableDU();
            cboIssuedTo.DataSource = drRec;
            cboIssuedTo.SelectedIndex = -1;
            cboIssuedTo.Text = "Select Issue Location";

            int month = dtCurrent.Month;
            int year = ((dtCurrent.Month < 11) ? dtCurrent.Year : dtCurrent.Year + 1);

            DataTable dtyears = Items.AllYears();

            foreach (DataRow drYears in dtyears.Rows)
            {
                int yr = Convert.ToInt32(drYears["year"]);
                cboYear.Items.Add(yr);
            }
            bool added = true;
            for (int x = 0; x < cboYear.Items.Count; x++)//to check if the current year is included or not
            {
                if (Convert.ToInt64(cboYear.Items[x]) == year)
                {
                    added = false;
                    break;
                }
            }
            if (added)
            {
                cboYear.Items.Add(year);
            }
            cboYear.SelectedItem = year;
        }
        /// <summary>
        /// Populate the lookups
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ManageItems_Load(object sender, EventArgs e)
        {
            var rec = new ReceivingUnits();
            DataTable drRec = rec.GetAllApplicableDU();
            cboIssuedTo.Properties.DataSource = drRec;
            cboIssuedTo.ItemIndex = -1;//.SelectedIndex = -1;
            cboIssuedTo.Text = @"Select Issue Location";

            var itemunit = new ItemUnit();
            var units = itemunit.GetAllUnits();
            unitbindingSource.DataSource = units.DefaultView;

            // populate the receiving unit's lookup edit
            var rus = new ReceivingUnits();
            rus.GetActiveDispensaries();
            lkEditReceivingUnis.DataSource = rus.DefaultView;

            var stor = new Stores();
            stor.GetActiveStores();
            cboStores.Properties.DataSource = stor.DefaultView;
            cboStores.ItemIndex = 0;
            var unitcolumn = ((GridView)gridIssues.MainView).Columns[12];
            switch (VisibilitySetting.HandleUnits)
            {
                case 1:
                    unitcolumn.Visible = false;
                   break;
                case 2:
                    unitcolumn.Visible = true;
                    break;
                default:
                    unitcolumn.Visible = true;
                    break;
            }

            try
            {
                DataRowView dr = (DataRowView)lstTree.GetDataRecordByNode(lstTree.Nodes[0].FirstNode);

                if (dr == null) return;

                //lstTransactions.Items.Clear();
                IssueDoc iss = new IssueDoc();
                DataTable dtRec;
                if (dr["ParentID"] == DBNull.Value)
                {
                    EthiopianDate.EthiopianDate ethiopianDate = new EthiopianDate.EthiopianDate(Convert.ToInt32(dr["ID"]), 1, 1);
                    dtRec = iss.GetTransactionByDateRange(Convert.ToInt32(cboStores.EditValue), ethiopianDate.StartOfFiscalYear.ToGregorianDate(), ethiopianDate.EndOfFiscalYear.ToGregorianDate());
                    string dateString = dr["RefNo"].ToString();
                    lblIssDate.Text = dateString;
                }
                else
                {
                    //dtRec = iss.GetTransactionByRefNo(dr["RefNo"].ToString(), Convert.ToInt32(cboStores.EditValue), dr["Date"].ToString());
                    dtRec = iss.GetTransactionByRefNo(dr["RefNo"].ToString(), Convert.ToDateTime(dr["Date"]));
                    lblIssDate.Text = Convert.ToDateTime(dr["Date"]).ToString("MM dd,yyyy");
                }
                gridIssues.DataSource = dtRec;
            }

            catch (Exception ex)
            {
                // do nothing
            }
        }