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

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

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

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        string Rcm_id = string.Empty;
        string R_BrachAlias = string.Empty;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        string BranchAlias = string.Empty;
        string ReadHQ = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "39";    // This is for  Bulk Image Posting  Rights Inherited from Layoutsetting Page
            hidclientName.Value = Session["CM_ID"].ToString();

            if (!IsPostBack)
            {
               
            }
            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();
                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
            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 = "Branch Name" + "&nbsp;" + "-" + "&nbsp;" + Curr_BranchFullName + "&nbsp; ";

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

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

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

                    }
                    #endregion


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

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

                        }


                    }

                }

            }
            else
            {

            }


        }


        public void ActiveCall()
        {
            string _default_branch = ObjMain.ExecuteScalar("select DefaultBranch from portaldb.companymaster where cm_id = " + Session["CM_ID"] + ";");

            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_LayoutSetting = DtLicense.Rows[0]["LAYOUTSETTING"].ToString();
                Session["L_LayoutSetting"] = L_LayoutSetting;
            }
            if ((Session["L_LayoutSetting"] == null) || Session["L_LayoutSetting"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                #region  Validation Between HQ Branch and Normal Branch 
                BranchFullName = cmbBranches.SelectedItem.Text;         // This will Return Branch FullName 
                if (BranchFullName == "HQ")
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    BranchAlias = Cmb_BranchName;

                }
                #endregion


                UPDATEBRANCH(BranchAlias);



            }
            else
            {

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

            }

            UPDATEBRANCH(Cmb_BranchName);

            txtDatabase.Text = Cmb_BranchName;

        }


        public void LoadBranchName()
        {
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtNormalUser;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }


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

            }

        }


       

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

            string Query = "select cd_branchalias from {0}.companydetails where cm_id={1} and cd_branchid =" + cmbBranches.SelectedValue + ";";
            string command = string.Format(Query, "portaldb", Session["CM_ID"].ToString()); 
            R_BrachAlias = ObjMain.ExecuteScalar(command);
            txtDatabase.Text = R_BrachAlias;

            UPDATEBRANCH(R_BrachAlias);


        }


        [WebMethod]

        public static int BulkImageSavingtoS3(string branchalias, string Barcode, string data)
        {
            MYSQLDB objMain = new MYSQLDB();
            string FileID = string.Empty;
            string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            // Get the Full S3Path 
            // var A = "https://suntoyo-aws-s3.s3.ap-southeast-1.amazonaws.com/49/da1/jpg/a01.jpg";
            int S3 = 0;
            int S3_U = 0;

            if (data != "")
            {

                var JsonResult = data;


                Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(JsonResult);

                var V = myDeserializedClass.dbPath;
                //hdnurl.Value = V;  actual path 
                var Result = V.Split('/');
                string S3_http = Result[0];
                string S3_null = Result[1];
                string S3_S3link = Result[2];
                string S3_Companyname = Result[3];
                string S3_Brachname = Result[4];
                string S3_Extention = Result[5];
                string S3_FileName = Result[6];

                string FileName = S3_FileName.ToString().Trim();
                string BucketName = "suntoyo-aws-s3";
                string StoreName = S3_Brachname.ToString().Trim();
                string Url = V.ToString().Trim();
                string Extention = S3_Extention.ToString().Trim();


                string[] a = FileName.Split('.');
                string NewBarcode = a[0];

                string ChkIsExist = string.Empty;
                // Getting the Inventoryid using the Barcode 


                // Prevention SQL Injection   18-10-21
                // Prevention xss 
                // Parameterized Approach 

                string QR1= " Select Inventoryid from  {0}.inventory where Barcode='{1}' ";
                string ReadqueryforInventoryid = string.Format(QR1, branchalias, NewBarcode);
                string Inventoryid = objMain.ExecuteScalar(ReadqueryforInventoryid);

                if (Inventoryid != "")
                {

                    string QR2= " Select Inventoryid from  {0}.filedetails where Inventoryid={1}  ";
                    string ChkIsExistQuery = string.Format(QR2, branchalias, Inventoryid);
                    ChkIsExist = objMain.ExecuteScalar(ChkIsExistQuery);
                    if (ChkIsExist != "")
                    {
                        // Call Update 

                        string QR3= "UPDATE {0}.filedetails SET fileName=@fileName, BucketName=@BucketName,Url=@Url,Extention=@Extention ,ModifiedDate=@ModifiedDate where Inventoryid=@Inventoryid AND CompanyName=@CompanyName AND StoreName=@StoreName; ";
                        string S3_Update = string.Format(QR3, branchalias);
                        MySqlParameter[] parameters =
                        {
                             new MySqlParameter("@fileName",FileName),
                             new MySqlParameter("@BucketName",BucketName),
                             new MySqlParameter("@Url",Url),
                             new MySqlParameter("@Extention",Extention),
                             new MySqlParameter("@ModifiedDate",Curr_Date),
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@CompanyName",S3_Companyname),
                             new MySqlParameter("@StoreName",StoreName),
                             
                        };


                        S3 = objMain.ExecuteQuery(S3_Update, parameters);

                        // Get the fileId 
                        string QR4 = "select fileid from {0}.filedetails  where inventoryid=@inventoryid and companyname=@companyname and StoreName=@StoreName ;";
                        string Command4 = string.Format(QR4, branchalias);
                        MySqlParameter[] parameters4 =
                       {
                            
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@CompanyName",S3_Companyname),
                             new MySqlParameter("@StoreName",StoreName),

                        };


                        FileID = objMain.NewExecuteScalar(Command4, parameters4);
                        // hdnfileid.Value = FileID;

                        // ImagePath Update in Inventory 
                        string QR5= "update  {0}.Inventory set imagepath=@imagepath,fileid=@fileid where Inventoryid=@Inventoryid; ";
                        string S3_InventoryUpdate = string.Format(QR5, branchalias);
                        MySqlParameter[] parameters5 =
                       {
                             new MySqlParameter("@imagepath", V),
                             new MySqlParameter("@fileid",FileID),
                             new MySqlParameter("@Inventoryid",Inventoryid),
                            

                        };

                        S3_U = objMain.ExecuteQuery(S3_InventoryUpdate,parameters5);


                    }
                    else
                    {
                        // Call Insert 
                        string QR6= " INSERT INTO  {0}.filedetails(fileName,BucketName,CompanyName,StoreName, Url, Extention,Inventoryid)" +
                            "values(@fileName,@BucketName,@CompanyName,@StoreName,@Url,@Extention,@Inventoryid)";
                        string S3_Insert = string.Format(QR6, branchalias);

                      MySqlParameter[] parameters6 =
                       {
                             new MySqlParameter("@fileName",FileName),
                             new MySqlParameter("@BucketName",BucketName),
                             new MySqlParameter("@CompanyName",S3_Companyname),
                             new MySqlParameter("@StoreName",StoreName),
                             new MySqlParameter("@Url",Url),
                             new MySqlParameter("@Extention",Extention),
                             new MySqlParameter("@Inventoryid",Inventoryid),
                        };

                        S3 = objMain.ExecuteQuery(S3_Insert,parameters6);
                        // Get the FileId 
                        string QR7 = "select fileid from {0}.filedetails  where inventoryid=@inventoryid and companyname=@companyname and StoreName=@StoreName ;";
                        string command7 = string.Format(QR7, branchalias);
                        MySqlParameter[] parameters7=
                       {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@CompanyName",S3_Companyname.ToString().Trim()),
                             new MySqlParameter("@StoreName",StoreName),
                        };


                        FileID = objMain.NewExecuteScalar(command7, parameters7);

                        string QR8= "update  {0}.Inventory set imagepath=@imagepath,fileid=@fileid where Inventoryid=@Inventoryid; ";
                        string S3_InventoryUpdate = string.Format(QR8, branchalias);
                        MySqlParameter[] parameters8 =
                        {
                             new MySqlParameter("@imagepath", V),
                             new MySqlParameter("@fileid",FileID),
                             new MySqlParameter("@Inventoryid",Inventoryid),


                        };

                        S3_U = objMain.ExecuteQuery(S3_InventoryUpdate, parameters8);
                        // hdnfileid.Value = FileID;
                    }



                }
                else
                {


                }



            }
            else
            {
            }

            return S3;


        }
        public class Root
        {
            public string dbPath { get; set; }
        }







    }
}