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;
namespace SUNWEB
{
    public partial class GroupMaster : 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 U = 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");

        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        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();
        DataTable DTGroup1 = new DataTable();
        DataTable DTGroup2 = new DataTable();
        DataTable DTGroup3 = new DataTable();
        DataTable DTGroup4 = new DataTable();
        DataTable DTGroup5 = new DataTable();

        DataTable DTCommonGroup = new DataTable();

        DataTable DtCateoryList = new DataTable();
        DataTable DtCate_Printer = new DataTable();
        DataTable DTInvInfo = new DataTable();
        DataTable DTCheckBarcode = new DataTable();
        DataTable DTQry = new DataTable();

        // string BranchAlias = "saffron1";
        string BranchAlias = string.Empty;
        string PSett;
        string CatValue;
        string Grp1Value;
        string Grp2Value;
        string Grp3Value;
        string Grp4Value;
        string Grp5Value;
        string Grp1_Maxid = string.Empty;
        string Grp2_Maxid = string.Empty;
        string Grp3_Maxid = string.Empty;
        string Grp4_Maxid = string.Empty;
        string Grp5_Maxid = string.Empty;


        // Category Variable :  

        string RCategoryNo = string.Empty;
        string RGroup1Name = string.Empty;
        string RGroup_Descp = string.Empty;
        string RActive_Stauts = string.Empty;
        string RUpdate_Status = string.Empty;
        string RBranch_Update = string.Empty;
        string RFlag1_Tax = string.Empty;
        string RFlag2_Printer = string.Empty;
        string RFireIndex = string.Empty;
        string RGroup1ID = string.Empty;


        //Inventory variables for editing purpose
        string GInventoryID = string.Empty;
        string GBarcode = string.Empty;
        string GInventoryName = string.Empty;
        string GDescription = string.Empty;
        string GCategoryID = string.Empty;
        string GClass = string.Empty;
        string GUnit = string.Empty;
        string GPrice = string.Empty;
        string GPrice2 = string.Empty;
        string GPrice3 = string.Empty;
        string GPrice4 = string.Empty;
        string GDateCreated = string.Empty;
        string GGroup1 = string.Empty;
        string GGroup2 = string.Empty;
        string GGroup3 = string.Empty;
        string GGroup4 = string.Empty;
        string GGroup5 = string.Empty;
        string GFlag1 = string.Empty;
        string GFlag2 = string.Empty;
        string GReorderLevel = string.Empty;
        string GMaximumLevel = string.Empty;
        string GSafetyLevel = string.Empty;

        string PortalTypeId = string.Empty;
        string ActiveCallvalue = string.Empty;
        string Datapath = string.Empty;
        string cd_BranchAlias = string.Empty;
        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_RetailDashboard = string.Empty;
        string L_SummarySales = string.Empty;
        string L_ItemSales = string.Empty;
        string L_TaxAnalysis = string.Empty;
        string L_TopSale = string.Empty;
        string L_MothlySales = string.Empty;
        string L_HourlySales = string.Empty;
        string L_GroupSale = string.Empty;
        string L_Usercreation = string.Empty;
        string L_UserRights = string.Empty;
        string L_Stock = string.Empty;
        string L_Inventory = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;

        //for InventoryAdjust Process
        string AdjInvCost = string.Empty;

        //for check barcode function
        string sChkBarcode = string.Empty;

        DataTable AdjDt = new DataTable();
        DataTable FAdjDt = new DataTable();
        string sSno = string.Empty;
        int iSno = 0;
        string sCmd = string.Empty;
        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;

        // Added On 02-12-2021
        string ReadHQ = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            btnUpdate1.Visible = false;

            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            PID = "13";    // This is for Inventory  PageAccess

            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {

                    LoadBranchesOnID();
                    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)
                {

                    LoadBranchesOnID();
                }
                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 = Cmb_BranchName;

                if (!IsPostBack)
                {

                    ActiveCall();

                }


            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {

                    LoadBranchesOnID();
                    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 = "&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_ItemSales"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else if (Session["Write_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }

                else
                {

                    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)
                            {

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

                                // Loading Parts : 
                                if (!IsPostBack)
                                {


                                    string GroupName = string.Empty;
                                    if (cmbGroupMain.SelectedIndex == 1)
                                    {
                                        GroupName = "group1";
                                        // LoadGroupNameList(BranchAlias, GroupName);
                                        hidGroupName.Value = GroupName;

                                    }
                                    else if (cmbGroupMain.SelectedIndex == 2)
                                    {
                                        GroupName = "group2";
                                        // LoadGroupNameList(BranchAlias, GroupName);
                                        hidGroupName.Value = GroupName;
                                    }

                                    else if (cmbGroupMain.SelectedIndex == 3)
                                    {
                                        GroupName = "group3";
                                        //   LoadGroupNameList(BranchAlias, GroupName);
                                        hidGroupName.Value = GroupName;
                                    }

                                    else if (cmbGroupMain.SelectedIndex == 4)
                                    {
                                        GroupName = "group4";
                                        //   LoadGroupNameList(BranchAlias, GroupName);
                                        hidGroupName.Value = GroupName;
                                    }


                                    else if (cmbGroupMain.SelectedIndex == 5)
                                    {
                                        GroupName = "group5";
                                        // LoadGroupNameList(BranchAlias, GroupName);
                                        hidGroupName.Value = GroupName;
                                    }




                                }

                            }

                        }


                    }

                }

            }
            else
            {

            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {

            // XSS Attack Prevention 


            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalGroupList();", true);
            if (cmbBranches.Visible == false)
            {

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

            }
            else
            {
                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;
                }
            }


            if (cmbSearchGroup.SelectedIndex == 1)
            {

                string sGroupName = "group1";
                LoadCommonGroup(BranchAlias, sGroupName, txtSearchGroupName.Text.ToString().Trim());


            }
            else if (cmbSearchGroup.SelectedIndex == 2)
            {
                string sGroupName = "group2";

                LoadCommonGroup(BranchAlias, sGroupName, txtSearchGroupName.Text.ToString().Trim());

            }
            else if (cmbSearchGroup.SelectedIndex == 3)
            {
                string sGroupName = "group3";

                LoadCommonGroup(BranchAlias, sGroupName, txtSearchGroupName.Text.ToString().Trim());
            }

            else if (cmbSearchGroup.SelectedIndex == 4)
            {
                string sGroupName = "group4";
                LoadCommonGroup(BranchAlias, sGroupName, txtSearchGroupName.Text.ToString().Trim());
            }

            else if (cmbSearchGroup.SelectedIndex == 5)
            {
                string sGroupName = "group5";
                LoadCommonGroup(BranchAlias, sGroupName, txtSearchGroupName.Text.ToString().Trim());
            }

        }

        protected void btnUpdate1_Click(object sender, EventArgs e)
        {

            if (cmbBranches.Visible == false)
            {

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

            }
            else
            {
                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;
                }
            }


            string mGroupName = string.Empty;
            if (cmbSearchGroup.SelectedIndex == 1)
            {
                mGroupName = "group1";
                // cmbGroupMain.SelectedIndex = 1;

            }
            else if (cmbSearchGroup.SelectedIndex == 2)
            {
                mGroupName = "group2";
                //cmbGroupMain.SelectedIndex = 2;
            }
            else if (cmbSearchGroup.SelectedIndex == 3)
            {
                mGroupName = "group3";
                //cmbGroupMain.SelectedIndex = 3;
            }

            else if (cmbSearchGroup.SelectedIndex == 4)
            {
                mGroupName = "group4";
                //cmbGroupMain.SelectedIndex = 4;
            }
            else if (cmbSearchGroup.SelectedIndex == 5)
            {
                mGroupName = "group5";
                //cmbGroupMain.SelectedIndex = 5;
            }




            #region  GroupMaster UPDATE

            string UptQRY = "UPDATE  {0}.{1} SET GroupName=@GroupName,Description=@Description where GroupID=@GroupID";


            string command = string.Format(UptQRY, BranchAlias, mGroupName);

            MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@GroupName",txtGroupName.Text.ToString().Trim()),
                     new MySqlParameter("@Description",txtDescription.Text),
                     new MySqlParameter("@GroupID",hidGroup1.Value),
                    };


            K = ObjMain.ExecuteQuery(command, parameters);
            
            #endregion

            if (K > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Group  Name Updated ! ');location.href='GroupMaster.aspx'", true);

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Group  Name NOT Updated ! ');location.href='GroupMaster.aspx'", true);
            }

        }


        protected void cmbGroupMain_SelectedIndexChanged(object sender, EventArgs e)
        {


            if (cmbBranches.Visible == false)
            {

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

            }
            else
            {
                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;
                }
            }



            string GroupName = string.Empty;
            if (cmbGroupMain.SelectedIndex == 1)
            {
                GroupName = "group1";
                // LoadGroupNameList(BranchAlias, GroupName);
                hidGroupName.Value = GroupName;

            }
            else if (cmbGroupMain.SelectedIndex == 2)
            {
                GroupName = "group2";
                //   LoadGroupNameList(BranchAlias, GroupName);
                hidGroupName.Value = GroupName;
            }

            else if (cmbGroupMain.SelectedIndex == 3)
            {
                GroupName = "group3";
                //  LoadGroupNameList(BranchAlias, GroupName);
                hidGroupName.Value = GroupName;
            }

            else if (cmbGroupMain.SelectedIndex == 4)
            {
                GroupName = "group4";
                //LoadGroupNameList(BranchAlias, GroupName);
                hidGroupName.Value = GroupName;
            }


            else if (cmbGroupMain.SelectedIndex == 5)
            {
                GroupName = "group5";
                //   LoadGroupNameList(BranchAlias, GroupName);
                hidGroupName.Value = GroupName;
            }

            txtGroupName.Text = "";
            txtDescription.Text = "";


        }


        protected void grdGroupnew_SelectedIndexChanged(object sender, EventArgs e)
        {
            //XSS Attack Prevention 

            if (cmbBranches.Visible == false)
            {

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

            }
            else
            {
                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;
                }
            }




            btnSave1.Visible = false;
            btnSave1.Enabled = false;
            btnSave1.CssClass = "btn btn-primary";
            btnUpdate1.Visible = true;
            btnUpdate1.Enabled = true;
            btnUpdate1.CssClass = "btn btn-primary";

            RGroup1ID = (grdGroupnew.SelectedRow.FindControl("lblGroupID") as Label).Text;

            string mGroupName = string.Empty;

            if (cmbSearchGroup.SelectedIndex == 1)
            {
                mGroupName = "group1";
                cmbGroupMain.SelectedIndex = 1;

            }
            else if (cmbSearchGroup.SelectedIndex == 2)
            {
                mGroupName = "group2";
                cmbGroupMain.SelectedIndex = 2;
            }
            else if (cmbSearchGroup.SelectedIndex == 3)
            {
                mGroupName = "group3";
                cmbGroupMain.SelectedIndex = 3;
            }

            else if (cmbSearchGroup.SelectedIndex == 4)
            {
                mGroupName = "group4";
                cmbGroupMain.SelectedIndex = 4;
            }
            else if (cmbSearchGroup.SelectedIndex == 5)
            {
                mGroupName = "group5";
                cmbGroupMain.SelectedIndex = 5;
            }


            DTCommonGroup = ObjSel.ReadGrouPCommonByID(BranchAlias, mGroupName, RGroup1ID);
            RGroup1Name = DTCommonGroup.Rows[0]["GroupName"].ToString();
            RGroup_Descp = DTCommonGroup.Rows[0]["Description"].ToString();
            txtGroupName.Text =RGroup1Name;
            txtDescription.Text = RGroup_Descp;
            hidGroup1.Value = RGroup1ID;


            Session["RGroup1Name"] = RGroup1Name;
            Session["RGroup_Descp"] = RGroup_Descp;



        }


        protected void grdGroupnew_RowCommand(object sender, GridViewCommandEventArgs e)
        {


            if (cmbBranches.Visible == false)
            {

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

            }
            else
            {
                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;
                }
            }
            string mGroupName = string.Empty;
            if (cmbSearchGroup.SelectedIndex == 1)
            {
                mGroupName = "group1";
                // cmbGroupMain.SelectedIndex = 1;

            }
            else if (cmbSearchGroup.SelectedIndex == 2)
            {
                mGroupName = "group2";
                //cmbGroupMain.SelectedIndex = 2;
            }
            else if (cmbSearchGroup.SelectedIndex == 3)
            {
                mGroupName = "group3";
                //cmbGroupMain.SelectedIndex = 3;
            }

            else if (cmbSearchGroup.SelectedIndex == 4)
            {
                mGroupName = "group4";
                //cmbGroupMain.SelectedIndex = 4;
            }
            else if (cmbSearchGroup.SelectedIndex == 5)
            {
                mGroupName = "group5";
                //cmbGroupMain.SelectedIndex = 5;
            }

           string Name = e.CommandName;
            if (Name == "Delete")
            {

                if (mGroupName != "")
                {
                    int rowIndex = Convert.ToInt32(e.CommandArgument);
                    string DEL_Qry = "Delete from  {0}.{1}  where  groupID=" + rowIndex + " ; ";
                    string Command = string.Format(DEL_Qry, BranchAlias, mGroupName);

                    K = ObjCloudMain.ExecuteNonQuery(Command);
                    Log.Info("GroupName Deleted"+"DB:"+ BranchAlias);
                    Log.Info(Command);
                    // ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Group  Name Deleted  ! ');", true);


                   if (mGroupName!="")
                    {
                      LoadCommonGroupAll(BranchAlias, mGroupName);
                    }


                    
                    //Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "ShowModalGroupList()", true);
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "ShowModalGroupList()", true);
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Group  Name Deleted  ! ');", true);
                    

                }


            }


        }




       




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

                #region  Default Branch Validation:Either HQ or First Branch Based On IsHQ Ini in PMS 
                string _hq_query = "select IsHQ from  portaldb.companymaster where cm_id=" + Session["CM_ID"] + " ;";
                string _Is_HQ_Enabled = Convert.ToString(ObjMain.ExecuteScalar(_hq_query));
                if (_Is_HQ_Enabled == "1")
                {
                    ActiveCallvalue = ObjSel.GetHQ(Session["Branch_HQ"].ToString());

                }
                else if (_Is_HQ_Enabled == "0")
                {
                    ActiveCallvalue = ObjSel.GetFirstBranch7(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
                }

                #endregion

            }



            cd_BranchAlias = ActiveCallvalue;

            // HQ Validation For Loading Branch Name : Dropdown  Added Karthik  On 02-12-21 

            ReadHQ = ObjUserBL.GetBranchFullNameByBranchName(Session["Branch_HQ"].ToString(), cd_BranchAlias);

            if (ReadHQ == "HQ")
            {
                cmbBranches.Items.FindByText(ReadHQ).Selected = true;
            }
            else
            {
                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_Inventory = DtLicense.Rows[0]["INVENTORY"].ToString();
                Session["L_Inventory"] = L_Inventory;


            }
            if ((Session["L_Inventory"] == null) || Session["L_Inventory"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                if (cmbBranches.SelectedItem.Text == "HQ")
                {

                    //No Calling Function 

                }
                else
                {
                    Response.Redirect("DeniedPage.aspx");
                }

                
            }
            else if (Session["Write_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }

            else
            {

                // btnExcel.Enabled = true;

                BranchAlias = Cmb_BranchName;


             


            }

        }


        public void LoadBranchesOnID()
        {
            DT = ObjUserBL.GetBranchIDList(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            StringBuilder StrBObj = new StringBuilder();

            for (int i = 0; i < DT.Rows.Count; i++)
            {
                DataRow dr = DT.Rows[i];
                RBranchid = dr["Branchid"].ToString();
                if (StrBObj.Length != 0)
                {

                    RBranchid = "," + RBranchid;
                    StrBObj.Append("  " + RBranchid + "    ");
                }
                else
                {
                    string _get_HQ = ObjSel.GetHQ_Status(Session["CM_ID"].ToString());
                    if (_get_HQ == "0")
                    {

                        //UPDATEBRANCH(Cmb_BranchName);
                        //Response.Redirect(Request.RawUrl);
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in ( " + Branchid + " ");


                    }
                    else if (_get_HQ == "1")
                    {
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in (1 , " + Branchid + " ");


                    }


                }


            }
            StrBObj.Append(")");
            Dt2 = ObjCloudMain.GetData_DT(StrBObj.ToString());

            if (Dt2.Rows.Count > 0)
            {
                cmbBranches.DataSource = Dt2;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }

        }

        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()
        {

            DtNormalUser = ObjUserBL.GetBranchOnSuperAdminWithHQ8(Session["Branch_HQ"].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");
            }

        }




        /// <summary>
        ///  This Group 1 Master 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave1_Click(object sender, EventArgs e)
        {
            // XSS Attack Prevention
            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {
                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;
                }
            }

           

            if (cmbGroupMain.SelectedIndex == 0)
            {

                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Select Group Name  ');", true);

            }
            else
            {

                if (hidGroupName.Value != "")
                {

                    string RdQuery = "select GroupName from {0}.{1} where  GroupName  like  CONCAT('%', @GroupName, '%')  ";

                    string commandA = string.Format(RdQuery, BranchAlias, hidGroupName.Value);
                    MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@GroupName",txtGroupName.Text),

                   };
                    Grp1Value = Convert.ToString(ObjMain.NewExecuteScalar(commandA, parameters));

                    //Grp1Value = Convert.ToString(Cmd.ExecuteScalar());  Existing Code 
                    Grp1_Maxid = ObjSel.GetMax_CommonGroupid(BranchAlias, hidGroupName.Value);

                    if (hidGroupName.Value != "")
                    {
                        // Prevents SQL Injections 
                        // Parameterized Approach 

                        string Active = "-1";
                        string Updated = "0";
                        string BranchUpdated = "0";
                        string Ins_Query = "Insert into {0}." + hidGroupName.Value + "(GroupID,GroupName,Description,DateCreated,Active,Updated,BranchUpdated) " +
                            "values" +
                            "(@GroupID,@GroupName,@Description,@DateCreated,@Active,@Updated,@BranchUpdated)";

                        string commandB = string.Format(Ins_Query, BranchAlias);
                        MySqlParameter[] parameters1 =
                         {
                         new MySqlParameter("@GroupID",Grp1_Maxid),
                         new MySqlParameter("@GroupName",txtGroupName.Text.ToString().Trim()),
                         new MySqlParameter("@Description",txtDescription.Text),
                         new MySqlParameter("@DateCreated",Curr_DateOnly),
                         new MySqlParameter("@Active",Active),
                         new MySqlParameter("@Updated",Updated),
                         new MySqlParameter("@BranchUpdated",BranchUpdated),
                        };

                        K = ObjMain.ExecuteQuery(commandB, parameters1);

                        //  K = ObjCloudMain.ExecuteNonQuery(Ins_Query);    Exiting Code 
                        txtGroupName.Text = "";
                        txtDescription.Text = "";
                        //LoadGroupNameList(Cmb_BranchName, hidGroupName.Value);
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Group  Name Created ');", true);

                    }
                    else
                    {

                    }


                }


            }




        }



       

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            grdGroupnew.DataSource = null;
            grdGroupnew.DataBind();
            cmbSearchGroup.SelectedIndex = 0;

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("Inventory.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;
                }

                if (cmbBranches.SelectedIndex == 1)
                {

                    BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                    Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                    UPDATEBRANCH(Cmb_BranchName);
                }
                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 )
                    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);
                }



                if (DtLicense.Rows.Count > 0)
                {
                    L_MaxUserCnt = DtLicense.Rows[0]["UserCnt"].ToString();
                    L_RetailDashboard = DtLicense.Rows[0]["RETAILDASHBOARD"].ToString();
                    L_SummarySales = DtLicense.Rows[0]["SUMMARYSALES"].ToString();
                    L_ItemSales = DtLicense.Rows[0]["ITEMSALE"].ToString();
                    L_TaxAnalysis = DtLicense.Rows[0]["TAXANALYSIS"].ToString();
                    L_TopSale = DtLicense.Rows[0]["TOPSALE"].ToString();
                    L_MothlySales = DtLicense.Rows[0]["MONTHLYSALE"].ToString();
                    L_HourlySales = DtLicense.Rows[0]["HOURLYSALE"].ToString();
                    L_GroupSale = DtLicense.Rows[0]["GROUPSALE"].ToString();
                    L_Usercreation = DtLicense.Rows[0]["USERCREATION"].ToString();
                    L_UserRights = DtLicense.Rows[0]["USERRIGHTS"].ToString();
                    L_Stock = DtLicense.Rows[0]["STOCK"].ToString();
                    L_Inventory = DtLicense.Rows[0]["INVENTORY"].ToString();
                    // Create Session for License Variables 
                    Session["L_MaxUserCnt"] = L_MaxUserCnt;
                    Session["L_RetailDashboard"] = L_RetailDashboard;
                    Session["L_SummarySales"] = L_SummarySales;
                    Session["L_ItemSales"] = L_ItemSales;
                    Session["L_TaxAnalysis"] = L_TaxAnalysis;
                    Session["L_TopSale"] = L_TopSale;
                    Session["L_MothlySales"] = L_MothlySales;
                    Session["L_HourlySales"] = L_HourlySales;
                    Session["L_GroupSale"] = L_GroupSale;
                    Session["L_Usercreation"] = L_Usercreation;
                    Session["L_UserRights"] = L_UserRights;
                    Session["L_Stock"] = L_Stock;
                    Session["L_Inventory"] = L_Inventory;
                }

                if ((Session["L_Inventory"] == null) || Session["L_Inventory"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    if (cmbBranches.SelectedItem.Text == "HQ")
                    {

                        BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                        Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                        UPDATEBRANCH(Cmb_BranchName);
                        BranchAlias = Cmb_BranchName;
                    }
                    else
                    {
                      
                     Response.Redirect("DeniedPage.aspx");
                       
                    }


                }
                else if (Session["Write_Acess"].ToString() == "N")
                {
                    btnSave1.Enabled = false;
                    btnUpdate1.Enabled = false;
                }

                else
                {
                    // btnExcel.Enabled = true;
                    btnSave1.Enabled = true;
                    btnUpdate1.Enabled = true;
                    BranchAlias = Cmb_BranchName;

                    string GroupName = string.Empty;

                   



                }
            }
            UPDATEBRANCH(BranchAlias);
        }

        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");

            }

        }


       



        public void LoadCommonGroup(string BranchAlias, string GRPNAME, string SearchTxt)
        {
            DT = ObjSel.GetCommonListNew(BranchAlias, GRPNAME, SearchTxt);
            grdGroupnew.DataSource = DT;
            grdGroupnew.DataBind();

        }
        public void LoadCommonGroupAll(string BranchAlias, string GRPNAME)
        {
            DT = ObjSel.GetCommonListAll(BranchAlias, GRPNAME);
            grdGroupnew.DataSource = DT;
            grdGroupnew.DataBind();

        }


        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            txtDescription.Text = "";
            txtGroupName.Text = "";

            Response.Redirect(HttpContext.Current.Request.Url.ToString(), true);


        }

        protected void grdGroupnew_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }
    }
}