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;
namespace SUNWEB
{
    public partial class Taxanalysis_Light : System.Web.UI.Page
    {

        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_ErrorLog ObjLog = new BL_ErrorLog();
        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 DtK = new DataTable();
        DataTable DtM = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DtExcel = new DataTable();
        DataTable DTExcelTemp = new DataTable();
        string ActiveCallvalue = string.Empty;
        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 cd_BranchAlias = string.Empty;
        string IsMultiBranch = string.Empty;
        string IsSuperAdmin = string.Empty;
        string Cd_BranchName = string.Empty;
        string Rcd_id = string.Empty;
        string RPortalid = 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 BranchFullName=string.Empty;


        string L_TaxAnalysis_light = string.Empty;

        // Others
        string Branchidval = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;

        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;
        string HQ = string.Empty;
        string Cm_id = string.Empty;

        string BranchDB = string.Empty;
        string ISHQ = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "75";    // This is for TaxAnlaysis_light


            if (!IsPostBack)
            {
                txtFromDt.Text = Curr_DateOnly;
                txtToDt.Text = Curr_DateOnly;
            }

            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_light();

                    UpdateActiveBrach_Light();
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();
                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin_light();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin_light();
                    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_TaxAnalysis_light"].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
            {

            }




        }
        public void UpdateActiveBrach_Light()
        {
            string R_current_Activecellvalue = ObjMain.ExecuteScalar("select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ");
            int _upt = ObjMain.ExecuteNonQuery("UPDATE  portaldb.usermaster SET ActiveValue='' WHERE Userid=" + Session["UserId"].ToString() + "");
            ActiveCallvalue = ObjSel.GetFirstBranch_Light(Session["Branch_HQ"].ToString());
            int _upt_new = ObjMain.ExecuteNonQuery("UPDATE  portaldb.usermaster SET ActiveValue='" + ActiveCallvalue + "' WHERE Userid=" + Session["UserId"].ToString() + "");
        }

        /// <summary>
        ///  This function for get branchname on branch selection 
        /// </summary>
        public void BranchUpdate_Light(string branchname)
        {
            string R_current_Activecellvalue = ObjMain.ExecuteScalar("select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ");
            int _upt = ObjMain.ExecuteNonQuery("UPDATE  portaldb.usermaster SET ActiveValue='' WHERE Userid=" + Session["UserId"].ToString() + "");
            ActiveCallvalue = ObjSel.GetBranch_Branchname_Light(Session["Branch_HQ"].ToString(), branchname);
            int _upt_new = ObjMain.ExecuteNonQuery("UPDATE  portaldb.usermaster SET ActiveValue='" + ActiveCallvalue + "' WHERE Userid=" + Session["UserId"].ToString() + "");
        }

        public void LoadBranchName4SuperAdmin_light()
        {
            DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdmin8_Light(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");
            }
        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

            ActiveCall_on_BranchSelection();

        }

        protected void btnGetReports_Click(object sender, EventArgs e)
        {

            
            if (txtFromDt.Text != "" && txtToDt.Text != "" && cmbBranches.SelectedIndex != 0)
            {

                string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);
                string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtToDt.Text);
                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 )
                LoadTaxanalysisData(Cmb_BranchName, StartDT, EndDt);

                

            }



        }
        public void ActiveCall()
        {
            UpdateActiveBrach_Light();

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


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

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch_Light(Session["Branch_HQ"].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_TaxAnalysis_light = DtLicense.Rows[0]["TAXANALYSIS_LIGHT"].ToString();
                Session["L_TaxAnalysis_light"] = L_TaxAnalysis_light;
            }
            if (Session["L_TaxAnalysis_light"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {

                System.Threading.Thread.Sleep(2000);

                // call the methods 
                LoadTaxanalysisData(Cmb_BranchName, txtFromDt.Text, txtToDt.Text);


            }

        }

        public void ActiveCall_on_BranchSelection()
        {
            BranchUpdate_Light(cmbBranches.SelectedItem.Text);

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


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

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch_Light(Session["Branch_HQ"].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_TaxAnalysis_light = DtLicense.Rows[0]["TAXANALYSIS_LIGHT"].ToString();
                Session["L_TaxAnalysis_light"] = L_TaxAnalysis_light;
            }
            if (Session["L_TaxAnalysis_light"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {

                System.Threading.Thread.Sleep(2000);

                // call the methods 
                LoadTaxanalysisData(Cmb_BranchName, txtFromDt.Text, txtToDt.Text);


            }

        }

        public void UPDATEBRANCH(string ActiveCallvalue)
        {
            Useridvalue = Session["UserId"].ToString();
            QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + ActiveCallvalue + "' where Userid=" + Useridvalue + "";
            S = ObjMain.ExecuteNonQuery(QueryCurr_Select);
        }

        public void LoadTaxanalysisData(string Branch_Nam, string D1, string D2)
        {

            System.Threading.Thread.Sleep(1000);
            string Qry1 = "  select * from {0}.TaxSummary_parent_light  where date(businessdate) between @D1  and  @D2  ";

            // Prevent the SQL Injections
            // Parameterized Approach 

            string command = string.Format(Qry1, Branch_Nam);
            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@D1",D1),
                     new MySqlParameter("@D2",D2),
                    };

            DtM = ObjMain.NewGetData_DT(command, parameters);

            grdTaxAnalysis.DataSource = DtM;
            grdTaxAnalysis.DataBind();




        }

        protected void grdTaxAnalysis_RowDataBound(object sender, GridViewRowEventArgs e)
        {

            try
            {

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

                }
                else
                {
                    cd_BranchAlias = Session["Branch_HQ"].ToString();

                }

                if (e.Row.RowType == DataControlRowType.DataRow)
                {

                    GridView gv = (GridView)e.Row.FindControl("grdDetails");
                    string businessdate1 = ((DataRowView)e.Row.DataItem)["businessdate"].ToString().Trim();
                    string businessdateT = businessdate1.Substring(0, businessdate1.IndexOf(' '));


                    DateTime businessdate;
                    businessdate = Convert.ToDateTime(businessdateT);
                    string BusinesDT = businessdate.ToString("yyyy-MM-dd");
                    string Qry2 = "select  DATE_FORMAT(BusinessDate, '%Y-%m-%d') AS BusinessDate, paymenttype as PaymentType , Total as Sales, Taxableamount as Taxableamount, Tax1 as SVC,TAX2 as GST, "
                        + " Tax3 as Tax3 ,TaxAmount from  {0}.TaxSummary_child_light where  businessdate=@businessdate  ";
           
                    string command = string.Format(Qry2, cd_BranchAlias);
                    MySqlParameter[] parameters =
                         {
                          new MySqlParameter("@businessdate",BusinesDT)
                         };

                    DtK = ObjMain.NewGetData_DT(command, parameters);

                    gv.DataSource = DtK;
                    gv.DataBind();

                }

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



        }

        protected void btnExcel_Click(object sender, EventArgs e)
        {

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

            LoadExcelReportByDate(cd_BranchAlias,txtFromDt.Text,txtToDt.Text);

        }
        public void  LoadExcelReportByDate(string db , string D1,string D2)
        {

            string Qry2 = "select  DATE_FORMAT(BusinessDate, '%Y-%m-%d') AS BusinessDate, paymenttype as PaymentType , Total as Sales, Taxableamount as Taxableamount, Tax1 as SVC,TAX2 as GST, "
                       + " Tax3 as Tax3 ,TaxAmount from  {0}.TaxSummary_child_light where  businessdate between @D1 AND @D2 order by BusinessDate  ";

            string command = string.Format(Qry2, db);
            MySqlParameter[] parameters =
                 {
                          new MySqlParameter("@D1", D1),
                          new MySqlParameter("@D2",D2)
                         };

            DtK = ObjMain.NewGetData_DT(command, parameters);

            DtK.AcceptChanges();

            // --- Export to Excel ---
            GridView gv = new GridView();
            gv.DataSource = DtK;
            gv.DataBind();

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=TaxAnalysisDatewiseExport.xls");
            HttpContext.Current.Response.Charset = "";
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            using (StringWriter sw = new StringWriter())
            using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            {
                gv.RenderControl(hw);
                string style = "<style> td { mso-number-format:\\@; } </style>";
                HttpContext.Current.Response.Write(style);
                HttpContext.Current.Response.Output.Write(sw.ToString());
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }




        }


        protected void grdTaxAnalysis_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
    }