using CLS_BL;
using CLS_DL;
using CLS_PL;
using MySql.Data;
using MySql.Data.MySqlClient;
using Org.BouncyCastle.Asn1.Ocsp;
using SUNWEB;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using static SUNWEB.InteractiveDashboard;

namespace SUNWEB
{
    public partial class Login : System.Web.UI.Page
    {
        BL_ErrorLog ObjLog = new BL_ErrorLog();
        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;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtEnduer = new DataTable();
        DataTable DtLicense = new DataTable();
        // 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;
        // License Variables 
        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 L_UpdateBranch = string.Empty;
        string L_Condiment = string.Empty;
        string L_StockMovement = string.Empty;
        string L_JournalReport = string.Empty;
        string L_RAPO = string.Empty;
        string L_RetailPayment = string.Empty;
        string L_DetailStockReprt = string.Empty;
        string L_StockCollector = string.Empty;
        string L_CustomerMaster = string.Empty;
        string L_MeberHistory = string.Empty;
        string L_PointsHistory = string.Empty;
        string L_InventoryPromotions = string.Empty;
        string L_OnlineKDS = string.Empty;
        string L_CondimentAdd = string.Empty;
        string L_CondimentGroup = string.Empty;
        string L_Modifier = string.Empty;
        string L_CategoryCustomize = string.Empty;
        string L_LandingCustomize = string.Empty;
        string L_OutletClosure = string.Empty;
        string L_TakeAwaysetting = string.Empty;
        string L_SpecialDiscount = string.Empty;
        string L_PriceCaptionSetting = string.Empty;
        string L_IorderlaSetting = string.Empty;
        string L_LayoutSetting = string.Empty;
        string L_UpsellingSetting = string.Empty;
        string L_ConsumerBehaviourAnalysis = string.Empty;
        string L_ReorderReport = string.Empty;
        string L_TimeInOutReport = string.Empty;
        string L_PromoCode = string.Empty;
        string L_CRMCustomerMaster = string.Empty;
        string L_CRMMembershipcampaign = string.Empty;
        string L_OperatingHours = string.Empty;
        string L_TimedurationReport = string.Empty;
        string L_InventoryPackage = string.Empty;
        string L_compaignAdjustment = string.Empty;
        string L_MenuGroupCreation = string.Empty;
        string L_ZeroIntegration = string.Empty;
        string L_SupplierWisecostandCollection = string.Empty;
        string L_InteractiveDashboard = string.Empty;
        string L_Zoho = string.Empty;
        string L_OneTimePromocode = string.Empty;
        string L_InventoryBatchAdjust=string.Empty;
        string L_PDPAContends = string.Empty;
        string L_BannerSchedule = string.Empty;
        string L_MobileInventoryBatchAdjust = string.Empty;
        string L_PriceSwitch = string.Empty;
        string L_Sales = string.Empty;
        string L_StkMovement = string.Empty;
        string L_SalesInvoice = string.Empty;
        string L_SalesInvoiceList = string.Empty;
        string L_KioskLandingpage = string.Empty;
        string L_Kioskbanner = string.Empty;

        string L_WebStockSetting = string.Empty;
        string L_QuickBook = string.Empty;
        string L_SummarySales_light = string.Empty;
        string L_ItemSales_light = string.Empty;
        string L_TaxAnalysis_light = string.Empty;



        string CM_ID;
        string CD_ID;
        string Fistbranch = string.Empty;
        string ActiveUserid = string.Empty;
        //Glabal 
        string ChkExit = string.Empty;
        string UPTTIME = string.Empty;
        string TimeDiff = string.Empty;
        string OHrVaue = string.Empty;
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        string ChkUPTDT = string.Empty;

        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        int S = 0;
        string _2fa = string.Empty;
        string _googleuser = string.Empty;
        private object window;
        string key = string.Empty;
        string value = string.Empty;
        string _default_branch = string.Empty;
        string _branchname = string.Empty;
        string _Fistbranch_multibranch = string.Empty;
        DataTable DtChkvalues = new DataTable();

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public void ReadUsers()
        {
            string script = string.Empty;
            try
            {

                DT = ObjUserBL.ReadUsersForIsMultiBranch(txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString().Trim());
                Dt2 = ObjUserBL.ReadUsersForIsSuperAdmin(txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString().Trim());
                DtEnduer = ObjUserBL.ReadUsers4Enduser(txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString().Trim());
                if (DT.Rows.Count > 0 || Dt2.Rows.Count > 0)
                {

                    if (DT.Rows.Count > 0)
                    {
                        UserId = DT.Rows[0]["Userid"].ToString();
                        UserName = DT.Rows[0]["UserName"].ToString();
                        PortalTypeId = DT.Rows[0]["PortalTypeId"].ToString();
                        cd_Id = DT.Rows[0]["cd_id"].ToString();
                        Datapath = DT.Rows[0]["Datapath"].ToString();
                        cd_BranchAlias = DT.Rows[0]["cd_BranchAlias"].ToString();

                        string IsMultiBranch = DT.Rows[0]["IsMultiBranch"].ToString();
                        Session["IsMultiBranch"] = IsMultiBranch;
                        string IsSuperAdmin = DT.Rows[0]["IssuperAdmin"].ToString();
                        Session["IsSuperAdmin"] = IsSuperAdmin;

                    }
                    else
                    {
                        UserId = Dt2.Rows[0]["Userid"].ToString();
                        UserName = Dt2.Rows[0]["UserName"].ToString();
                        PortalTypeId = Dt2.Rows[0]["PortalTypeId"].ToString();
                        cd_Id = Dt2.Rows[0]["cd_id"].ToString();
                        Datapath = Dt2.Rows[0]["Datapath"].ToString();
                        cd_BranchAlias = Dt2.Rows[0]["cd_BranchAlias"].ToString();

                        string IsMultiBranch = Dt2.Rows[0]["IsMultiBranch"].ToString();
                        Session["IsMultiBranch"] = IsMultiBranch;

                        string IsSuperAdmin = Dt2.Rows[0]["IssuperAdmin"].ToString();
                        Session["IsSuperAdmin"] = IsSuperAdmin;
                    }


                    CM_ID = ObjSel.GETcmid(cd_Id);
                    //Fistbranch = ObjSel.GETBrachAlias(CM_ID);


                    Session["Branch_HQ"] = cd_BranchAlias;
                    Session["DataPath"] = Datapath;
                    Session["UserId"] = UserId;
                    Session["Cd_Id"] = cd_Id;
                    Session["PortalTypeId"] = PortalTypeId;
                    Session["CM_ID"] = CM_ID;
                    Fistbranch = ObjSel.GetFirstBranch8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
                    Session["Fistbranch"] = Fistbranch;
                    Session["UserName"] = txtUserName.Text;
                    Session["Password"] = txtPassword.Text;


                    // Added Nov24
                    _default_branch = ObjMain.ExecuteScalar("select DefaultBranch from portaldb.companymaster where cm_id = " + Session["CM_ID"] + ";");
                    //Session["_default_branch"] = _default_branch;





                    // New  Code: Nov-18
                    // Add Active Userid : Approach 

                    UPTTIME = ObjMain.ExecuteScalar("select UPTTIME  from  portaldb.usermaster where  userid=" + UserId + " And Active=1 ");

                    TimeDiff = ObjMain.ExecuteScalar("SELECT   TIMESTAMPDIFF(MINUTE,T.UPTTIME,'" + Convert.ToDateTime(Curr_Date).ToString("yyyy-MM-dd HH:mm:ss") + "') AS DIF from portaldb.usermaster  AS T  WHERE  T.userid=" + UserId + " ");
                    ActiveUserid = ObjMain.ExecuteScalar("SELECT Active from portaldb.usermaster  where userid=" + UserId + " ");

                    if (Convert.ToBoolean(ActiveUserid) == true && Convert.ToInt32(TimeDiff) >= 2)
                    {

                        ActiveReverseUPT(UserId);
                    }

                    ActiveUserid = ObjMain.ExecuteScalar("SELECT Active from portaldb.usermaster  where userid=" + UserId + " ");
                    if (Convert.ToBoolean(ActiveUserid) == true)
                    {
                        Page page = HttpContext.Current.Handler as Page;
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Either You are not Logout Properly or Session Exist ! Try After 2 Mins ');location.href='Login.aspx'", true);

                    }
                    else if (Convert.ToBoolean(ActiveUserid) == false)
                    {
                       
                        _2fa = Return2FA(Session["CM_ID"].ToString());

                        _googleuser= ReturnGoogleAuthUser(Session["UserId"].ToString());

                        if (_2fa.Equals("0"))
                        {
                            ActiveUserUPT(UserId);
                            UPDATEBRANCH();
                            key = "Initialbranch";
                            value = Server.HtmlEncode(Fistbranch);
                            script = $"localStorage.setItem('{key}', '{value}');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);
                            // Added Nov24
                            _default_branch = ObjMain.ExecuteScalar("select DefaultBranch from portaldb.companymaster where cm_id = " + Session["CM_ID"] + ";");
                            // Session["_default_branch"] = _default_branch;

                            _branchname = ObjMain.ExecuteScalar("select cd_branchAlias as branch from companydetails where cm_id =" + Session["CM_ID"].ToString() + "  and cd_branchid = " + _default_branch + ";");

                            _Fistbranch_multibranch = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());


                            if (_branchname == _Fistbranch_multibranch)
                            {
                                UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                Response.Redirect("Dashboard.aspx", false);
                            }
                            else
                            {
                                DtChkvalues = ObjMain.GetData_DT("SELECT  BranchName FROM " + Session["Branch_HQ"].ToString() + ".branches  as b inner join    "
                                    + " portaldb.Companydetails as C on C.cd_branchid=b.Branchid     inner join portaldb.subcompmaster as S  "
                                    + " on b.Branchid=S.cd_Branchid    "
                                    + " where S.userid=" + Session["UserId"].ToString() + " and Multi_Access<>'N' and c.cm_id=" + Session["CM_ID"].ToString() + " AND C.Status='A' order by b.Branchid   ; ");

                                bool exists = DtChkvalues.AsEnumerable()
                                 .Any(row => row["BranchName"].ToString() == _branchname);

                                if (exists)
                                {
                                    UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                    Response.Redirect("Dashboard.aspx", false);
                                }
                                else
                                {

                                    if (_default_branch == "1")
                                    {
                                        UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                        Response.Redirect("Dashboard.aspx", false);
                                    }
                                    else
                                    {
                                        UPDATEBRANCH_BY_DEFAULT_BRANCH(_Fistbranch_multibranch);
                                        Response.Redirect("Dashboard.aspx", false);
                                    }


                                }
                            }


                          

                        }
                        else if (_2fa.Equals("1") && _googleuser.Equals("1"))
                        {
                            ActiveUserUPT(UserId);
                            UPDATEBRANCH();
                            Response.Redirect("ShowgoogleAuth.aspx", false);
                        }
                        else
                        {   

                            key = "Initialbranch";
                            value = Server.HtmlEncode(Fistbranch);
                            script = $"localStorage.setItem('{key}', '{value}');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);

                            // Added Nov24
                            _default_branch = ObjMain.ExecuteScalar("select DefaultBranch from portaldb.companymaster where cm_id = " + Session["CM_ID"] + ";");
                            // Session["_default_branch"] = _default_branch;
                            _branchname = ObjMain.ExecuteScalar("select cd_branchAlias as branch from companydetails where cm_id ="+ Session["CM_ID"].ToString() + "  and cd_branchid = "+ _default_branch + ";");
                            _Fistbranch_multibranch = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());


                            if (_branchname == _Fistbranch_multibranch)
                            {
                                UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                Response.Redirect("Dashboard.aspx", false);
                            }
                            else
                            {
                                DtChkvalues = ObjMain.GetData_DT("SELECT  BranchName FROM " + Session["Branch_HQ"].ToString() + ".branches  as b inner join    "
                                    + " portaldb.Companydetails as C on C.cd_branchid=b.Branchid     inner join portaldb.subcompmaster as S  "
                                    + " on b.Branchid=S.cd_Branchid    "
                                    + " where S.userid="+ Session["UserId"].ToString() + " and Multi_Access<>'N' and c.cm_id="+ Session["CM_ID"].ToString() + " AND C.Status='A' order by b.Branchid   ; ");

                                bool exists = DtChkvalues.AsEnumerable()
                                 .Any(row => row["BranchName"].ToString() == _branchname);

                                if (exists)
                                {
                                    UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                    Response.Redirect("Dashboard.aspx", false);
                                }
                                else
                                {

                                    if (_default_branch == "1")
                                    {
                                        UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                        Response.Redirect("Dashboard.aspx", false);
                                    }
                                    else
                                    {
                                        UPDATEBRANCH_BY_DEFAULT_BRANCH(_Fistbranch_multibranch);
                                        Response.Redirect("Dashboard.aspx", false);
                                    }

                                    
                                }
                             
                            }
                        }



                    }
                    else
                    {

                    }



                }
                else if (DtEnduer.Rows.Count > 0)
                {

                    string UserId = DtEnduer.Rows[0]["Userid"].ToString();
                    string UserName = DtEnduer.Rows[0]["UserName"].ToString();
                    string PortalTypeId = DtEnduer.Rows[0]["PortalTypeId"].ToString();
                    string cd_Id = DtEnduer.Rows[0]["cd_id"].ToString();
                    string Datapath = DtEnduer.Rows[0]["Datapath"].ToString();
                    string cd_BranchAlias = DtEnduer.Rows[0]["cd_BranchAlias"].ToString();

                    CM_ID = ObjSel.GETcmid(cd_Id);
                    //Fistbranch = ObjSel.GETBrachAlias(CM_ID);                                 // Modidfied On 30-10-2020
                    Fistbranch = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());

                    Session["Fistbranch"] = Fistbranch;
                    Session["Branch_HQ"] = cd_BranchAlias;
                    Session["DataPath"] = Datapath;
                    Session["UserId"] = UserId;
                    Session["Cd_Id"] = cd_Id;
                    Session["PortalTypeId"] = PortalTypeId;

                    string IsMultiBranch = DtEnduer.Rows[0]["IsMultiBranch"].ToString();
                    Session["IsMultiBranch"] = IsMultiBranch;
                    string IsSuperAdmin = DtEnduer.Rows[0]["IssuperAdmin"].ToString();
                    Session["IsSuperAdmin"] = IsSuperAdmin;
                    Session["UserName"] = txtUserName.Text;
                    Session["Password"] = txtPassword.Text;
                    Session["CM_ID"] = CM_ID;

                    string key = "Initialbranch";
                    string value = Server.HtmlEncode(Fistbranch);
                    script = $"localStorage.setItem('{key}', '{value}');";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);




                    // Chk with License Detatils 
                    DtLicense = ObjUserBL.GetLicenseDetails(PortalTypeId);

                    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();
                        L_Condiment = DtLicense.Rows[0]["CONDIMENTREPORT"].ToString();

                        L_UpdateBranch = DtLicense.Rows[0]["UPDATEBRANCH"].ToString();
                        L_StockMovement = DtLicense.Rows[0]["STOCKMOVEMENT"].ToString();
                        L_JournalReport = DtLicense.Rows[0]["JOURNALREPORT"].ToString();
                        L_RAPO = DtLicense.Rows[0]["RAPOREPORT"].ToString();
                        L_RetailPayment = DtLicense.Rows[0]["RETAILPAYMENT"].ToString();
                        L_DetailStockReprt = DtLicense.Rows[0]["DETAILSTOCKREPORT"].ToString();
                        L_StockCollector = DtLicense.Rows[0]["STOCKCOLLECTOR"].ToString();
                        L_CustomerMaster = DtLicense.Rows[0]["CUSTOMERMASTER"].ToString();
                        L_MeberHistory = DtLicense.Rows[0]["MEMBERHISTORY"].ToString();
                        L_PointsHistory = DtLicense.Rows[0]["POINTSHISTORY"].ToString();
                        L_InventoryPromotions = DtLicense.Rows[0]["INVENTORYPROMOTIONS"].ToString();
                        L_OnlineKDS = DtLicense.Rows[0]["ONLINEKDS"].ToString();
                        L_CondimentAdd = DtLicense.Rows[0]["CONDIMENT"].ToString();
                        L_CondimentGroup = DtLicense.Rows[0]["CONDIMENTGROUP"].ToString();
                        L_Modifier = DtLicense.Rows[0]["MODIFIER"].ToString();
                        L_CategoryCustomize = DtLicense.Rows[0]["CATEGORYCUSTOMIZE"].ToString();
                        L_LandingCustomize = DtLicense.Rows[0]["LANDINGCUSTOMIZE"].ToString();
                        L_OutletClosure = DtLicense.Rows[0]["OUTLETCLOSURE"].ToString();
                        L_TakeAwaysetting = DtLicense.Rows[0]["TAKEAWAYSETTING"].ToString();
                        L_SpecialDiscount = DtLicense.Rows[0]["SPECIALDISCOUNT"].ToString();
                        L_PriceCaptionSetting = DtLicense.Rows[0]["PRICECAPTIONSETTING"].ToString();
                        L_IorderlaSetting = DtLicense.Rows[0]["IORDERLAPRODUCTTIMING"].ToString();
                        L_LayoutSetting = DtLicense.Rows[0]["LAYOUTSETTING"].ToString();
                        L_UpsellingSetting = DtLicense.Rows[0]["UPSELLINGSETTING"].ToString();
                        L_ConsumerBehaviourAnalysis = DtLicense.Rows[0]["CONSUMERBEHAVIOURANALYSIS"].ToString();
                        L_ReorderReport = DtLicense.Rows[0]["REORDERREPORT"].ToString();
                        L_TimeInOutReport = DtLicense.Rows[0]["TIMEINOUTREPORT"].ToString();
                        L_PromoCode = DtLicense.Rows[0]["PROMOCODE"].ToString();
                        L_CRMCustomerMaster = DtLicense.Rows[0]["CRMCUSTOMERMASTER"].ToString();
                        L_CRMMembershipcampaign = DtLicense.Rows[0]["CRMMEMBERSHIPCAMPAIGN"].ToString();
                        L_OperatingHours = DtLicense.Rows[0]["OPERATINGHOURS"].ToString();

                        L_TimedurationReport = DtLicense.Rows[0]["TIMEDURATIONREPORT"].ToString();
                        L_InventoryPackage = DtLicense.Rows[0]["INVENTORYPACKAGE"].ToString();
                        L_compaignAdjustment = DtLicense.Rows[0]["CAMPAIGNADJUSTMENT"].ToString();
                        L_MenuGroupCreation = DtLicense.Rows[0]["MENUGROUPCREATION"].ToString();
                        L_ZeroIntegration = DtLicense.Rows[0]["ZEROINTEGRATION"].ToString();
                        L_SupplierWisecostandCollection = DtLicense.Rows[0]["SUPPLIERWISECOSTANDCOLLECTIONREPORT"].ToString();
                        L_InteractiveDashboard = DtLicense.Rows[0]["INTERACTIVEDASHBOARD"].ToString();
                        L_Zoho = DtLicense.Rows[0]["ZOHO"].ToString();
                        L_OneTimePromocode = DtLicense.Rows[0]["ONETIMEPROMOCODE"].ToString();
                        L_InventoryBatchAdjust= DtLicense.Rows[0]["INVENTORYBATCHADJUST"].ToString();
                        L_PDPAContends= DtLicense.Rows[0]["PDPACONTEND"].ToString();

                        L_BannerSchedule = DtLicense.Rows[0]["BANNERTIMESCHEDULE"].ToString();
                        L_MobileInventoryBatchAdjust= DtLicense.Rows[0]["MOBILEINVENTORYBATCHADJUST"].ToString();
                        L_PriceSwitch= DtLicense.Rows[0]["PRICESWITCH"].ToString();
                        L_Sales= DtLicense.Rows[0]["SALES"].ToString();
                        L_StkMovement = DtLicense.Rows[0]["STKMOVEMENT"].ToString();
                        L_SalesInvoice = DtLicense.Rows[0]["SALESINVOICE"].ToString();
                        L_SalesInvoiceList= DtLicense.Rows[0]["SALESINVOICELIST"].ToString();
                        L_KioskLandingpage = DtLicense.Rows[0]["KIOSKLANDINGPAGE"].ToString();
                        L_Kioskbanner= DtLicense.Rows[0]["KIOSKBANNER"].ToString();
                        L_WebStockSetting = DtLicense.Rows[0]["WEBSTOCKPRESET"].ToString();
                        L_QuickBook= DtLicense.Rows[0]["QUICKBOOK"].ToString();

                        L_SummarySales_light = DtLicense.Rows[0]["SUMMARYREPORT_LIGHT"].ToString();
                        L_ItemSales_light = DtLicense.Rows[0]["TAXANALYSIS_LIGHT"].ToString();
                        L_TaxAnalysis_light = DtLicense.Rows[0]["PRODUCTSALE_LIGHT"].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;
                        Session["L_Condiment"] = L_Condiment;
                        Session["L_UpdateBranch"] = L_UpdateBranch;
                        Session["L_StockMovement"] = L_StockMovement;
                        Session["L_JournalReport"] = L_JournalReport;
                        Session["L_RAPO"] = L_RAPO;
                        Session["L_RetailPayment"] = L_RetailPayment;
                        Session["L_DetailStockReprt"] = L_DetailStockReprt;
                        Session["L_StockCollector"] = L_StockCollector;
                        Session["L_CustomerMaster"] = L_CustomerMaster;
                        Session["L_MeberHistory"] = L_MeberHistory;
                        Session["L_PointsHistory"] = L_PointsHistory;
                        Session["L_InventoryPromotions"] = L_InventoryPromotions;
                        Session["L_OnlineKDS"] = L_OnlineKDS;
                        Session["L_CondimentAdd"] = L_CondimentAdd;
                        Session["L_CondimentGroup"] = L_CondimentGroup;
                        Session["L_Modifier"] = L_Modifier;
                        Session["L_CategoryCustomize"] = L_CategoryCustomize;
                        Session["L_LandingCustomize"] = L_LandingCustomize;
                        Session["L_OutletClosure"] = L_OutletClosure;
                        Session["L_TakeAwaysetting"] = L_TakeAwaysetting;
                        Session["L_SpecialDiscount"] = L_SpecialDiscount;
                        Session["L_PriceCaptionSetting"] = L_PriceCaptionSetting;
                        Session["L_IorderlaSetting"] = L_IorderlaSetting;
                        Session["L_LayoutSetting"] = L_IorderlaSetting;
                        Session["L_UpsellingSetting"] = L_UpsellingSetting;
                        Session["L_ConsumerBehaviourAnalysis"] = L_ConsumerBehaviourAnalysis;
                        Session["L_ReorderReport"] = L_ReorderReport;
                        Session["L_TimeInOutReport"] = L_TimeInOutReport;
                        Session["L_PromoCode"] = L_PromoCode;
                        Session["L_CRMCustomerMaster"] = L_CRMCustomerMaster;
                        Session["L_CRMMembershipcampaign"] = L_CRMMembershipcampaign;
                        Session["L_OperatingHours"] = L_OperatingHours;
                        Session["L_TimedurationReport"] = L_TimedurationReport;
                        Session["L_InventoryPackage"] = L_InventoryPackage;
                        Session["L_compaignAdjustment"] = L_compaignAdjustment;
                        Session["L_MenuGroupCreation"] = L_MenuGroupCreation;

                        Session["L_ZeroIntegration"] = L_ZeroIntegration;
                        Session["L_SupplierWisecostandCollection"] = L_SupplierWisecostandCollection;
                        Session["L_InteractiveDashboard"] = L_InteractiveDashboard;
                        Session["L_Zoho"] = L_Zoho;
                        Session["L_OneTimePromocode"] = L_OneTimePromocode;
                        Session["L_InventoryBatchAdjust"] = L_InventoryBatchAdjust;
                        Session["L_PDPAContends"] = L_PDPAContends;
                        Session["L_BannerSchedule"] = L_BannerSchedule;
                        Session["L_MobileInventoryBatchAdjust"] = L_MobileInventoryBatchAdjust;
                        Session["L_PriceSwitch"] = L_PriceSwitch;
                        Session["L_Sales"] = L_Sales;
                        Session["L_StkMovement"] = L_StkMovement;
                        Session["L_SalesInvoice"] = L_SalesInvoice;
                        Session["L_SalesInvoiceList"] = L_SalesInvoiceList;
                        Session["L_KioskLandingpage"] = L_KioskLandingpage;
                        Session["L_Kioskbanner"] = L_Kioskbanner;
                        Session["L_WebStockSetting"] = L_WebStockSetting;
                        Session["L_QuickBook"] = L_QuickBook;

                        Session["L_SummarySales_light"] = L_SummarySales_light;
                        Session["L_ItemSales_light"] = L_ItemSales_light;
                        Session["L_TaxAnalysis_light"] = L_TaxAnalysis_light;
                    }
                    UPTTIME = ObjMain.ExecuteScalar("select UPTTIME  from  portaldb.usermaster where  userid=" + UserId + " And Active=1 ");
                    TimeDiff = ObjMain.ExecuteScalar("SELECT   TIMESTAMPDIFF(MINUTE,T.UPTTIME,'" + Convert.ToDateTime(Curr_Date).ToString("yyyy-MM-dd HH:mm:ss") + "') AS DIF from portaldb.usermaster  AS T  WHERE  T.userid=" + UserId + " ");
                    ActiveUserid = ObjMain.ExecuteScalar("SELECT Active from portaldb.usermaster  where userid=" + UserId + " ");
                    if (Convert.ToBoolean(ActiveUserid) == true && Convert.ToInt32(TimeDiff) >= 2)
                    {

                        ActiveReverseUPT(UserId);
                    }

                    ActiveUserid = ObjMain.ExecuteScalar("SELECT Active from portaldb.usermaster  where userid=" + UserId + " ");
                    if (Convert.ToBoolean(ActiveUserid) == true)
                    {
                        Page page = HttpContext.Current.Handler as Page;
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Either You are not Logout Properly ! Session Exist ! Try After 2 Mins');location.href='Login.aspx'", true);
                    }
                    else if (Convert.ToBoolean(ActiveUserid) == false)
                    {

                     
                        _2fa = Return2FA(Session["CM_ID"].ToString());

                        _googleuser = ReturnGoogleAuthUser(Session["UserId"].ToString());

                        if (_2fa.Equals("0"))
                        {
                            UPDATEBRANCH();


                            key = "Initialbranch";
                            value = Server.HtmlEncode(Fistbranch);
                            script = $"localStorage.setItem('{key}', '{value}');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);

                            // Added Nov24
                            _default_branch = ObjMain.ExecuteScalar("select DefaultBranch from portaldb.companymaster where cm_id = " + Session["CM_ID"] + ";");
                            // Session["_default_branch"] = _default_branch;
                            _branchname = ObjMain.ExecuteScalar("select cd_branchAlias as branch from companydetails where cm_id =" + Session["CM_ID"].ToString() + "  and cd_branchid = " + _default_branch + ";");
                            _Fistbranch_multibranch = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
                            _Fistbranch_multibranch = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());


                            if (_branchname == _Fistbranch_multibranch)
                            {
                                UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                Response.Redirect("Dashboard.aspx", false);
                            }
                            else
                            {
                                DtChkvalues = ObjMain.GetData_DT("SELECT  BranchName FROM " + Session["Branch_HQ"].ToString() + ".branches  as b inner join    "
                                   + " portaldb.Companydetails as C on C.cd_branchid=b.Branchid     inner join portaldb.subcompmaster as S  "
                                   + " on b.Branchid=S.cd_Branchid    "
                                   + " where S.userid=" + Session["UserId"].ToString() + " and Multi_Access<>'N' and c.cm_id=" + Session["CM_ID"].ToString() + " AND C.Status='A' order by b.Branchid   ; ");

                                bool exists = DtChkvalues.AsEnumerable()
                                 .Any(row => row["BranchName"].ToString() == _branchname);

                                if (exists)
                                {
                                    UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                    Response.Redirect("Dashboard.aspx", false);
                                }
                                else
                                {

                                    if (_default_branch == "1")
                                    {
                                        UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                        Response.Redirect("Dashboard.aspx", false);
                                    }
                                    else
                                    {
                                        UPDATEBRANCH_BY_DEFAULT_BRANCH(_Fistbranch_multibranch);
                                        Response.Redirect("Dashboard.aspx", false);
                                    }


                                }
                            }

                        }
                        else if (_2fa.Equals("1") && _googleuser.Equals("1"))
                        {
                            UPDATEBRANCH();
                            Response.Redirect("ShowgoogleAuth.aspx", false);
                        } 
                        else
                        {
                            key = "Initialbranch";
                            value = Server.HtmlEncode(Fistbranch);
                            script = $"localStorage.setItem('{key}', '{value}');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);

                            // Added Nov24
                            _default_branch = ObjMain.ExecuteScalar("select DefaultBranch from portaldb.companymaster where cm_id = " + Session["CM_ID"] + ";");
                            // Session["_default_branch"] = _default_branch;
                            _branchname = ObjMain.ExecuteScalar("select cd_branchAlias as branch from companydetails where cm_id =" + Session["CM_ID"].ToString() + "  and cd_branchid = " + _default_branch + ";");
                            _Fistbranch_multibranch = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());


                            if (_branchname == _Fistbranch_multibranch)
                            {
                                UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                Response.Redirect("Dashboard.aspx", false);
                            }
                            else
                            {
                                DtChkvalues = ObjMain.GetData_DT("SELECT  BranchName FROM " + Session["Branch_HQ"].ToString() + ".branches  as b inner join    "
                                    + " portaldb.Companydetails as C on C.cd_branchid=b.Branchid     inner join portaldb.subcompmaster as S  "
                                    + " on b.Branchid=S.cd_Branchid    "
                                    + " where S.userid=" + Session["UserId"].ToString() + " and Multi_Access<>'N' and c.cm_id=" + Session["CM_ID"].ToString() + " AND C.Status='A' order by b.Branchid   ; ");

                                bool exists = DtChkvalues.AsEnumerable()
                                 .Any(row => row["BranchName"].ToString() == _branchname);

                                if (exists)
                                {
                                    UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                    Response.Redirect("Dashboard.aspx", false);
                                }
                                else
                                {

                                    if (_default_branch == "1")
                                    {
                                        UPDATEBRANCH_BY_DEFAULT_BRANCH(_branchname);
                                        Response.Redirect("Dashboard.aspx", false);
                                    }
                                    else
                                    {
                                        UPDATEBRANCH_BY_DEFAULT_BRANCH(_Fistbranch_multibranch);
                                        Response.Redirect("Dashboard.aspx", false);
                                    }


                                }
                            }
                        }
                    }

                }
                else
                {
                    Page page = HttpContext.Current.Handler as Page;
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Either Credential Wrong or Invalid User !! ');location.href='Login.aspx'", true);
                }

            }

            catch (Exception ex)
            {
                ObjLog.Write(ex);
            }

        }


        public void ReadUsers_Light()
        {
            string script = string.Empty;
            try
            {

                DT = ObjUserBL.ReadUsersForIsMultiBranch(txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString().Trim());
                Dt2 = ObjUserBL.ReadUsersForIsSuperAdmin(txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString().Trim());
                DtEnduer = ObjUserBL.ReadUsers4Enduser(txtUserName.Text.ToString().Trim(), txtPassword.Text.ToString().Trim());
                if (DT.Rows.Count > 0 || Dt2.Rows.Count > 0)
                {

                    if (DT.Rows.Count > 0)
                    {
                        UserId = DT.Rows[0]["Userid"].ToString();
                        UserName = DT.Rows[0]["UserName"].ToString();
                        PortalTypeId = DT.Rows[0]["PortalTypeId"].ToString();
                        cd_Id = DT.Rows[0]["cd_id"].ToString();
                        Datapath = DT.Rows[0]["Datapath"].ToString();
                        cd_BranchAlias = DT.Rows[0]["cd_BranchAlias"].ToString();

                        string IsMultiBranch = DT.Rows[0]["IsMultiBranch"].ToString();
                        Session["IsMultiBranch"] = IsMultiBranch;
                        string IsSuperAdmin = DT.Rows[0]["IssuperAdmin"].ToString();
                        Session["IsSuperAdmin"] = IsSuperAdmin;

                    }
                    else
                    {
                        UserId = Dt2.Rows[0]["Userid"].ToString();
                        UserName = Dt2.Rows[0]["UserName"].ToString();
                        PortalTypeId = Dt2.Rows[0]["PortalTypeId"].ToString();
                        cd_Id = Dt2.Rows[0]["cd_id"].ToString();
                        Datapath = Dt2.Rows[0]["Datapath"].ToString();
                        cd_BranchAlias = Dt2.Rows[0]["cd_BranchAlias"].ToString();

                        string IsMultiBranch = Dt2.Rows[0]["IsMultiBranch"].ToString();
                        Session["IsMultiBranch"] = IsMultiBranch;

                        string IsSuperAdmin = Dt2.Rows[0]["IssuperAdmin"].ToString();
                        Session["IsSuperAdmin"] = IsSuperAdmin;
                    }


                    CM_ID = ObjSel.GETcmid(cd_Id);
                    //Fistbranch = ObjSel.GETBrachAlias(CM_ID);


                    Session["Branch_HQ"] = cd_BranchAlias;
                    Session["DataPath"] = Datapath;
                    Session["UserId"] = UserId;
                    Session["Cd_Id"] = cd_Id;
                    Session["PortalTypeId"] = PortalTypeId;
                    Session["CM_ID"] = CM_ID;
                    Fistbranch = ObjSel.GetFirstBranch8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
                    Session["Fistbranch"] = Fistbranch;
                    Session["UserName"] = txtUserName.Text;
                    Session["Password"] = txtPassword.Text;










                    // New  Code: Nov-18
                    // Add Active Userid : Approach 

                    UPTTIME = ObjMain.ExecuteScalar("select UPTTIME  from  portaldb.usermaster where  userid=" + UserId + " And Active=1 ");

                    TimeDiff = ObjMain.ExecuteScalar("SELECT   TIMESTAMPDIFF(MINUTE,T.UPTTIME,'" + Convert.ToDateTime(Curr_Date).ToString("yyyy-MM-dd HH:mm:ss") + "') AS DIF from portaldb.usermaster  AS T  WHERE  T.userid=" + UserId + " ");
                    ActiveUserid = ObjMain.ExecuteScalar("SELECT Active from portaldb.usermaster  where userid=" + UserId + " ");

                    if (Convert.ToBoolean(ActiveUserid) == true && Convert.ToInt32(TimeDiff) >= 2)
                    {

                        ActiveReverseUPT(UserId);
                    }

                    ActiveUserid = ObjMain.ExecuteScalar("SELECT Active from portaldb.usermaster  where userid=" + UserId + " ");
                    if (Convert.ToBoolean(ActiveUserid) == true)
                    {
                        Page page = HttpContext.Current.Handler as Page;
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Either You are not Logout Properly or Session Exist ! Try After 2 Mins ');location.href='Login.aspx'", true);

                    }
                    else if (Convert.ToBoolean(ActiveUserid) == false)
                    {

                        _2fa = Return2FA(Session["CM_ID"].ToString());

                        _googleuser = ReturnGoogleAuthUser(Session["UserId"].ToString());

                        if (_2fa.Equals("0"))
                        {
                            ActiveUserUPT(UserId);
                            UPDATEBRANCH();



                            key = "Initialbranch";
                            value = Server.HtmlEncode(Fistbranch);
                            script = $"localStorage.setItem('{key}', '{value}');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);

                            Response.Redirect("SummaryReport_light.aspx", false);

                        }
                        else if (_2fa.Equals("1") && _googleuser.Equals("1"))
                        {
                            ActiveUserUPT(UserId);
                            UPDATEBRANCH();

                            Response.Redirect("ShowgoogleAuth.aspx", false);
                        }
                        else
                        {

                            //string branch = Server.HtmlEncode(Fistbranch);
                            //script = $@"
                            //localStorage.setItem('Initialbranch', '{branch}');
                            //window.location.href = 'Dashboard.aspx';";
                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "SetAndRedirect", script, true);


                            key = "Initialbranch";
                            value = Server.HtmlEncode(Fistbranch);
                            script = $"localStorage.setItem('{key}', '{value}');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);


                            Response.Redirect("SummaryReport_light.aspx", false);
                        }



                    }
                    else
                    {

                    }



                }
                else if (DtEnduer.Rows.Count > 0)
                {

                    string UserId = DtEnduer.Rows[0]["Userid"].ToString();
                    string UserName = DtEnduer.Rows[0]["UserName"].ToString();
                    string PortalTypeId = DtEnduer.Rows[0]["PortalTypeId"].ToString();
                    string cd_Id = DtEnduer.Rows[0]["cd_id"].ToString();
                    string Datapath = DtEnduer.Rows[0]["Datapath"].ToString();
                    string cd_BranchAlias = DtEnduer.Rows[0]["cd_BranchAlias"].ToString();

                    CM_ID = ObjSel.GETcmid(cd_Id);
                    //Fistbranch = ObjSel.GETBrachAlias(CM_ID);                                 // Modidfied On 30-10-2020
                    Fistbranch = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());

                    Session["Fistbranch"] = Fistbranch;
                    Session["Branch_HQ"] = cd_BranchAlias;
                    Session["DataPath"] = Datapath;
                    Session["UserId"] = UserId;
                    Session["Cd_Id"] = cd_Id;
                    Session["PortalTypeId"] = PortalTypeId;

                    string IsMultiBranch = DtEnduer.Rows[0]["IsMultiBranch"].ToString();
                    Session["IsMultiBranch"] = IsMultiBranch;
                    string IsSuperAdmin = DtEnduer.Rows[0]["IssuperAdmin"].ToString();
                    Session["IsSuperAdmin"] = IsSuperAdmin;
                    Session["UserName"] = txtUserName.Text;
                    Session["Password"] = txtPassword.Text;
                    Session["CM_ID"] = CM_ID;

                    string key = "Initialbranch";
                    string value = Server.HtmlEncode(Fistbranch);
                    script = $"localStorage.setItem('{key}', '{value}');";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);




                    // Chk with License Detatils 
                    DtLicense = ObjUserBL.GetLicenseDetails(PortalTypeId);

                    if (DtLicense.Rows.Count > 0)
                    {


                        L_SummarySales_light = DtLicense.Rows[0]["SUMMARYSALES"].ToString();
                        L_ItemSales_light = DtLicense.Rows[0]["ITEMSALE"].ToString();
                        L_TaxAnalysis_light = DtLicense.Rows[0]["TAXANALYSIS"].ToString();


                        // Create Session for License Variables 


                        Session["L_SummarySales"] = L_SummarySales_light;
                        Session["L_ItemSales"] = L_ItemSales_light;
                        Session["L_TaxAnalysis"] = L_TaxAnalysis_light;




                    }
                    UPTTIME = ObjMain.ExecuteScalar("select UPTTIME  from  portaldb.usermaster where  userid=" + UserId + " And Active=1 ");
                    TimeDiff = ObjMain.ExecuteScalar("SELECT   TIMESTAMPDIFF(MINUTE,T.UPTTIME,'" + Convert.ToDateTime(Curr_Date).ToString("yyyy-MM-dd HH:mm:ss") + "') AS DIF from portaldb.usermaster  AS T  WHERE  T.userid=" + UserId + " ");
                    ActiveUserid = ObjMain.ExecuteScalar("SELECT Active from portaldb.usermaster  where userid=" + UserId + " ");
                    if (Convert.ToBoolean(ActiveUserid) == true && Convert.ToInt32(TimeDiff) >= 2)
                    {

                        ActiveReverseUPT(UserId);
                    }

                    ActiveUserid = ObjMain.ExecuteScalar("SELECT Active from portaldb.usermaster  where userid=" + UserId + " ");
                    if (Convert.ToBoolean(ActiveUserid) == true)
                    {
                        Page page = HttpContext.Current.Handler as Page;
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Either You are not Logout Properly ! Session Exist ! Try After 2 Mins');location.href='Login.aspx'", true);
                    }
                    else if (Convert.ToBoolean(ActiveUserid) == false)
                    {


                        _2fa = Return2FA(Session["CM_ID"].ToString());

                        _googleuser = ReturnGoogleAuthUser(Session["UserId"].ToString());

                        if (_2fa.Equals("0"))
                        {
                            UPDATEBRANCH();


                            key = "Initialbranch";
                            value = Server.HtmlEncode(Fistbranch);
                            script = $"localStorage.setItem('{key}', '{value}');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);

                            //string branch = Server.HtmlEncode(Fistbranch);
                            //script = $@"
                            //localStorage.setItem('Initialbranch', '{branch}');
                            //window.location.href = 'Dashboard.aspx';";
                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "SetAndRedirect", script, true);



                            Response.Redirect("SummaryReport_light.aspx", false);

                        }
                        else if (_2fa.Equals("1") && _googleuser.Equals("1"))
                        {
                            UPDATEBRANCH();
                            Response.Redirect("ShowgoogleAuth.aspx", false);
                        }
                        else
                        {
                            //string branch = Server.HtmlEncode(Fistbranch);
                            //script = $@"
                            //localStorage.setItem('Initialbranch', '{branch}');
                            //window.location.href = 'Dashboard.aspx';";
                            //ScriptManager.RegisterStartupScript(this, this.GetType(), "SetAndRedirect", script, true);

                            key = "Initialbranch";
                            value = Server.HtmlEncode(Fistbranch);
                            script = $"localStorage.setItem('{key}', '{value}');";
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);
                            Response.Redirect("SummaryReport_light.aspx", false);
                        }


                    }



                }
                else
                {
                    Page page = HttpContext.Current.Handler as Page;
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Either Credential Wrong or Invalid User !! ');location.href='Login.aspx';", true);
                }

            }

            catch (Exception ex)
            {
                ObjLog.Write(ex);
            }

        }






        /// <summary>
        ///  This function for Avoid user : MultiUser access on Same Login credential 
        /// </summary>
        /// <param name="Userid_Active"></param>
        public void ActiveUserUPT(string Userid_Active)
        {
            string Val = "1";
            K = ObjMain.ExecuteNonQuery("UPDATE   portaldb.UserMaster set  Active=" + Val + ",UPTTIME='" + Curr_Date + "'  where userid=" + Userid_Active + "");
            ResetSatus();
        }

        public void ActiveReverseUPT(string Userid_Active)
        {
            string Val = "0";
            K = ObjMain.ExecuteNonQuery("UPDATE   portaldb.UserMaster set  Active=" + Val + " ,UPTTIME='" + Curr_Date + "'  where userid=" + Userid_Active + "");


        }
        protected void btnSingnin_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text != "" && txtPassword.Text != "")
            {
                string _r_userid = ObjMain.ExecuteScalar("select userid  from portaldb.usermaster where UserName='" + txtUserName.Text.Trim().ToString() + "' and Password='" + txtPassword.Text.Trim().ToString() + "' ");

                string _chk_Islight = ObjMain.ExecuteScalar("select IsLightReport  from portaldb.usermaster where userid=" + _r_userid + " ");

                if (_r_userid != "")
                {

                    if (_chk_Islight.Equals("Y"))
                    {
                        ReadUsers_Light();
                    }
                    else
                    {
                        ReadUsers();
                    }
                }
                else
                {
                    //Page page = HttpContext.Current.Handler as Page;
                    //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' User Name is Wrong \n  Password is  Wrong\n Invalid User - Contact Suntoyo ');location.href='Login.aspx'", true);
                    Page page = HttpContext.Current.Handler as Page;

                    ScriptManager.RegisterStartupScript(
                        page,
                        page.GetType(),
                        "err_msg",
                        "alert('User Name is Wrong \\nPassword is Wrong\\nInvalid User - Contact Suntoyo'); window.location.href='Login.aspx';",
                        true
                    );


                }



            }
            else
            {
                Page page = HttpContext.Current.Handler as Page;
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' User Name is Wrong \n  Password is  Wrong\n Invalid User - Contact Suntoyo ');location.href='Login.aspx';", true);
            }

        }

        public void ResetSatus()
        {
            ChkUPTDT = ObjMain.ExecuteScalar("Select   DATE_FORMAT(MonthlyUPTDT,'%Y-%m-%d') as MonthlyUPTDT from Portaldb.UserMaster where MonthlyUPTDT='" + Curr_DateOnly + "' And Userid='" + Session["UserId"].ToString() + "' ");

            if (ChkUPTDT != Curr_DateOnly)
            {
                UPTSatus();
            }


        }

        public void UPTSatus()
        {
            string StatusValue = "N";
            string UPTQuery455 = "UPDATE Portaldb.Usermaster  set MonthlyUPT='" + StatusValue + "'  WHERE Userid=" + Session["UserId"].ToString() + "  ";
            K = ObjMain.ExecuteNonQuery(UPTQuery455);
        }


        public string Return2FA(string cm_id)
        {
            string _2FA = ObjMain.ExecuteScalar("SELECT Is2FA from  Portaldb.companymaster where cm_id=" + cm_id + ";");
            return _2FA;
        }


        public string ReturnGoogleAuthUser (string userid)
        {
            string _googleuser = ObjMain.ExecuteScalar(" select Is2FA from Portaldb.Usermaster where userid=" + userid +";");
            return _googleuser;
        }

        /// <summary>
        ///  This Function Update the First Branch When Login
        /// </summary>
        public void UPDATEBRANCH()
        {
            if (!string.IsNullOrEmpty(Session["UserId"] as string))
            {
                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 == "0")
                {
                    Useridvalue = Session["UserId"].ToString();
                    QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + Session["Fistbranch"].ToString() + "' where Userid=" + Useridvalue + "";
                    S = ObjMain.ExecuteNonQuery(QueryCurr_Select);
                }
                else if (_Is_HQ_Enabled == "1")
                {
                    Useridvalue = Session["UserId"].ToString();
                    QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='' where Userid=" + Useridvalue + "";
                    S = ObjMain.ExecuteNonQuery(QueryCurr_Select);

                }


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



        }


        public void UPDATEBRANCH_BY_DEFAULT_BRANCH(string branch)
        {
            if (!string.IsNullOrEmpty(Session["UserId"] as string))
            {
                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 == "0")
                {
                    Useridvalue = Session["UserId"].ToString();
                    QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + branch + "' where Userid=" + Useridvalue + "";
                    S = ObjMain.ExecuteNonQuery(QueryCurr_Select);
                }
                else if (_Is_HQ_Enabled == "1")
                {
                    Useridvalue = Session["UserId"].ToString();
                    QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + branch + "' where Userid=" + Useridvalue + "";
                    S = ObjMain.ExecuteNonQuery(QueryCurr_Select);

                }


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



        }







    }
}