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.Web.UI.DataVisualization.Charting;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.Services;
namespace SUNWEB
{
    public partial class TopSale : 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();
        string Rcd_id = string.Empty;
        string RPortalid = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        string ActiveCallvalue = string.Empty;
        string L_MaxUserCnt = string.Empty;
        string L_RetailDashboard = string.Empty;
        string L_SummarySales = string.Empty;
        string L_ItemSales = string.Empty;
        string L_TaxAnalysis = string.Empty;
        string L_TopSale = string.Empty;
        string L_MothlySales = string.Empty;
        string L_HourlySales = string.Empty;
        string L_GroupSale = string.Empty;
        string Branchidval = string.Empty;
        DataTable dtgraphItem = new DataTable("Chart");
        DataTable dtgraphCat = new DataTable("Chart");
        string X, Y;
        string GraphWidth = "360";
        string GraphHeight = "260";
        string[] color = new string[12];
        MYSQLCLOUD ObjMainCloud = new MYSQLCLOUD();
        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();
        decimal totaltaxableamount = 0;
        decimal Gtotaltaxableamount = 0;
        decimal totaltaxamount = 0;
        decimal Gtotaltaxamount = 0;
        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 PID = string.Empty;
        string Page_Acess = string.Empty;
        string Read_Acess = string.Empty;
        string Write_Acess = string.Empty;
        string Isdowld_Acess = 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;
        StringBuilder str = new StringBuilder();
        protected void Page_Load(object sender, EventArgs e)
        {
             PID = "5";            // This is for TopSale
             Chart sales = new Chart();
             if (!IsPostBack)
             {
                 txtFromDt.Text = Curr_DateOnly;
                 txtToDt.Text = Curr_DateOnly;
             }
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            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();

                    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["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
             if (!IsPostBack)
                {
                    LoadBranchName();
                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        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;
                    LoadDate(Session["Branch_HQ"].ToString(), txtFromDt.Text, txtToDt.Text);
                    LoadDataGraphByCategory(Session["Branch_HQ"].ToString(), txtFromDt.Text, txtToDt.Text);
                    LoadDataGraphByItem(Session["Branch_HQ"].ToString(), txtFromDt.Text, txtToDt.Text);
                    System.Threading.Thread.Sleep(2000);
                 }
                if ((Session["L_TopSale"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {

                }

            }
            else
            { 

            }



     }


        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 LoadDate(string Branch_Nam, string D1, string D2)
        {
            MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
            Cn.Open();
            string Qry1 = "Select b.barcode,b.Name,b.InventoryDesc,sum(qty) as QTY,sum(b.taxamount1+b.taxamount2+b.taxamount3+b.TaxableAmount) as TPrice " +
                        " from " + Branch_Nam + ".trans a join " + Branch_Nam + ".transdetail b " +
                        " on a.transid=b.transid " +
                        " where businessdate between '" + D1 + "' and '" + D2 + "' and TransStatus=2 and itemstatus=0 " +
                        " group by barcode order by qty desc ; ";
            MySqlDataAdapter Ada = new MySqlDataAdapter(Qry1, Cn);
            ds = new DataSet();
            Ada.Fill(DT);
            grdTaxAnalysis.DataSource = DT;
            grdTaxAnalysis.DataBind();
        }
        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.GetFirstBranch7(Session["Branch_HQ"].ToString(), Session["UserId"].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);
            DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            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_TopSale = DtLicense.Rows[0]["TOPSALE"].ToString();
                Session["L_TopSale"] = L_TopSale;
                
              }
            if (Session["L_TopSale"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {
                LoadDate(ActiveCallvalue, txtFromDt.Text, txtToDt.Text);
                LoadDataGraphByCategory(ActiveCallvalue, txtFromDt.Text, txtToDt.Text);
                LoadDataGraphByItem(ActiveCallvalue, txtFromDt.Text, txtToDt.Text);
                System.Threading.Thread.Sleep(2000);
            }
           }
        public void UPDATEBRANCH(string ActiveCallvalue)
        {
            if (!string.IsNullOrEmpty(Session["UserId"] as string))
            {
                Useridvalue = Session["UserId"].ToString();
                QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + ActiveCallvalue + "' where Userid=" + Useridvalue + "";
                S = ObjMain.ExecuteNonQuery(QueryCurr_Select);
            }
            else
            {
                Response.Redirect("Login.aspx");
            }
        }
        public void LoadBranchName()
        {
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtNormalUser;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }
        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranches.Visible == true)
            {
                Curr_BranchFullName = cmbBranches.SelectedItem.Text;
                cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )

            }

            if (cmbBranches.Visible == false)
            {
                Curr_BranchFullName = cmbBranches.SelectedItem.Text;
                cd_BranchAlias = Session["Branch_HQ"].ToString();

            }


            lblSearchResult.Text = "Search Result";
            if(cmbBranches.SelectedIndex != 0)
            {
                 
                 LoadDate(cd_BranchAlias, txtFromDt.Text, txtToDt.Text);
                 LoadDataGraphByCategory(cd_BranchAlias, txtFromDt.Text, txtToDt.Text);
                 
                 LoadDataGraphByItem(cd_BranchAlias, txtFromDt.Text, txtToDt.Text);

                 lblMsgTotalSelection.Text = "&nbsp;&nbsp;&nbsp; Top Sales  Between &nbsp;&nbsp; " + txtFromDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtToDt.Text;
                 UPDATEBRANCH(cd_BranchAlias);
            }
            else
            { 
            }
            Page.Response.Redirect(Page.Request.Url.ToString(), true);
        }
        protected void btnGetReports_Click(object sender, EventArgs e)
        {

            if (cmbBranches.Visible == true)
            {
                Curr_BranchFullName = cmbBranches.SelectedItem.Text;
                cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
              
            }

            if (cmbBranches.Visible ==false)
            {
                Curr_BranchFullName = cmbBranches.SelectedItem.Text;
                cd_BranchAlias = Session["Branch_HQ"].ToString();

            }
            

            lblSearchResult.Text = "Search Result";
            if (cmbBranches.SelectedIndex!=0)
            {
                LoadDate(cd_BranchAlias, txtFromDt.Text, txtToDt.Text);
                LoadDataGraphByCategory(cd_BranchAlias, txtFromDt.Text, txtToDt.Text);
                LoadDataGraphByItem(cd_BranchAlias, txtFromDt.Text, txtToDt.Text);
                // Change code : 29-10-19
               // GetData();
                lblMsgTotalSelection.Text = "&nbsp;&nbsp;&nbsp; Top Sales  Between &nbsp;&nbsp; " + txtFromDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtToDt.Text;


            }
          // Page.Response.Redirect(Page.Request.Url.ToString(), true);   (Reload the Page)
        }
        protected void txtToDt_TextChanged(object sender, EventArgs e)
        {
        }
        protected void txtFromDt_TextChanged(object sender, EventArgs e)
        {
        }
        protected void grdTaxAnalysis_RowDataBound(object sender, GridViewRowEventArgs e)
        {
        }
        protected void grdTaxAnalysis_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void LoadDataGraphByItem(string Branch_Nam, string D1, string D2)
        {
            string sCmd = "Select TRIM(SUBSTRING(`InventoryDesc`, 1, 16)) as InventoryDesc,sum(qty) as QTY " +
                         " from " + Branch_Nam + ".trans a join " + Branch_Nam + ".transdetail b " +
                         " on a.transid=b.transid " +
                         " where businessdate between '" + D1 + "' and '" + D1 + "' and TransStatus=2 and itemstatus=0 " +
                         " group by barcode order by qty desc limit 10 ;";
            dtgraphItem = ObjMainCloud.GetData_DT(sCmd);
            Session["dtgraphItem"] = dtgraphItem;

           
          
        }
        private void LoadDataGraphByCategory(string Branch_Nam, string D1, string D2)
        {
 
            string sCmd = "  Select C.CategoryName,sum(qty) as QTY " +
                          " from " + Branch_Nam + ".trans a join " + Branch_Nam + ".transdetail b " +
                          " on a.transid=b.transid join " + Branch_Nam + ".inventorycategories c " +
                          " on b.categorynumber = c.categorynumber " +
                          " where businessdate between '" + D1 + "' and '" + D2 + "' and TransStatus=2 and itemstatus=0 " +
                          " group by b.CategoryNumber order by qty desc limit 10 ;";
            dtgraphCat = ObjMainCloud.GetData_DT(sCmd);
            Session["dtgraphCat"] = dtgraphCat;
           
        }
        public static string unicode_iso8859(string src)           
        {
         
            Encoding iso = Encoding.GetEncoding("iso8859-1");
            Encoding unicode = Encoding.UTF8;
            byte[] unicodeBytes = unicode.GetBytes(src);
            return iso.GetString(unicodeBytes);
        }
        public static string iso8859_unicode(string src)
        {
            Encoding iso = Encoding.GetEncoding("iso8859-1");
            Encoding unicode = Encoding.UTF8;
            byte[] isoBytes = iso.GetBytes(src);
            return unicode.GetString(isoBytes);
            
        }

        [WebMethod]
        public static List<Data> GetData()
        {         
            DataTable dt = new DataTable();
            dt = HttpContext.Current.Session["dtgraphCat"] as DataTable;


            //dt = people;
             List<Data> dataList = new List<Data>();
             string cat = "";
             int val = 0;

             foreach (DataRow dr in dt.Rows)
             {
                 cat = dr[0].ToString();
                 val = Convert.ToInt32(dr[1]);
                 dataList.Add(new Data(cat, val));
             }
             return dataList;
        }

        [WebMethod]
        public static List<Data1> GetData1()
        {
            DataTable dt = new DataTable();
            dt = HttpContext.Current.Session["dtgraphItem"] as DataTable;

            //dt = people;
            List<Data1> dataList1 = new List<Data1>();
            string cat = "";
            int val = 0;

            foreach (DataRow dr in dt.Rows)
            {
                cat = dr[0].ToString();
                val = Convert.ToInt32(dr[1]);
                dataList1.Add(new Data1(cat, val));
            }


            return dataList1;
        }

       




    }

     public class Data
    {
        public string ColumnName = "";
        public int Value = 0;

        public Data(string columnName, int value)
        {
            ColumnName = columnName;
            Value = value;
        }

    }

     public class Data1
    {
        public string ColumnName = "";
        public int Value = 0;

        public Data1(string columnName, int value)
        {
            ColumnName = columnName;
            Value = value;
        }

    }










}