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 System.Data;
using System.Web.UI.DataVisualization.Charting;
using System.Web.Services;
using Newtonsoft.Json;

namespace SUNWEB
{
    public partial class StockReceiving : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();

        //MYSQLDB ObjMain = new MYSQLDB();
        MYSQLCLOUD ObjMainCloud = new MYSQLCLOUD();

        decimal totaltaxableamount = 0;
        decimal Gtotaltaxableamount = 0;

        decimal totaltaxamount = 0;
        decimal Gtotaltaxamount = 0;
        // User Variables 

        string UserId = string.Empty;
        string UserName = string.Empty;
        string PortalTypeId = string.Empty;
        string cd_Id = string.Empty;
        string Datapath = string.Empty;
        
        string IsMultiBranch = string.Empty;
        string IsSuperAdmin = string.Empty;

        // License Variables ..
        string PID = string.Empty;
        string Page_Acess = string.Empty;
        string Read_Acess = string.Empty;
        string Write_Acess = string.Empty;
        string Isdowld_Acess = string.Empty;

        // New Variables 
               
        string ActiveCallvalue = string.Empty;
        string cd_BranchAlias = 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_Stock = string.Empty;
      
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;
        string HQ = string.Empty;
        string Cm_id = string.Empty;

        string BranchAlias = string.Empty;
        string ISHQ = string.Empty;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        string sFromDate = string.Empty;
        string sToDate = string.Empty;
        // Added On 02-12-2021
        string ReadHQ = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "12"; //  This is for Stock Concept Pages
            if (!IsPostBack)
            {

                //txtFromDt.Text = Curr_DateOnly;
                //txtToDt.Text = Curr_DateOnly;
                //LoadData();
                txtStartDt.Text = Curr_DateOnly;
                txtEndDt.Text = Curr_DateOnly;
                sFromDate = txtStartDt.Text;
                sToDate = txtEndDt.Text;
            }
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            //MonthstartDt = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);

            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }


            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                    
                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();
                    }


                    Useridvalue = Session["UserId"].ToString();
                    QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='{0}' where Userid={1} ";
                    string command = string.Format(QueryCurr_Select, cd_BranchAlias, Useridvalue);
                    S = ObjMain.ExecuteNonQuery(command);

                
                }

              

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


                cd_BranchAlias = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);
                
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {

                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                    
                    //ActiveCall();
                }

                cd_BranchAlias = cmbBranches.SelectedItem.Text;
            
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;
                lblBranchAliasName.Text = "Welcome" + "&nbsp;&nbsp;" + Session["Branch_HQ"].ToString() + "&nbsp; !";
                cd_BranchAlias = Session["Branch_HQ"].ToString();
                Datapath = Session["DataPath"].ToString();
                PortalTypeId = Session["PortalTypeId"].ToString();
                PID = "12"; //  This is for ItemSale 

                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_Stock"].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 (cmbBranches.Visible == false)
                        {
                            LoadData(Session["Branch_HQ"].ToString(),sFromDate,sToDate);
                        }
                        else
                        {
                            LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text), sFromDate, sToDate);
                        }
                    }
                    else
                    {
                        LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text), sFromDate, sToDate);
                    }


                }

            }
            else
            {

            }

            
        }


        public void UPDATEBRANCH(string ActiveCallvalue)
        {
            if (!string.IsNullOrEmpty(Session["UserId"] as string))
            {
                Useridvalue = Session["UserId"].ToString();
                QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='{0}' where Userid={1} ";
                string command = string.Format(QueryCurr_Select, ActiveCallvalue, Useridvalue);
                S = ObjMain.ExecuteNonQuery(command);
            }
            else
            {
                Response.Redirect("Login.aspx");

            }

        }


        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,branchprefix FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in ( " + Branchid + " ");


                    }
                    else if (_get_HQ == "1")
                    {
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath,branchprefix 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");

                var json = JsonConvert.SerializeObject(Dt2.AsEnumerable().Select(r => r.ItemArray));
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", " loadbranches(" + json + "); ", true);
            }

        }
        public void LoadBranchName4SuperAdmin()
        {
            //DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdmin(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            //if (DtSuperAdmin.Rows.Count > 0)
            //{
            //    cmbBranches.DataSource = DtSuperAdmin;
            //    cmbBranches.DataTextField = "BranchName";
            //    cmbBranches.DataValueField = "Branchid";
            //    cmbBranches.DataBind();
            //    //cmbBranches.Items.Insert(0, "Select Branch");
            //}

            DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdminWithHQ8(Session["Branch_HQ"].ToString(), Session["CM_ID"].ToString());
            if (DtSuperAdmin.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtSuperAdmin;
                cmbBranches.DataTextField = "BranchFullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                //cmbBranches.Items.Insert(0, "Select Branch");
            }
        }

        public void 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 LoadData(string sBranch,string sFromDate,string sToDate)
        {
            // Prevention SQL Injection 
            // Prevention XSS 
            // Parameterized Approach 

            //Label sFromBranch = (row.FindControl("lblInventoryID") as Label;
            //string sCmd = "Select TransferNo,B.BranchName as BranchName,TransferDate,if(ConfirmFlag=0,'Not Confirm','Confirmed') as Status from " +
            //                " " + sBranch + ".receivestock A " +
            //                " Join " + sBranch + ".branches B " +
            //                " on A.FromBranchID=B.BranchID where BranchName <> '" + sBranch + "' and senddatetime <> '';";

            //string sCmd = "Select TransferNo,B.BranchName as BranchName,'" + sBranch  + "' as ToBranch,TransferDate,if(ConfirmFlag=0,'Not Confirm','Confirmed') as Status from  " + sBranch + ".receivestock A  " +
            //            "Join " + sBranch  + ".branches B  on A.FromBranchID=B.BranchID;";

            string sCmd = "Select TransferNo,B.BranchFullname as BranchName,@BranchName as BranchFullName,'{0}' as ToBranch,TransferDate,if(ConfirmFlag=0,'Not Confirm','Confirmed') as Status from  {0}.receivestock A  " +
                        " Join {0}.branches B  on A.FromBranchID=B.BranchID where Transferdate between @D1 and @D2 ;";

            string command = string.Format(sCmd, sBranch);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@D1",sFromDate),
                     new MySqlParameter("@D2",sToDate),
                     new MySqlParameter("@BranchName",cmbBranches.SelectedItem.Text),
                    };


            DT = ObjMainCloud.NewGetData_DT(command, parameters);
            grdStockReceiving.DataSource = DT;
            grdStockReceiving.DataBind();


        }

        protected void btnApplySearch_Click(object sender, EventArgs e)
        {  
            Curr_BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);
            cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);
            sFromDate = txtStartDt.Text.Trim();
            sToDate = txtEndDt.Text.Trim();
            LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text), Microsoft.Security.Application.Encoder.HtmlEncode(sFromDate), Microsoft.Security.Application.Encoder.HtmlEncode(sToDate));
        }

        protected void grdStockReceiving_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

            grdStockReceiving.PageIndex = e.NewPageIndex;
            LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text), Microsoft.Security.Application.Encoder.HtmlEncode(sFromDate), Microsoft.Security.Application.Encoder.HtmlEncode(sToDate));

        }


        public void ActiveCall()
        {
            //string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
            //ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
            //cd_BranchAlias = ActiveCallvalue;
            //Curr_BranchFullName = ObjUserBL.GetBranchCurr_BranchVal(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cd_BranchAlias);
            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.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
                }

                #endregion


            }

            #region  HQ Validation in ActiveCall Function : Starts 
            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);

            }

            #endregion

            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_Stock = DtLicense.Rows[0]["STOCK"].ToString();
               
                Session["L_Stock"] = L_Stock;
               

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

                    LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text), Microsoft.Security.Application.Encoder.HtmlEncode(sFromDate), Microsoft.Security.Application.Encoder.HtmlEncode(sToDate));
                }
                else
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                
            }

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

            else
            {
                // Load Part : 

                LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text), Microsoft.Security.Application.Encoder.HtmlEncode(sFromDate), Microsoft.Security.Application.Encoder.HtmlEncode(sToDate));
            
            }

        }

        protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var status = (Label)e.Row.FindControl("lblTranferStatus");
                if (status.Text == "Confirmed")
                {
                    e.Row.Cells[5].ForeColor = System.Drawing.Color.Green;
                }               
            }
        }
        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {


            //Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
            sFromDate = txtStartDt.Text.Trim();
            sToDate = txtEndDt.Text.Trim();
            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);
            LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text), sFromDate, sToDate);
            //cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
            //Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);
            cd_BranchAlias = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
            UPDATEBRANCH(cd_BranchAlias);


            //if (cmbBranches.SelectedIndex == 0)
            //{
            //    //Response.Redirect("StockReceiving.aspx");
            //    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 )

            //    LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text));
            //    // Update the BranchName at Every Dropdown Selection..
            //    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 )

            //    LoadData(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.SelectedItem.Text));
            //    // Update the BranchName at Every Dropdown Selection..
            //    UPDATEBRANCH(Cmb_BranchName);




            //}

        }

        protected void grdStockReceiving_SelectedIndexChanged(object sender, EventArgs e)
        {

          


        }


        [WebMethod]
        public static string GET_ReceiveStockList(string db)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.GET_ReceiveStockList(bearertoken, db);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }
    }
}