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 MySql.Data;
using CLS_BL;
using CLS_DL;
using CLS_PL;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing.Printing;
using System.Drawing;
using System.Drawing.Text;

namespace SUNWEB
{
    public partial class CustomerMaster : 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();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        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_CustomerMaster = 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 CustId = string.Empty;
        string NewCustId = string.Empty;
        string Vw_Chk = string.Empty;
        string RcustId = string.Empty;
        string CardType = string.Empty;
        string SplBranChk = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            btnUpdate.Visible = false;
            //txtCustomerId.CssClass = "form-control";
            //txtCustomerId.Enabled = false;
            PID = "24";       // This is for Customer Master Page 
            if (!IsPostBack)
            {
                txtBirthDate.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();
                    ActiveCall(); 
                }
                
                
            }
            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;" + Microsoft.Security.Application.Encoder.HtmlEncode(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_RetailPayment"].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)
                            {
                                
                                LoadCustMasterGrid(Session["Branch_HQ"].ToString());
                            }

                        }


                    }

                }

            }
            else
            {

            }


        }

        protected void btnSearchbyVal_Click(object sender, EventArgs e)
        {
            string Query = "select BranchName from {0}.specialbranches where Branchid=1";
            string command = string.Format(Query, Session["Branch_HQ"]);
            SplBranChk = ObjCloudMain.ExecuteScalar(command);


            if (SplBranChk != "")
            {
                BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                Session["Branch_HQ"] = BranchAlias;

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

            }


            if (cmbSearch.SelectedIndex == 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' You Must Select Search By Selection ! ')", true);       

            }
             else if (cmbSearch.SelectedIndex == 1)
            {

             SplBranChk = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
            if (SplBranChk != "")
             {
                BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                Session["Branch_HQ"] = BranchAlias;
             }
            else
            {
                BranchAlias = Session["Branch_HQ"].ToString();

            }
               LoadCustMasterGrid(BranchAlias);
            }
               


            else if (cmbSearch.SelectedIndex == 2)
            {

                string QryLoad = "select *  from  {0}.customers  where CustomerNumber  like  CONCAT('%',@SearchText,'%') ";
                string command1 = string.Format(QryLoad, Session["Branch_HQ"]);
                MySqlParameter[] parameters1 =
                   {
                     new MySqlParameter("@SearchText",txtSearchVal.Text.ToString().Trim()),
                   };

                DT = ObjCloudMain.NewGetData_DT(command1, parameters1); 
                grdCustomerMaster.DataSource = DT;
                grdCustomerMaster.DataBind();

            }

            else if (cmbSearch.SelectedIndex == 3)
            {

                string QryLoad = "select *  from  {0}.customers  where CustomerName like CONCAT('%',@SearchText,'%') ";
                string command2 = string.Format(QryLoad, Session["Branch_HQ"]);
                MySqlParameter[] parameters2 =
                   {
                     new MySqlParameter("@SearchText",txtSearchVal.Text.ToString().Trim()),
                   };
                DT = ObjCloudMain.NewGetData_DT(command2, parameters2);
                grdCustomerMaster.DataSource = DT;
                grdCustomerMaster.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 4)
            {

                string QryLoad = "select *  from  {0}.customers  where ID  like  CONCAT('%',@SearchText,'%') ";
                string command3 = string.Format(QryLoad, Session["Branch_HQ"]);

                   MySqlParameter[] parameters3 =
                   {
                     new MySqlParameter("@SearchText", txtSearchVal.Text.ToString().Trim()),
                   };
                DT = ObjCloudMain.NewGetData_DT(command3, parameters3);
                grdCustomerMaster.DataSource = DT;
                grdCustomerMaster.DataBind();

            }

            else if (cmbSearch.SelectedIndex == 5)
            {

                string QryLoad = "select *  from  {0}.customers  where Mobile like  CONCAT('%',@SearchText,'%') ";
                MySqlParameter[] parameters4 =
                   {
                     new MySqlParameter("@SearchText", txtSearchVal.Text.ToString().Trim()),
                   };
                string commad4 = string.Format(QryLoad, Session["Branch_HQ"]);
                DT = ObjCloudMain.NewGetData_DT(commad4, parameters4);
                grdCustomerMaster.DataSource = DT;
                grdCustomerMaster.DataBind();

            }

        }
        protected void cmbSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtSearchVal.Text = "";


            if (cmbSearch.SelectedIndex == 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' You Must Select Search By Selection ! ')", true);

            }
            else if (cmbSearch.SelectedIndex == 1)
            {

                SplBranChk = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                if (SplBranChk != "")
                {
                    BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                    Session["Branch_HQ"] = BranchAlias;
                }
                else
                {
                    BranchAlias = Session["Branch_HQ"].ToString();

                }
                LoadCustMasterGrid(BranchAlias);
            }


        }

        protected void btnExcel_Click(object sender, EventArgs e)
        {


            string Qry = "select BranchName from {0}.specialbranches where Branchid=1";
            string command = string.Format(Qry, Session["Branch_HQ"]);
            SplBranChk = ObjCloudMain.ExecuteScalar(command);
            if (SplBranChk != "")
            {
                BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                Session["Branch_HQ"] = BranchAlias;
            }
            else
            {
                BranchAlias = Session["Branch_HQ"].ToString();

            }

            if (cmbBranches.SelectedIndex != 0)
            {
                if (Session["Isdowld_Acess"].ToString() == "N")
                {
                    Page page = HttpContext.Current.Handler as Page;
                    string message = "No Access To download";
                    System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + message + "');", true);
                }
                else
                {
                   
                    if (cmbBranches.Visible ==true)
                    {
                       string cmd1 =" SELECT CustomerID, CustomerNumber,ID, CustomerName,CompanyName, date(OpenDate) as OpenDate,  " +
                                    " DATE_FORMAT(LastDate, '%Y/%m/%d') as LastDate, DATE_FORMAT(Birthday, '%Y/%m/%d')  as Birthday, DATE_FORMAT(ExpiryDate, '%Y/%m/%d')   as ExpiryDate, " +
                                    " Address, PostalCode, City,StateOrProvince, Country, Tel1, Tel2, Fax,Mobile,Pager, EmailAddress,Contact, Active, Updated, Notes, CardType, BranchUpdated, " +
                                    " DepositBalance, TotalAmount, TotalBonusPoint, TotalDiscount, CurrentPoints, EmployeeNumber, MotherNric, MotherName, MotherMobile, MotherEmail, FatherNric, " +
                                    " FatherName, FatherMobile, FatherEmail, Age, Relation1, Relation2, CarModel, YearMade, "
                                    + " ChassisNo, Capacity, EngineNo, DATE_FORMAT(PointsExpiry, '%Y/%m/%d') as PointsExpiry, DueType, DueDays, CreditLimit, password, Picture,PDPA    FROM  {0}. customers  ";


                        string Command = string.Format(cmd1, BranchAlias);
                        DataTable Dt1 = new DataTable();
                        Dt1 = ObjMain.GetData_DT(Command);
                        //Create a dummy GridView
                        GridView GridView1 = new GridView();
                        GridView1.ShowFooter = true;
                        GridView1.AllowPaging = false;
                        GridView1.DataSource = Dt1;
                        GridView1.DataBind();
                        Response.Clear();
                        Response.Buffer = true;
                        Response.AddHeader("content-disposition",
                         "attachment;filename=CustomerMaster.xls");
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.ms-excel";
                        StringWriter sw = new StringWriter();
                        HtmlTextWriter hw = new HtmlTextWriter(sw);
                        for (int i = 0; i < GridView1.Rows.Count; i++)
                        {
                            //Apply text style to each Row
                            GridView1.Rows[i].Attributes.Add("class", "textmode");
                        }


                        GridView1.RenderControl(hw);

                        //style to format numbers to string
                        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                        Response.Write(style);
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.End();
                    }
                  


                }

            }
        }


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


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

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].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=" + Microsoft.Security.Application.Encoder.HtmlEncode(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_CustomerMaster = DtLicense.Rows[0]["CUSTOMERMASTER"].ToString();
                Session["L_CustomerMaster"] = L_CustomerMaster;
            }
            if (Session["L_CustomerMaster"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {

                //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 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);

                LoadCustMasterGrid(Session["Branch_HQ"].ToString());

                System.Threading.Thread.Sleep(2000);

            }

        }


        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 cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

            //txtCustomerId.CssClass = "form-control";
            //txtCustomerId.Enabled = false;

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("CustomerMaster.aspx");
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, 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;
                }

                if (cmbBranches.SelectedIndex == 1)
                {

                    BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                    Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                    UPDATEBRANCH(Cmb_BranchName);
                }
                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_CustomerMaster = DtLicense.Rows[0]["CUSTOMERMASTER"].ToString();
                    Session["L_CustomerMaster"] = L_CustomerMaster;
                }

                if (Session["L_CustomerMaster"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    if (cmbBranches.SelectedIndex == 1)
                    {
                       
                        btnSave.Enabled = false;
                        BranchAlias = Cmb_BranchName;
                       
                       
                    }
                    else
                    {
                        Response.Redirect("DeniedPage.aspx");
                    }


                }
                else
                {
                    if (Session["Write_Acess"].ToString() == "N")
                    {
                        
                        btnSave.Enabled = false;
                        btnUpdate.Enabled = false;
                        BranchAlias = Cmb_BranchName;
                        
                        
                    }
                    else
                    {
                        
                        btnSave.Enabled = true;
                        btnUpdate.Enabled = true;
                        BranchAlias = Session["Branch_HQ"].ToString();
                        LoadCustMasterGrid(BranchAlias);
                      
                    }


                }
            }

            //UPDATEBRANCH(BranchAlias);
  
        }


        protected void grdCustomerMaster_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Select")
            {
                //Determine the RowIndex of the Row whose Button was clicked.
                int rowIndex = Convert.ToInt32(e.CommandArgument);

                //Reference the GridView Row.
                GridViewRow row = grdCustomerMaster.Rows[rowIndex];

                //Fetch value of Name.
                string CustNoID = (row.FindControl("lblCustomerid") as Label).Text;



            }
        }


        public void SaveCustomerMaster()
        {
            SplBranChk = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");

            if (SplBranChk != "")
            {
                BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                Session["Branch_HQ"] = BranchAlias;

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

            }

            CustId = ObjSel.GetMaxCUSTID(BranchAlias);

            NewCustId = String.Format("{0:D5}", int.Parse(CustId));
            NewCustId = "CUS" + NewCustId;
            CardType = "0";
            string QrySave = " Insert into {0}.customers  (CustomerNumber,ID,CustomerName,OpenDate,LastDate,Birthday,ExpiryDate,Mobile,EmailAddress,CardType)" +
                             " values(@CustomerNumber,@ID,@CustomerName,@OpenDate,@LastDate,@Birthday,@ExpiryDate,@Mobile,@EmailAddress,@CardType)";

            string command = string.Format(QrySave, BranchAlias);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@CustomerNumber",txtCustNo.Text),
                     new MySqlParameter("@ID",NewCustId),
                     new MySqlParameter("@CustomerName",txtCustomerName.Text),
                     new MySqlParameter("@OpenDate",Curr_DateOnly),
                     new MySqlParameter("@LastDate",Curr_DateOnly),
                     new MySqlParameter("@Birthday",txtBirthDate.Text),
                     new MySqlParameter("@ExpiryDate",Curr_DateOnly),
                     new MySqlParameter("@Mobile",txtMobileNo.Text),
                     new MySqlParameter("@EmailAddress",txtEmail.Text),
                     new MySqlParameter("@CardType",CardType),
                    };

            K = ObjCloudMain.ExecuteQuery(command, parameters);
            if (K > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Customer Added Successfully ');location.href='CustomerMaster.aspx' ", true);       
            }

        
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SaveCustomerMaster();

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

            SplBranChk = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");

            if (SplBranChk != "")
            {
                BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                Session["Branch_HQ"] = BranchAlias;

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

            }
                                 

           // RcustId=ObjCloudMain.ExecuteScalar("select CustomerID from " + BranchAlias + ".customers where ID='"+txtCustomerId.Text+"'  ");
            UpdateCustMaster(BranchAlias,hidCustomerID.Value);

        }

        public void UpdateCustMaster(string Branch, string CusID)
        {
            string QryUpdate = "Update {0}.customers set CustomerNumber=@CustomerNumber,CustomerName=@CustomerName ,LastDate=@LastDate, Birthday=@Birthday, Mobile=@Mobile, EmailAddress=@EmailAddress where  CustomerID=@CustomerID ";
            string command = string.Format(QryUpdate, Branch);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@CustomerNumber",txtCustNo.Text),
                     new MySqlParameter("@CustomerName",txtCustomerName.Text),
                     new MySqlParameter("@LastDate",Curr_DateOnly),
                     new MySqlParameter("@Birthday",txtBirthDate.Text),
                     new MySqlParameter("@Mobile",txtMobileNo.Text),
                     new MySqlParameter("@EmailAddress",txtEmail.Text),
                     new MySqlParameter("@CustomerID",CusID),
                                      
                    };
            K = ObjCloudMain.ExecuteQuery(command, parameters);
            if (K > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Customer Updated Successfully ');location.href='CustomerMaster.aspx' ", true);
            }

        
        }

        public void LoadCustMasterGrid(string Branch_Nam)
        {

            SplBranChk = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");

            if (SplBranChk != "")
            {
                BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                Session["Branch_HQ"] = BranchAlias;

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

            }


             string QryLoad = "select *  from  {0}.customers;";
             string command = string.Format(QryLoad, BranchAlias);
             DT = ObjCloudMain.GetData_DT(command);
             grdCustomerMaster.DataSource = DT;
             grdCustomerMaster.DataBind();

        
        }

        protected void grdCustomerMaster_SelectedIndexChanged(object sender, EventArgs e)
        {

            btnUpdate.Visible = true;
            btnSave.Visible = false;
            SplBranChk = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");

            if (SplBranChk != "")
            {
                BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                Session["Branch_HQ"] = BranchAlias;

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

            }


            string CustNoID = (grdCustomerMaster.SelectedRow.FindControl("lblCustomerid") as Label).Text;

            hidCustomerID.Value = CustNoID;



            Dt2 = ObjSel.GetCustMasterDetails(BranchAlias, CustNoID);
            if (Dt2.Rows.Count == 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Customer Not Fund ')", true);
            }
            else
            {
                ReadCustomerMaster(CustNoID);

            }



        }
        /// <summary>
        ///  This Function Read's CustomerMaster Data
        /// </summary>
        public void ReadCustomerMaster( string Custoemrid )
        {

            //txtCustomerId.CssClass = "form-control";
            //txtCustomerId.Enabled = false;

            SplBranChk = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");

            if (SplBranChk != "")
            {
                BranchAlias = ObjCloudMain.ExecuteScalar("select BranchName from " + Session["Branch_HQ"] + ".specialbranches where Branchid=1");
                Session["Branch_HQ"] = BranchAlias;

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

            }

            Dt2 = ObjSel.GetCustMasterDetails(BranchAlias, Custoemrid);
            if (Dt2.Rows.Count > 0)
            {

                btnSave.Visible = false;
                btnUpdate.Visible = true;

                txtCustNo.Text = Dt2.Rows[0]["CustomerNumber"].ToString();
                txtCustomerName.Text = Dt2.Rows[0]["CustomerName"].ToString();
                //txtCustomerId.Text = Dt2.Rows[0]["ID"].ToString();
                txtBirthDate.Text = Dt2.Rows[0]["Birthday"].ToString();
                txtMobileNo.Text = Dt2.Rows[0]["Mobile"].ToString();
                
                txtEmail.Text = Dt2.Rows[0]["EmailAddress"].ToString();



            }
            else
            {

                if (hidCustomerID.Value != "")
                {
                    btnSave.Visible = false;
                    btnUpdate.Visible = true;

                }
                else
                {

                    btnSave.Visible = true;
                    btnUpdate.Visible = false;
                }
               


            }


        }

        //protected void txtCustNo_TextChanged(object sender, EventArgs e)
        //{
  
        //  ReadCustomerMaster(hidCustomerID.Value);

        //}

    }
}