using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using MySql.Data;
using System.Reflection;
using System.Web.Services;
using System.Web.Script.Serialization;
using CLS_BL;
using CLS_DL;
using CLS_PL;

namespace SUNWEB
{
    public partial class PromoCode : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        MySqlCommand Cmdv = new MySqlCommand();
        // User Variables 
        string UserId = string.Empty;
        string UserName = string.Empty;
        string PortalTypeId = string.Empty;
        string cd_Id = string.Empty;
        string Datapath = string.Empty;
        string cd_BranchAlias = string.Empty;
        string IsMultiBranch = string.Empty;
        string IsSuperAdmin = string.Empty;
        string ActiveCallvalue = string.Empty;
        // License Variables ..
        string PID = string.Empty;
        string Page_Acess = string.Empty;
        string Read_Acess = string.Empty;
        string Write_Acess = string.Empty;
        string Isdowld_Acess = string.Empty;
        string Rcd_id = string.Empty;
        string RPortalid = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        string L_MaxUserCnt = string.Empty;

        string L_PromoCode = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();
        string BranchAlias = string.Empty;

        string Vw_Chk = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            



            btnUpdate.Visible = false;

            PID = "44";    // This is for Promocode Page 
            if (!IsPostBack)
            {
                txtPromoStartDt.Text = Curr_DateOnly;
                txtPromoEnddt.Text = Curr_DateOnly;
                lblperSynmbol.Visible = false;

                txtSearchStartDt.Text = Curr_DateOnly;
                txtSearchEndDt.Text = Curr_DateOnly;


            }
            MonthstartDt = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();

                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();
                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName();
                    ActiveCall();
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;

                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                lblBranchAliasName.ForeColor = System.Drawing.Color.DodgerBlue;
                lblBranchAliasName.Text = "Branch Name" + "&nbsp;" + "-" + "&nbsp;" + Curr_BranchFullName + "&nbsp; ";

                cd_BranchAlias = Session["Branch_HQ"].ToString();
                Datapath = Session["DataPath"].ToString();
                PortalTypeId = Session["PortalTypeId"].ToString();

                DT = ObjUserBL.GetPageRightsDetailsPid(Session["UserId"].ToString(), PID);
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }
                if ((Session["L_PromoCode"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    // lblMsgTotalSelection.Text = "Item Sale  Between" + "&nbsp;&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  and  &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    if (!IsPostBack)
                    {
                        if (Session["Isdowld_Acess"].ToString() == "N")
                        {
                            // btnExcel.Enabled = false;
                            Response.Write(@"<script language='javascript'>alert('No Access To download.')</script>");
                        }
                        else
                        {


                            if (cmbBranches.Visible == false)
                            {
                                //  BindGridview(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                            }

                        }


                    }

                }

            }
            else
            {

            }


        }


        public void ActiveCall()
        {
            string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
            ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
            if (ActiveCallvalue == "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            }


            ISHQ = ObjMain.ExecuteScalar("select BranchName from " + ActiveCallvalue + ".branches where Branchname='" + ActiveCallvalue + "' and branchID=1;");  //now 

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
                UPDATEBRANCH(ActiveCallvalue);
            }

            cd_BranchAlias = ActiveCallvalue;
            Curr_BranchFullName = ObjUserBL.GetBranchCurr_BranchVal(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cd_BranchAlias);
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
            cmbBranches.Items.FindByText(Curr_BranchFullName).Selected = true;
            Branchidval = ObjUserBL.GetBranchIDbyName(ActiveCallvalue, ActiveCallvalue);
            if (Branchidval != "")
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Session["Fistbranch"].ToString());

            }
            if (DT.Rows.Count > 0)
            {
                Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                Session["Page_Acess"] = Page_Acess;
                Session["Read_Acess"] = Read_Acess;
                Session["Write_Acess"] = Write_Acess;
                Session["Isdowld_Acess"] = Isdowld_Acess;
            }
            Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + ActiveCallvalue + "';");
            RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
            DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);
            if (DtLicense.Rows.Count > 0)
            {
                L_PromoCode = DtLicense.Rows[0]["PROMOCODE"].ToString();
                Session["L_PromoCode"] = L_PromoCode;
            }
            if (Session["L_PromoCode"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {
                btnUpdate.Visible = false;
                btnAdd.Visible =true;

                //btnExcel.Enabled = true;
                //lblMsgTotalSelection.Text = "Total Sale Selection Between" + "&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                // BindGridview(ActiveCallvalue, txtStartDt.Text, txtEndDt.Text);
                System.Threading.Thread.Sleep(2000);

                LoadPromoCode(Cmb_BranchName);

            }

        }


        public void LoadBranchName()
        {
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtNormalUser;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }
        public void LoadBranchName4SuperAdmin()
        {
            DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdmin8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtSuperAdmin.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtSuperAdmin;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }
        public void UPDATEBRANCH(string ActiveCallvalue)
        {
            if (!string.IsNullOrEmpty(Session["UserId"] as string))
            {
                Useridvalue = Session["UserId"].ToString();
                QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + ActiveCallvalue + "' where Userid=" + Useridvalue + "";
                S = ObjMain.ExecuteNonQuery(QueryCurr_Select);
            }
            else
            {
                Response.Redirect("Login.aspx");

            }

        }


        protected void btnGetReports_Click(object sender, EventArgs e)
        {

        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPromotionList();", true);
            txtInputPromocodeName.Text = "";
        }
        protected void btnSearchPromocode_Click(object sender, EventArgs e)
        {
            if (cmbBranches.Visible == true)
            {
                #region  Validation Between HQ Branch and Normal Branch 
                BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                if (BranchFullName == "HQ")
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    BranchAlias = Cmb_BranchName;

                }
                #endregion

            }
            else
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }

            if (txtInputPromocodeName.Text != "")
            {
                DataTable DtSearchResult = new DataTable();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPromotionList();", true);

                string Query_by_Promocodename = "  select  Promoid,PromocodeName,PromoCode,PromoValue, DATE_FORMAT(StartDate,'%Y-%m-%d') as StartDate, DATE_FORMAT(EndDate,'%Y-%m-%d') as EndDate,"
                                        + " PromoTypeid , CASE PromoTypeid "
                                        + " WHEN 1  THEN 'Percentage' WHEN 2  THEN 'Amount'  else null end as PromoType  from {0}.Promocode where status = 'A' and  PromocodeName like CONCAT('%',@SearchVal,'%'); ";

                MySqlParameter[] parameters =
                {
                     new MySqlParameter("@SearchVal",txtInputPromocodeName.Text.ToString().Trim()),
                };

                string command = string.Format(Query_by_Promocodename, BranchAlias);
                DtSearchResult = ObjMain.NewGetData_DT(command, parameters);
                GrdPromoCode.DataSource = DtSearchResult;
                GrdPromoCode.DataBind();

            }
            else if (txtSearchStartDt.Text!="" && txtSearchEndDt.Text!="") 
            {
                DataTable DtSearchResult = new DataTable();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPromotionList();", true);

                string Query_by_Promocodename = "  select  Promoid,PromocodeName,PromoCode,PromoValue, DATE_FORMAT(StartDate,'%Y-%m-%d') as StartDate, DATE_FORMAT(EndDate,'%Y-%m-%d') as EndDate,"
                                        + " PromoTypeid , CASE PromoTypeid "
                                        + " WHEN 1  THEN 'Percentage' WHEN 2  THEN 'Amount'  else null end as PromoType  from {0}.Promocode where status = 'A'   and EndDate <= @EndDate AND StartDate >= @StartDate ; ";

                MySqlParameter[] parameters =
                    {
                     
                     new MySqlParameter("@StartDate",txtSearchStartDt.Text),
                     new MySqlParameter("@EndDate",txtSearchEndDt.Text),
                    };

                string command = string.Format(Query_by_Promocodename, BranchAlias);
                DtSearchResult = ObjMain.NewGetData_DT(command, parameters);
                GrdPromoCode.DataSource = DtSearchResult;
                GrdPromoCode.DataBind();

            }

        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {



            System.Threading.Thread.Sleep(1000);
            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Redirect("PromoCode.aspx");
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Value));
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }

                ISHQ = ObjMain.ExecuteScalar("select BranchName from branches where Branchname='" + ActiveCallvalue + "' and branchID=1;");  //now 

                if (ISHQ != "")
                {
                    ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
                    UPDATEBRANCH(ActiveCallvalue);
                }
                else
                {
                    BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + Cmb_BranchName + "';");
                    RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
                    DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);

                }

                UPDATEBRANCH(Cmb_BranchName);
                if (DtLicense.Rows.Count > 0)
                {
                    L_PromoCode = DtLicense.Rows[0]["PROMOCODE"].ToString();
                    Session["L_PromoCode"] = L_PromoCode;
                }

                if (Session["L_PromoCode"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    LoadPromoCode(Cmb_BranchName);
                }

            }

        }
        

       protected void btnUpdate_Click(object sender, EventArgs e)
        {
          UpdatePromoCode(Convert.ToInt32(hidvaluePromoid.Value));
        }
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (cmbPromoCodeType.SelectedIndex == 0)
            {

                Page page = HttpContext.Current.Handler as Page;
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Select PromoCode Type ');", true);

            }
            else
            {
                SavePromocode();
            }

        }

        public void SavePromocode()
        {

            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                #region  Validation Between HQ Branch and Normal Branch 
                BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                if (BranchFullName == "HQ")
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    BranchAlias = Cmb_BranchName;

                }
                #endregion


            }

            string ProQuert = "INSERT INTO {0}.Promocode ( PromocodeName,"
                     + " PromoCode ,PromoTypeid  ,PromoValue ,StartDate ,EndDate ,Status ,CreatedDate,CreatedBy ) "
                     + " VALUES "
                     + " (@PromocodeName, @PromoCode, @PromoTypeid, @PromoValue, @StartDate, @EndDate, "
                     + " @Status,@CreatedDate,@CreatedBy); ";


            int _promoCodeType = 0;
            if (cmbPromoCodeType.SelectedIndex == 1)
            {
                _promoCodeType = 0;
            }
            else if (cmbPromoCodeType.SelectedIndex == 2)
            {
                _promoCodeType = 1;
            }
              


            MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@PromocodeName",txtPromocodeName.Text.ToString().Trim()),
                     new MySqlParameter("@PromoCode",txtPromoCode.Text.ToString().Trim()),
                     new MySqlParameter("@PromoTypeid",_promoCodeType),
                     new MySqlParameter("@PromoValue",txtPromoValue.Text.ToString().Trim()),
                     new MySqlParameter("@StartDate",txtPromoStartDt.Text),
                     new MySqlParameter("@EndDate",txtPromoEnddt.Text),
                     new MySqlParameter("@Status","A"),
                     new MySqlParameter("@CreatedDate",Curr_Date),
                     new MySqlParameter("@CreatedBy",Session["UserId"].ToString()),

                   };

            string commmand = string.Format(ProQuert, BranchAlias);
            K = ObjMain.ExecuteQuery(commmand, parameters);
            if (K > 0)
            {
                Page page = HttpContext.Current.Handler as Page;
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('PromoCode Added Succeessfully.');location.href='PromoCode.aspx';", true);
            }


        }

        public void UpdatePromoCode(int _promoid)
        {
            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Microsoft.Security.Application.Encoder.HtmlEncode(Cmb_BranchName);
            }
            string Update_query = " Update  {0}.Promocode set PromocodeName=@PromocodeName,"
                                + " PromoCode=@PromoCode ,PromoTypeid=@PromoTypeid,PromoValue=@PromoValue ,StartDate=@StartDate ," 
                                + " EndDate=@EndDate,ModifiedDate=@ModifiedDate,CreatedBy=@CreatedBy where Promoid=@Promoid ;";



            int _promoCodeType = 0;
            if (cmbPromoCodeType.SelectedIndex == 1)
            {
                _promoCodeType = 0;
            }
            else if (cmbPromoCodeType.SelectedIndex == 2)
            {
                _promoCodeType = 1;
            }



            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@Promoid",_promoid),
                     new MySqlParameter("@PromocodeName",txtPromocodeName.Text.ToString().Trim()),
                     new MySqlParameter("@PromoCode",txtPromoCode.Text.ToString().Trim()),
                     new MySqlParameter("@PromoTypeid",_promoCodeType),
                     new MySqlParameter("@PromoValue",txtPromoValue.Text.ToString().Trim()),
                     new MySqlParameter("@StartDate",txtPromoStartDt.Text),
                     new MySqlParameter("@EndDate",txtPromoEnddt.Text),
                     new MySqlParameter("@ModifiedDate",Curr_Date),
                     new MySqlParameter("@CreatedBy",Session["UserId"].ToString()),

                   };

            string command = string.Format(Update_query, BranchAlias);

            L = ObjMain.ExecuteQuery(command,parameters);

            if (L > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('PromoCode  Updated Successfully ! ');location.href='PromoCode.aspx'", true);
               // Response.Redirect("PromoCode.aspx");

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('PromoCode Not Updated! ');location.href='PromoCode.aspx'", true);
                //Response.Redirect("PromoCode.aspx");
            }

        }
        protected void GrdPromoCode_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Microsoft.Security.Application.Encoder.HtmlEncode(Cmb_BranchName);
            }
            string Name = e.CommandName;

            if (Name == "Delete")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                string Update_Query = " Update {0}.Promocode  set Status='D' , ModifiedDate=@ModifiedDate,CreatedBy=@CreatedBy where Promoid=@Promoid;";
                string command = string.Format(Update_Query, BranchAlias);


                MySqlParameter[] parameters =
               {
                     new MySqlParameter("@Promoid",index),
                     new MySqlParameter("@ModifiedDate",Curr_Date),
                     new MySqlParameter("@CreatedBy",Session["UserId"].ToString()),
               };

                K = ObjMain.ExecuteQuery(command, parameters);

                if (K > 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('PromoCode  Deleted Successfully ! ');location.href='PromoCode.aspx'", true);
                    Response.Redirect("PromoCode.aspx");
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('PromoCode Not Deleted  ! ');location.href='PromoCode.aspx'", true);
                }

            }

        }


        public void LoadPromoCode(string db)
        {
            DataTable DtResult = new DataTable();
            string Query = " select  Promoid,PromocodeName,PromoCode,PromoValue, status,DATE_FORMAT(StartDate,'%Y-%m-%d') as StartDate, DATE_FORMAT(EndDate,'%Y-%m-%d') as EndDate,"
                         + " PromoTypeid , CASE PromoTypeid "
                         + " WHEN 1  THEN 'Percentage' WHEN 0  THEN 'Amount'  else null end as PromoType  from {0}.Promocode where status = 'A'; ";
            string command = string.Format(Query, db);
            DtResult = ObjMain.GetData_DT(command);
            GrdPromoCode.DataSource = DtResult;
            GrdPromoCode.DataBind();
        }

        

        protected void cmbSearchByPromoCodeType_SelectedIndexChanged(object sender, EventArgs e)
        {


            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Microsoft.Security.Application.Encoder.HtmlEncode(Cmb_BranchName);
            }


            if (cmbSearchByPromoCodeType.SelectedIndex != 0)
            {

                int _promoCodeType = 0;
                if (cmbSearchByPromoCodeType.SelectedIndex == 1)
                {
                    _promoCodeType = 1;
                }
                else if (cmbSearchByPromoCodeType.SelectedIndex == 2)
                {
                    _promoCodeType = 0;
                }



                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPromotionList();", true);

                DataTable DtResult = new DataTable();
                string Query = " select  Promoid,PromocodeName,PromoCode,PromoValue,status, DATE_FORMAT(StartDate,'%Y-%m-%d') as StartDate, DATE_FORMAT(EndDate,'%Y-%m-%d') as EndDate,"
                             + " PromoTypeid , CASE PromoTypeid "
                             + " WHEN 0 THEN 'Amount'  WHEN 1  THEN 'Percentage'  else null end as PromoType  from {0}.Promocode where status = 'A' and PromoTypeid=@PromoTypeid ; ";
                string command = string.Format(Query, BranchAlias);

                MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@PromoTypeid",_promoCodeType),
                  };
                DtResult = ObjMain.NewGetData_DT(command, parameters);

                GrdPromoCode.DataSource = DtResult;
                GrdPromoCode.DataBind();


            }
            else
            {
                GrdPromoCode.DataSource = null;
                GrdPromoCode.DataBind();

                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPromotionList();", true);
            }


        }

        public string  SearchByPromoCode(string promocode)
        {
            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Microsoft.Security.Application.Encoder.HtmlEncode(Cmb_BranchName);
            }


            string Query = "  select  Promoid  from {0}.Promocode where status = 'A' and PromoCode=@PromoCode; ";
            string command = string.Format(Query, BranchAlias);

            MySqlParameter[] parameters =
              {
                     new MySqlParameter("@PromoCode",promocode),
              };
            string CheckVAL = ObjMain.NewExecuteScalar(command, parameters);

            return CheckVAL;


        }
        protected void cmbPromoCodeType_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (hidvaluePromoid.Value != "")
            {
                btnUpdate.Visible = true;
                btnAdd.Visible = false;
            }
            else
            {
               
            }

            if (cmbPromoCodeType.SelectedIndex == 2)
            {
                lblperSynmbol.Visible = true;

            }
            else if (cmbPromoCodeType.SelectedIndex == 0)
            {

                lblperSynmbol.Visible = false;
            }

            else if (cmbPromoCodeType.SelectedIndex == 1)
            {

                lblperSynmbol.Visible = false;
            }


        }


        protected void OnSelectedIndexChanged(object sender, EventArgs e)
        {

            btnAdd.Visible = false;
            btnUpdate.Visible = true;

            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Microsoft.Security.Application.Encoder.HtmlEncode(Cmb_BranchName);
            }

            //Accessing TemplateField Column controls.
            string PromoId  = (GrdPromoCode.SelectedRow.FindControl("lblPromoid") as Label).Text;

            hidvaluePromoid.Value = PromoId;

            DataTable DtResult = new DataTable();
            string Query = "  select  Promoid,PromocodeName,PromoCode,PromoValue, status,DATE_FORMAT(StartDate,'%Y-%m-%d') as StartDate, DATE_FORMAT(EndDate,'%Y-%m-%d') as EndDate,"
                         + " PromoTypeid , CASE PromoTypeid "
                         + " WHEN 0  THEN 'Amount'   WHEN 1  THEN 'Percentage' else null end as PromoType  from {0}.Promocode where status = 'A' and PromoId=@PromoId; ";
            string command = string.Format(Query, BranchAlias);

            MySqlParameter[] parameters =
              {
                     new MySqlParameter("@Promoid",PromoId),
              };
            DtResult = ObjMain.NewGetData_DT(command,parameters);

            if (DtResult.Rows.Count > 0)
            {
                txtPromocodeName.Text = DtResult.Rows[0]["PromocodeName"].ToString();
                txtPromoCode.Text= DtResult.Rows[0]["PromoCode"].ToString();
                txtPromoValue.Text= DtResult.Rows[0]["PromoValue"].ToString();
                txtPromoStartDt.Text= DtResult.Rows[0]["StartDate"].ToString();
                txtPromoEnddt.Text= DtResult.Rows[0]["EndDate"].ToString();
                string _promotypeid= DtResult.Rows[0]["PromoTypeid"].ToString();
                if (_promotypeid.Equals("0"))
                {
                    cmbPromoCodeType.SelectedIndex = 1;
                }
                else if (_promotypeid.Equals("1"))
                {
                    cmbPromoCodeType.SelectedIndex = 2;
                }
                else
                {
                    cmbPromoCodeType.SelectedIndex = 0;
                }

            }





        }

        protected void txtPromoCode_TextChanged(object sender, EventArgs e)
        {
            string isval = string.Empty;
            isval = SearchByPromoCode(txtPromoCode.Text.ToString().Trim());

            if (isval != "")
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('PromoCode Already Exist.Try Another Promocode ! ')", true);
                txtPromoCode.Text = "";
                txtPromoCode.Focus();
            }
            else
            { 


            
            }


        }
    }
    }