protected void btnPrintAll_Click(object sender, EventArgs e)
        {
            try
            {
                if (ddlMarket.SelectedIndex == -1)
                {
                    Alert.Show("Please select a market first.");
                    ddlMarket.Focus();
                    return;
                }

                int marketId = int.Parse(ddlMarket.SelectedValue);

                DataSet ds = new DataSet();

                DataTable dtBillDetail = new BillMaster().GetBillMasterDetailForReport(marketId);
                ds.Tables.Add(dtBillDetail);

                DataTable dtCompany = new Company().GetCompanyDatatableById(1);
                ds.Tables.Add(dtCompany);

                Session["ReportDataset"] = ds;

                string myScript = "window.open('CrystalReportViewer.aspx?report=crptBillCopy.rpt');";
                //string myScript = "window.open('ReportView.aspx?report=Report1.rdlc');";
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "OpenPopup", myScript, true);

            }
            catch (Exception ex)
            {
                Alert.Show("Error during leave grid event. Error: " + ex.Message);
            }
        }
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            StringBuilder strSuccess=new StringBuilder();
            StringBuilder strFailure = new StringBuilder();

            strSuccess.Append("<strong>Success</strong><br>");
            strFailure.Append("<strong>Failure</strong><br>");

            try
            {
                if (ddlMarket.SelectedIndex <= 0)
                {
                    Alert.Show("Please select a market first.");
                    ddlMarket.Focus();
                    return;
                }

                int marketId = int.Parse(ddlMarket.SelectedValue);
                List<Shop> shopList = new Shop().GetAllShopByMarketId(marketId);
                BillMaster billMaster = new BillMaster();
                BillDetail billDetail = new BillDetail();

                foreach (ListItem li in cbListShops.Items)
                {
                    if (!li.Selected) continue;

                    int shopId = int.Parse(li.Value);

                    Shop shop = shopList.Find(x => x.Id == shopId);
                    try
                    {
                        #region process bill master data

                        string monthYearText = ddlMonth.SelectedItem.Text;
                        string monthYearVal = ddlMonth.SelectedValue;

                        ShopeMapping shopeMapping = new ShopeMapping().GetAllShopeMappingByShopId(shop.Id);

                        billMaster.BilGeneratelDate = DateTime.Parse(txtDate.Text);
                        billMaster.BillMonth = monthYearText.Substring(5);
                        billMaster.BillYear = int.Parse(monthYearText.Substring(0, 4));
                        billMaster.TenantId = shopeMapping.TenantId;

                        billMaster.BillNo = billMaster.BillYear + "-" + monthYearVal.Substring(5) + "-" +
                                            shop.Id + "-" + shopeMapping.TenantId;

                        billMaster.GenerateBy = 1;
                        billMaster.ApprovedBy = 0;
                        billMaster.TotalAmount = 0;
                        billMaster.TotalPayment = 0;
                        billMaster.LastPaymentDate = (DateTime) dtpLastDate.SelectedDate;

                        string MonthVal = ddlMonth.SelectedValue.Substring(5);
                        billMaster.BillMonthId = int.Parse(MonthVal);
                        int success = 0;

                        int billId = billMaster.CheckExistanceByBillNo(billMaster.BillNo);
                        if (billId > 0)
                        {
                            if (!chkUpdateExisting.Checked)
                            {
                                strFailure.Append("Bill already generated for the shop: " + shop.ShopNo + "<br>");
                                continue;
                            }

                            billMaster.Id = billId;
                            success = billMaster.UpdateBillMaster();
                        }
                        else
                        {
                            success = billMaster.InsertBillMaster();
                            billMaster.Id = new BillMaster().GetLastId();
                        }

                    #endregion

                        #region process bill detail data

                        if (success > 0)
                        {
                            billDetail = new BillDetail();
                            billDetail.BillMasterId = billMaster.Id;
                            billDetail.MarketId = int.Parse(ddlMarket.SelectedValue);
                            billDetail.ShopId = shop.Id;
                            billDetail.MonthlyRent = shopeMapping.MonthlyRent;
                            billDetail.ServiceCharge = shopeMapping.ServiceCharge;
                            billDetail.MiscBills = shopeMapping.MiscBill;

                            if (chkPrevDue.Checked)
                            {
                                DueInstallment installment = new DueInstallment().GetDueInstallmentByTenant(billMaster.TenantId);
                                if (installment.Id != 0)
                                {
                                    billDetail.PreviousDue = installment.InstallmentAmount;
                                    if (installment.DueAmount < installment.InstallmentAmount)
                                        billDetail.PreviousDue = installment.DueAmount;
                                }
                                else
                                {
                                    if (billDetail.CheckBillExistenceByTenant(billMaster.TenantId, shop.Id) > 0)
                                        billDetail.PreviousDue = billDetail.GetLastDueTenantAndShopWise(billMaster.TenantId, shop.Id);
                                    else
                                        billDetail.PreviousDue = new ShopeMapping().GetAllShopeMappingByShopId(shop.Id).PreviousDue;
                                }

                            }
                            else
                                billDetail.PreviousDue = 0;

                            billDetail.LateFee = Math.Round((shopeMapping.MonthlyRent*5)/100,0);
                            billDetail.Payment = 0;
                            billDetail.IsClosed = false;
                            billDetail.ClosedBy = 0;

                            if (billId > 0)
                            {
                                int billDetailId = billDetail.GetBillDetailIdByMasterId(billId);
                                if (billDetailId > 0)
                                {
                                    billDetail.Id = billDetailId;
                                    success = billDetail.UpdateBillDetail();
                                }
                                else
                                    success = billDetail.InsertBillDetail();
                            }
                            else
                                success = billDetail.InsertBillDetail();

                            //update total amount in master table
                            if (success > 0)
                            {
                                decimal totalAmount = (billDetail.MonthlyRent + billDetail.ServiceCharge +
                                                       billDetail.MiscBills +
                                                       billDetail.PreviousDue);

                                billMaster.UpdateTotalAmount(billMaster.Id, totalAmount);

                                strSuccess.Append("Bill generated for Shop: " + shop.ShopNo + "<br>");
                            }
                        }

                        #endregion

                    }

                    catch (Exception ex)
                    {
                        strFailure.Append("Bill generate failed for Shop " + shop.ShopNo + ". Error: " + ex.Message +
                                          "<br>");
                        continue;
                    }
                }

                strFailure.Append("<br><br>");

                ltrStatus.Text = strFailure.ToString() + strSuccess.ToString();
            }
            catch (Exception ex)
            {

                Alert.Show(ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadGrid()
        {
            try
            {
                //if (ddlMarket.SelectedIndex <= 0) return;

                if (ddlMonth.SelectedIndex == -1) return;

                int marketId = 0;

                if(ddlMarket.SelectedIndex>0) marketId = int.Parse(ddlMarket.SelectedValue);

                string month = ddlMonth.SelectedItem.Text.Substring(5);
                int year = int.Parse(ddlMonth.SelectedItem.Text.Substring(0, 4));

                DataTable dt = new BillMaster().GetBillMasterDetailForGrid(year, month, marketId);

                if (dt.Rows.Count > 0)
                {
                    DataRow row = dt.NewRow();

                    dt.Rows.Add(row);
                }

                RadGrid1.DataSource = dt;
                RadGrid1.DataBind();
            }
            catch (Exception ex)
            {
                Alert.Show("Error in method 'LoadLeaveDetailsGrid'. Error: " + ex.Message);
            }
        }
        protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {

                if (e.CommandName == "btnPayment")
                {
                    GridDataItem item = (GridDataItem)e.Item;
                    int id = int.Parse(item["colId"].Text);
                    DateTime lastDate = DateTime.Parse(item["colPayDate"].Text);

                    DateTime payDate = DateTime.Parse(dtpPaymentDate.SelectedDate.ToString());
                    bool applyLateFee = (payDate > lastDate) ? true : false;
                    if (id != 0)
                    {
                        int success = new BillMaster().UpdatePaymentById(id, applyLateFee);
                        if (success > 0)
                            this.LoadGrid();
                    }
                }

            }
            catch (Exception ex)
            {
                Alert.Show("Error during leave grid event. Error: " + ex.Message);
            }
        }
        private DataTable GetBillData()
        {
            if (ddlMonth.SelectedIndex == -1) return new DataTable();

            int marketId = 0;

            if (ddlMarket.SelectedIndex > 0) marketId = int.Parse(ddlMarket.SelectedValue);

            string month = ddlMonth.SelectedItem.Text.Substring(5);
            int year = int.Parse(ddlMonth.SelectedItem.Text.Substring(0, 4));

            DataTable dt;
            if(rbDue.Checked)
                dt = new BillMaster().GetBillMasterDetailForGridWithCondition(year, month, marketId, " And Due > 0");
            else if(rbPaid.Checked)
                dt = new BillMaster().GetBillMasterDetailForGridWithCondition(year, month, marketId, " And Due = 0");
            else
                dt = new BillMaster().GetBillMasterDetailForGrid(year, month, marketId);

            return dt;
        }
        protected void RadGrid1_ItemCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {

                if (e.CommandName == "btnPrint")
                {
                    GridDataItem item = (GridDataItem) e.Item;
                    int id = int.Parse(item["colId"].Text);

                    if (id != 0)
                    {
                        DataSet ds = new DataSet();

                        DataTable dtBillDetail = new BillMaster().GetBillMasterDetailForSingleReport(id);
                        ds.Tables.Add(dtBillDetail);

                        DataTable dtCompany = new Company().GetCompanyDatatableById(1);
                        ds.Tables.Add(dtCompany);

                        Session["ReportDataset"] = ds;

                        //string myScript = "window.open('reportview.aspx?report=rptBillCopy.rdlc');";
                        string myScript = "window.open('CrystalReportViewer.aspx?report=crptBillCopyWithoutCaption.rpt');";

                        Page.ClientScript.RegisterStartupScript(Page.GetType(), "OpenPopup", myScript, true);
                    }

                }
            }
            catch (Exception ex)
            {
                Alert.Show("Error during leave grid event. Error: " + ex.Message);
            }
        }