using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using MySql.Data.MySqlClient;
using MySql.Data;
using CLS_BL;
using CLS_DL;
using CLS_PL;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.DataVisualization.Charting;

namespace SUNWEB
{
    public partial class PriceCaptionSetting : 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();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        // 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_PriceCaptionSetting = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();

        Int32 iAddPriceCaption = 0;
        Int32 iAddPriceCaptionName = 0;
        Int32 iUpdatePriceCaptionHeader = 0;
        Int32 iUpdatePriceCaptionDetail = 0;

        DataTable dtPriceCaptionDetail = new DataTable();

        string Vw_Chk = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "37";    // This is for Price Caption Page 


            if (!IsPostBack)
            {
                txtStartDt.Text = Curr_DateOnly;
                txtEndDt.Text = Curr_DateOnly;
            }
            MonthstartDt = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();

                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();
                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName();
                    ActiveCall();
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;

                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                lblBranchAliasName.ForeColor = System.Drawing.Color.DodgerBlue;
                lblBranchAliasName.Text = "Branch Name" + "&nbsp;" + "-" + "&nbsp;" + 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_PriceCaptionSetting"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    // lblMsgTotalSelection.Text = "Item Sale  Between" + "&nbsp;&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  and  &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    if (!IsPostBack)
                    {
                        if (Session["Isdowld_Acess"].ToString() == "N")
                        {
                            // btnExcel.Enabled = false;
                            Response.Write(@"<script language='javascript'>alert('No Access To download.')</script>");
                        }
                        else
                        {
                            btnGetReports.Visible = true;

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

            }

            BranchFullName =cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
            Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
            ShowPriceCaptionList(Cmb_BranchName); //LOAD PRICE CAPTION LIST JOHN ADDED ON 13-JAN-2021
        }

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

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

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
                UPDATEBRANCH(ActiveCallvalue);
            }

            cd_BranchAlias = ActiveCallvalue;
            Curr_BranchFullName = ObjUserBL.GetBranchCurr_BranchVal(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cd_BranchAlias);
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
            cmbBranches.Items.FindByText(Curr_BranchFullName).Selected = true;
            Branchidval = ObjUserBL.GetBranchIDbyName(ActiveCallvalue, ActiveCallvalue);
            if (Branchidval != "")
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Session["Fistbranch"].ToString());

            }
            if (DT.Rows.Count > 0)
            {
                Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                Session["Page_Acess"] = Page_Acess;
                Session["Read_Acess"] = Read_Acess;
                Session["Write_Acess"] = Write_Acess;
                Session["Isdowld_Acess"] = Isdowld_Acess;
            }
            Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + 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_PriceCaptionSetting = DtLicense.Rows[0]["PRICECAPTIONSETTING"].ToString();
                Session["L_PriceCaptionSetting"] = L_PriceCaptionSetting;
            }
            if (Session["L_PriceCaptionSetting"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {
                //btnExcel.Enabled = true;
                //lblMsgTotalSelection.Text = "Total Sale Selection Between" + "&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                // BindGridview(ActiveCallvalue, txtStartDt.Text, txtEndDt.Text);
                System.Threading.Thread.Sleep(2000);
            }
        }

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

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

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

            }

        }

        protected void btnGetReports_Click(object sender, EventArgs e)
        {

        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnSavePriceCaption_Click(object sender, EventArgs e)
        {
            BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
            Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
            SavePriceCaption(Cmb_BranchName);           

        }

        private void SavePriceCaption(string sDB)
        {
            string PriceHasValue = "false";

            if (txtPriceCaptionName.Text == "")
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Please add Caption name.')", true);
                return;
            }

            if (txtPriceCaptionID.Text == "")
            {
                if (ObjSel.CheckPriceCaptionHeader(sDB, txtPriceCaptionName.Text.Trim()) != "")
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Price caption name already exist.')", true);
                    return;
                }
            }

            if (txtPrice1Caption1.Text != "")
            {
                PriceHasValue = "true";
            }
            else if (txtPrice1Caption2.Text != "")
            {
                PriceHasValue = "true";
            }
            else if (txtPrice1Caption3.Text != "")
            {
                PriceHasValue = "true";
            }
            else if (txtPrice1Caption4.Text != "")
            {
                PriceHasValue = "true";
            }

            if (PriceHasValue == "true")
            {
                if (txtPriceCaptionID.Text == "")
                {
                    InsertCaption(sDB);
                }
                else
                {
                    UpdatePriceCaption(sDB, txtPriceCaptionID.Text.Trim());
                }

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Please add atleast 1 price caption.')", true);
            }

            ShowPriceCaptionList(sDB);
        }

        private void InsertCaption(string sDB)
        {
            // Prevention SQL Injection 
            // Prevention xss 
            // Parameterized Approaches 

            string sCmd = string.Empty;
            string Cmd = string.Empty;
            int iPriceCaptionHeaderID;
            string sPriceCaptionName = string.Empty;
            //int iAddPriceCa = int.Parse(ObjSel.GenerateCondimentGroupID(sDB));
            sCmd = "Insert into {0}.webpricecaption(PriceCaptionName)values(@PriceCaptionName)";
            string command = string.Format(sCmd, sDB);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@PriceCaptionName",txtPriceCaptionName.Text.Trim()),
                     
                   };
            iAddPriceCaption = ObjMain.ExecuteQuery(command, parameters);
            iPriceCaptionHeaderID = int.Parse(ObjSel.GetPriceCaptionHeaderID(sDB));

            for (int i = 1; i < 5; i++)
            {
                sPriceCaptionName = "";
                switch (i)
                {
                    case 1:
                        //sPriceCaptionName = Microsoft.Security.Application.Encoder.HtmlEncode(txtPrice1Caption1.Text.Trim());
                        sPriceCaptionName = txtPrice1Caption1.Text.Trim();
                        break;
                    case 2:
                        //sPriceCaptionName = Microsoft.Security.Application.Encoder.HtmlEncode(txtPrice1Caption2.Text.Trim());
                        sPriceCaptionName = txtPrice1Caption2.Text.Trim();
                        break;
                    case 3:
                        //sPriceCaptionName = Microsoft.Security.Application.Encoder.HtmlEncode(txtPrice1Caption3.Text.Trim());
                        sPriceCaptionName = txtPrice1Caption3.Text.Trim();
                        break;
                    case 4:
                        //sPriceCaptionName = Microsoft.Security.Application.Encoder.HtmlEncode(txtPrice1Caption4.Text.Trim());
                        sPriceCaptionName = txtPrice1Caption4.Text.Trim();
                        break;
                }

                int iItemID = i + 1;
                Cmd = "Insert into {0}.webpricecaptiondetail(pricecaptionid,priceid,pricecaption)values(@pricecaptionid,@priceid,@pricecaption)";
                string commandA = string.Format(Cmd, sDB);

                MySqlParameter[] parametersA =
                   {
                     new MySqlParameter("@pricecaptionid",iPriceCaptionHeaderID),
                     new MySqlParameter("@priceid",i),
                     new MySqlParameter("@pricecaption",sPriceCaptionName ),

                   };
                iAddPriceCaptionName = ObjMain.ExecuteQuery(commandA, parametersA);
            }
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "success_msg", "alert(' Price Caption Successfully Added. ')", true);
            txtPriceCaptionName.Text = "";
            txtPrice1Caption1.Text = "";
            txtPrice1Caption2.Text = "";
            txtPrice1Caption3.Text = "";
            txtPrice1Caption4.Text = "";
        }

        private void UpdatePriceCaption(string sDB, string ID)
        {
            // Prevention SQL Injection 
            // Prevention xss 
            // Parameterized Approaches 

            string sPriceCaptionName = string.Empty;
            string sCmd = string.Empty;
            sCmd = "Update {0}.WebPriceCaption set PriceCaptionName =@PriceCaptionName where ID =@ID ; ";
            string command = string.Format(sCmd, sDB);

            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@PriceCaptionName",txtPriceCaptionName.Text.Trim()),
                     new MySqlParameter("@ID",ID),
                 };

            iUpdatePriceCaptionHeader = ObjMain.ExecuteQuery(command, parameters);

            for (int i = 1; i < 5; i++)
            {
                sPriceCaptionName = "";
                switch (i)
                {
                    case 1:
                        //sPriceCaptionName = Microsoft.Security.Application.Encoder.HtmlEncode(txtPrice1Caption1.Text.Trim());
                        sPriceCaptionName = txtPrice1Caption1.Text.Trim();
                        break;
                    case 2:
                        //sPriceCaptionName = Microsoft.Security.Application.Encoder.HtmlEncode(txtPrice1Caption2.Text.Trim());
                        sPriceCaptionName = txtPrice1Caption2.Text.Trim();
                        break;
                    case 3:
                        //sPriceCaptionName = Microsoft.Security.Application.Encoder.HtmlEncode(txtPrice1Caption3.Text.Trim());
                        sPriceCaptionName = txtPrice1Caption3.Text.Trim();
                        break;
                    case 4:
                        //sPriceCaptionName = Microsoft.Security.Application.Encoder.HtmlEncode(txtPrice1Caption4.Text.Trim());
                        sPriceCaptionName = txtPrice1Caption4.Text.Trim();
                        break;
                }

                int iItemID = i + 1;
                sCmd = "Update {0}.WebPriceCaptionDetail set pricecaption=@pricecaption where pricecaptionid=@pricecaptionid and priceid=@priceid ";
                string commandA = string.Format(sCmd, sDB);
                MySqlParameter[] parametersA =
                  {
                     new MySqlParameter("@pricecaption",sPriceCaptionName),
                     new MySqlParameter("@pricecaptionid",ID),
                     new MySqlParameter("@priceid",i),
                 };
                iUpdatePriceCaptionDetail = ObjMain.ExecuteQuery(commandA, parametersA);              
            }
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "success_msg", "alert(' Price Caption Successfully Update. ')", true);
            txtPriceCaptionName.Text = "";
            txtPrice1Caption1.Text = "";
            txtPrice1Caption2.Text = "";
            txtPrice1Caption3.Text = "";
            txtPrice1Caption4.Text = "";
        }

        private void ShowPriceCaptionList(string sDB)
        {
            // Prevention SQL Injection : 11-10-21
            // Prevention xss 
            // Parameterized Approaches 
            grdPriceCaption.DataSource = null;
          
           string  cmd =  "Select ID,pricecaptionname from {0}.webpricecaption;";
           string command = string.Format(cmd, sDB);
            
            DataSet ds = new DataSet();
            DataTable Dt = new DataTable();

            Dt = ObjMain.GetData_DT(command);
            grdPriceCaption.DataSource = Dt;
            grdPriceCaption.DataBind();

        }
        protected void OnSelectedIndexChanged(object sender, EventArgs e)
        {            
            BranchFullName =cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
            Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
            string sDB = Cmb_BranchName;
            string ID = (grdPriceCaption.SelectedRow.FindControl("lblPriceCaptionID") as Label).Text;
            string PriceCaption = (grdPriceCaption.SelectedRow.FindControl("lblPriceCaptionname") as Label).Text;
            txtPriceCaptionID.Text = ID.ToString().Trim();
            txtPriceCaptionName.Text = PriceCaption.ToString().Trim();
            dtPriceCaptionDetail = ObjSel.GetPriceCaptionDetail(sDB, ID.ToString());
            for (int i = 0; i < dtPriceCaptionDetail.Rows.Count; i++)
            {
                switch (i)
                {
                    case 0:
                        txtPrice1Caption1.Text = dtPriceCaptionDetail.Rows[i]["PriceCaption"].ToString();
                        break;
                    case 1:
                        txtPrice1Caption2.Text = dtPriceCaptionDetail.Rows[i]["PriceCaption"].ToString();
                        break;
                    case 2:
                        txtPrice1Caption3.Text = dtPriceCaptionDetail.Rows[i]["PriceCaption"].ToString();
                        break;
                    case 3:
                        txtPrice1Caption4.Text = dtPriceCaptionDetail.Rows[i]["PriceCaption"].ToString();
                        break;
                }
            }

        }

    }
}