/// <summary>
 /// Handles Delete of an item
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void toolBtnDelete_Click(object sender, EventArgs e)
 {
     DataRow drv = gridView1.GetFocusedDataRow();
     if (drv != null)
     {
         Items itm = new Items();
         ProductsCategory proCat = new ProductsCategory();
         int itemId = Convert.ToInt32(drv["ID"]);
         if (!itm.HasTransactions(itemId))
         {
             if (XtraMessageBox.Show("Are You Sure, You want to delete this Transaction? You will not be able to restore this data.", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
             {
                 proCat.GetCategoryByItem(itemId);
                 foreach (DataRowView drcat in proCat.DefaultView)
                 {
                     ProductsCategory cat = new ProductsCategory();
                     cat.LoadByPrimaryKey(Convert.ToInt32(drcat["ID"]));
                     cat.MarkAsDeleted();
                     cat.Save();
                 }
                 itm.LoadByPrimaryKey(itemId);
                 itm.MarkAsDeleted();
                 itm.Save();
                 XtraMessageBox.Show("Item Deleted!","Confirmation",MessageBoxButtons.OK,MessageBoxIcon.Information);
             }
         }
         else
         {
             XtraMessageBox.Show("Unable to Delete, This Item has been Received or Issued.", "Unable to Delete", MessageBoxButtons.OK, MessageBoxIcon.Stop);
         }
     }
 }
        private void btnSave_Click(object sender, EventArgs e)
        {
            Items itm = new Items();
            if (_itemId != 0)
                itm.LoadByPrimaryKey(_itemId);
            else
            {
                itm.AddNew();
                itm.IsInHospitalList = true;
            }
            itm.IINID = Convert.ToInt32(cboIIN.EditValue);
            //itm.StockCode = txtCatCode.Text + "-" + txtStockCode.Text;
            itm.StockCode = txtStockCode.Text;
            itm.Strength = txtStrength.Text;
            itm.DosageFormID = Convert.ToInt32(cboDosageForm.EditValue);
            //itm.IsDiscontinued = false;
            //itm.IsFree = ckIsFree.Checked;
            //itm.EDL = ckIsEDL.Checked;
            itm.UnitID = Convert.ToInt32(cboUnit.EditValue);
            itm.NeedExpiryBatch = ckNeedExp.Checked ;
            //itm.Pediatric = ckIsPedatric.Checked;
            //itm.Refrigeratored = ckIsRefrigerated.Checked;

            itm.Save();

            ItemSupplyCategory prodCate = new ItemSupplyCategory();

                //int catId = Convert.ToInt32(lstC.Tag);
            if (_categoryId != 0)
            {
                if (!prodCate.CategoryExists(itm.ID, _categoryId))
                {

                    prodCate.AddNew();
                    prodCate.ItemID = itm.ID;
                    prodCate.CategoryID = _categoryId;
                    prodCate.Save();
                }
            }

            XtraMessageBox.Show("Supply is Saved Successfully!","Confirmation",MessageBoxButtons.OK,MessageBoxIcon.Information);
            this.Close();
        }
        /// <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);
            }
        }
        /// <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();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            Items itm = new Items();
            if (_itemId != 0)
                itm.LoadByPrimaryKey(_itemId);
            else
            {
                itm.AddNew();
                itm.IsInHospitalList = true;

                Items itms = new Items();
                itm.ID = itms.GetNextItemID();
                itm.StorageTypeID = 1;
                itm.NearExpiryTrigger = 0;
            }
            itm.IINID = Convert.ToInt32(cboIIN.SelectedValue);

            //itm.StockCode = txtCatCode.Text + "-" + txtStockCode.Text;
            itm.StockCode = txtStockCode.Text;
            itm.Code = txtStock2.Text;
            itm.StockCodeDACA = txtStock3.Text;
            itm.Strength = txtStrength.Text;
            itm.DosageFormID = Convert.ToInt32(cboDosageForm.SelectedValue);
            itm.IsDiscontinued = ckIsDiscontinued.Checked;
            itm.IsFree = ckIsFree.Checked;
            itm.EDL = ckIsEDL.Checked;
            itm.UnitID = Convert.ToInt32(cboUnit.SelectedValue);
            itm.Pediatric = ckIsPedatric.Checked;
            itm.Refrigeratored = ckIsRefrigerated.Checked;
            itm.NeedExpiryBatch = true;
            itm.Save();

            ProductsCategory prodCate = new ProductsCategory();
            foreach (ListViewItem lstC in lstCat.Items)
            {
                int catId = Convert.ToInt32(lstC.Tag);

                if (prodCate.CategoryExists(itm.ID, catId)) continue;

                prodCate.AddNew();
                prodCate.ItemId = itm.ID;
                prodCate.SubCategoryID = catId;
                prodCate.Save();
            }

            if (itm.IsColumnNull("StockCode"))
            {
                // Update the Stock Code

                prodCate.Rewind();
                SubCategory sc = new SubCategory();
                sc.LoadByPrimaryKey(prodCate.SubCategoryID);

                if(sc.RowCount > 0)
                {
                    itm.StockCode = string.Format("{0}.{1}.{2}.{3}",sc.SubCategoryCode, 1, itm.DosageFormID, 1);
                    itm.Save();
                }
            }
            XtraMessageBox.Show( "Item is Saved Successfully!" , "Confirmation" , MessageBoxButtons.OK, MessageBoxIcon.Information);

            this.Close();
        }