using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;
using System.Text;

public partial class Reports_TA_UI_LeavePermissionDailyReport : Base.BasePage
{
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    HeaderInformation hdrTable = new HeaderInformation();
    GetReports rptEmp = new GetReports();
    ResourceManager rm;
    CultureInfo ci;
    cls_Common objCommon = new cls_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    string strFromdate, gstrDateFormat;
    Rpt_Common rptcommon = new Rpt_Common();
    int intIndividualUser = 0;

    protected override void Page_Load(object sender, EventArgs e)
    {
        objCommon.menu("LeaveReports", "112");
        // session checking
        base.Page_Load(sender, e);

        //get the culture info to set the language        
        if (!Page.IsPostBack)
        {
            Hidden1.Value = Session["IDateFormat"].ToString();
            base.CheckPages(0);
        }
        string source_Language;
        source_Language = Session["Session_ActiveLanguage"].ToString();
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        LoadStrings(ci);
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);

        //Set UserRights
        UserRights();

        if (!IsPostBack)
        {
            txtFromDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
          

            if (Request.QueryString["Source"] != null)
            {
                if (Request.QueryString["Source"].ToString() == "Email")
                {
                    string strScript = "";
                    strScript = strScript + "<script language='javascript'>";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_divMenu').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div1').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div2').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div3').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_Header1_RptLogoHeader').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_BodyContentPHRpt_Modifylevel').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_BodyContentPHRpt_TimePeriod').style.display = 'none';";




                    strScript = strScript + "</script>";
                    Page.RegisterStartupScript("Script", strScript);

                    btnSave.Visible = true;
                    btn_View.Visible = false;
                    btnBack.Visible = true;
                    IDTest1.Visible = false;

                }
            }
            else
            {
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "document.getElementById('ctl00_BodyContentPHRpt_Modifylevel').style.display = 'none';";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Script", strScript);
                IDTest1.Visible = false;
            }
            if (Request.QueryString["ScheduleId"] != null)
            {
                string strGet = hdnReportFilters.Value;
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "GethiddenValue();";
                strScript += " </script>";
                this.RegisterStartupScript("setScript", strScript);
                IDTest1.Visible = true;
                //string strScript1 = "<script language=\"javascript\">";
                //strScript1 = strScript1 + "{window.opener.parent.document.getElementById('ctl00_BodyContentPH_hdnFilters').value='" + hdnReportFilters.Value + "';}";
                //strScript1 = strScript1 + "self.close();";
                //strScript1 = strScript1 + "</script>";
                ////string str = strScript;
                //Response.Write(strScript1);

                //Page.RegisterStartupScript("GethiddenValue", "<script>GethiddenValue();</script>");


            }

        }

        //Check whether the employee is Individual User

        intIndividualUser = objCheckUser.CheckIndividualUser(Session["UserGroupName"].ToString());



        if (intIndividualUser >= 1)
        {
            PlaceHolderShift.Controls.Clear();
            //divEmployeeDetails.Visible = false;
            //lblEmpSwipe.Visible = false;
            //txtSwipeCard.Visible = false;

        }

        //Convert date time to MM/dd/YYYY format

        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        fillReportingddl();
        fillSanctioningddl();
    }



    // <summary>
    /// Validate the FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            //strCurrentDate = objCommon.DateConvertion(gstrDateFormat,DateTime.Today.Date.ToString());
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            //strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);

            //DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date.ToString("MM/dd/yyyy")); ;
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strFromdate);

            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
            //
        }

    }

    #region 'Button Clicks'

    /// <summary>
    /// Load the Shift report
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    protected void btn_View_Click(object sender, EventArgs e)
    {
        int employeeCategory = 0, employeeType = 0;
        string strSwipeCard = "";
        if (Page.IsValid == true)
        {
            //Create the datatable ,that holds the header information
            DataTable dtHdr = new DataTable();
            dtHdr = hdrTable.CreateHeader();
            dtHdr.TableName = "Header";

            //Add the Header information
            DataRow drHdr = dtHdr.NewRow();
            drHdr["Link"] = 1;
            drHdr["Hdr1"] = "";
            drHdr["Hdr2"] = "";
            drHdr["Address1"] = "";
            drHdr["Address2"] = "";
            drHdr["ReportName"] = "Monthly Attendance Report";

            if (txtFromDate.Text != "")
            {
                DateTime tmpFrom = DateTime.Parse(strFromdate);
                drHdr["FromDate"] = tmpFrom.ToString("dd-MMM-yyyy");
            }
            else
                drHdr["FromDate"] = "";
            //if (txtToDate.Text != "")
            //{
            //    DateTime tmpTo = DateTime.Parse(strTodate);
            //    drHdr["ToDate"] = tmpTo.ToString("dd-MMM-yyyy");
            //}
            //else
            drHdr["ToDate"] = "";

            dtHdr.Rows.Add(drHdr);


            string dtFrom = "", dtTo = "";

            if (txtFromDate.Text != "")
                dtFrom = strFromdate;




            //Get the Report source from the Server and load this into the report table
            DataSet dsDailyLeave = new DataSet();

            //this is new report

            int shft = 0;
            string Level = string.Empty;
            string employeeName = string.Empty;
            string empName = string.Empty;
            string empId = string.Empty;

            if (intIndividualUser >= 1)
            {
                empName = string.Empty;
                shft = 0;
                Level = string.Empty;
                empId = Convert.ToString(Session["EmployeeCodeId"]);
            }
            else
            {
                //if (Convert.ToInt16(Session["parentLevelId"]) != 0)
                //{
                // Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]));
                Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                //}
            }
            DataSet dsDailyLeaveUnplanned = new DataSet();
            DataSet dsDailyPermission = new DataSet();

            DataSet dsDailyPermissionUnplanned = new DataSet();

            string strEmpAutoId = string.Empty;
            if (Session["ReportsBasedOn"] != null)
            {
                if (Session["ReportsBasedOn"].ToString() == "False")
                {
                    strEmpAutoId = "0";
                }
                else
                {
                    strEmpAutoId = Session["EmpAutoID"].ToString();
                }
            }

            dsDailyLeave = rptEmp.SelectLeavePermissionDailyReport_Leaves_Angler(dtFrom, Level, "P", Convert.ToInt64(strEmpAutoId), ddl_ReportingToNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_ReportingToNew.SelectedValue) : 0, ddl_LeaveSancAuthorityNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_LeaveSancAuthorityNew.SelectedValue) : 0, Convert.ToInt16(Session["parentLevelId"]), Session["UserGroupName"].ToString());
            dsDailyLeaveUnplanned = rptEmp.SelectLeavePermissionDailyReport_Leaves_Angler(dtFrom, Level, "U", Convert.ToInt64(strEmpAutoId), ddl_ReportingToNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_ReportingToNew.SelectedValue) : 0, ddl_LeaveSancAuthorityNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_LeaveSancAuthorityNew.SelectedValue) : 0, Convert.ToInt16(Session["parentLevelId"]), Session["UserGroupName"].ToString());

            dsDailyPermission = rptEmp.SelectLeavePermissionDailyReport_Permission_Angler(dtFrom, Level, "P", Convert.ToInt64(strEmpAutoId), ddl_ReportingToNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_ReportingToNew.SelectedValue) : 0, ddl_LeaveSancAuthorityNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_LeaveSancAuthorityNew.SelectedValue) : 0, Convert.ToInt16(Session["parentLevelId"]), Session["UserGroupName"].ToString());
            dsDailyPermissionUnplanned = rptEmp.SelectLeavePermissionDailyReport_Permission_Angler(dtFrom, Level, "U", Convert.ToInt64(strEmpAutoId), ddl_ReportingToNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_ReportingToNew.SelectedValue) : 0, ddl_LeaveSancAuthorityNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_LeaveSancAuthorityNew.SelectedValue) : 0, Convert.ToInt16(Session["parentLevelId"]), Session["UserGroupName"].ToString());

            if (ddl_ReportingToNew.SelectedValue != "-Select-")
            {
                Session["ddlReportingTo"] = ddl_ReportingToNew.SelectedValue;
            }
            else
            {
                Session["ddlReportingTo"] = "0";
            }
            if (ddl_LeaveSancAuthorityNew.SelectedValue != "-Select-")
            {
                Session["ddlSanctioningAuthority"] = ddl_LeaveSancAuthorityNew.SelectedValue;
            }
            else
            {
                Session["ddlSanctioningAuthority"] = "0";
            }
            ////Report Header
            //int orgID = Convert.ToInt16(Session["parentLevelId"]);
            //Session["parentLevelId"] = null;
            //if (orgID == 0)
            //{
            //    //orgID = 1;
            //    DataSet dsOrgid = new DataSet();
            //    dsOrgid = rptEmp.getMinLevel();
            //    if (dsOrgid.Tables[0].Rows.Count > 0)
            //    {
            //        if (dsOrgid.Tables[0].Rows[0]["minID"] != DBNull.Value)
            //        {
            //            orgID = Convert.ToInt16(dsOrgid.Tables[0].Rows[0]["minID"]);
            //        }
            //    }
            //}
            //int lid = 0;
            //org_levelsEventData getOrg = new org_levelsEventData();
            //getOrg.GetOrgParentLevels_FromID(orgID);
            //DataSet ds_getOrg = new DataSet();
            //ds_getOrg = getOrg.GetOrgParentLevels();
            //if (ds_getOrg.Tables[0].Rows.Count > 0)
            //{
            //    lid = Convert.ToInt16(ds_getOrg.Tables[0].Rows[0]["levelID"]);
            //}
            //DataSet dsHeader = new DataSet();
            //dsHeader = rptEmp.getHeader(lid);
            //if (dsHeader.Tables[0].Rows.Count > 0)
            //{
            //    DataTable dtRptHeader = new DataTable();
            //    dtRptHeader = dsHeader.Tables[0].Copy();
            //    dtRptHeader.WriteXmlSchema(@"E:\reportHeader.xml");
            //    Session["reportHeader"] = dtRptHeader;
            //}
            ////End of Report Header
            //Session["parentLevelId"] = null;

            //DataTable dtDailyLeave = new DataTable();

            //DataTable dtDailyLeaveUnplanned = new DataTable();

            //DataTable dtDailyPermission = new DataTable();

            //Check the Empty table 

            if (dsDailyLeave.Tables["Table"].Rows.Count == 0 && dsDailyLeaveUnplanned.Tables["Table"].Rows.Count == 0 && dsDailyPermission.Tables["Table"].Rows.Count == 0 && dsDailyPermissionUnplanned.Tables["Table"].Rows.Count == 0)
            {
                string strMsg;
                strMsg = "<script language='javascript'>";
                strMsg = strMsg + "alert('There is no record ');";
                strMsg = strMsg + "</script>";

                Page.RegisterStartupScript("Display Message", strMsg);

                return;
            }


            //dtDailyLeave = dsDailyLeave.Tables["Table"].Copy();

            //dtDailyLeaveUnplanned = dsDailyLeaveUnplanned.Tables["Table"].Copy();
            //dtDailyPermission = dsDailyPermission.Tables["Table"].Copy();


            ////Add the link column
            //DataColumn dcLink = new DataColumn("Link", Type.GetType("System.Int32"));
            //dtDailyLeave.Columns.Add(dcLink);

            //for (int i = 0; i < dtDailyLeave.Rows.Count; i++)
            //{
            //    dtDailyLeave.Rows[i]["Link"] = 1;
            //}

            ////WRITE XML SCHEMA TO DISK - THIS IS ONLY REQUIRED DURING DEVELOPMENT TO BUILD THE REPORT
            //dtDailyLeave.WriteXmlSchema(@"E:\DailyReportLeave.xml");

            //dtDailyLeaveUnplanned.WriteXmlSchema(@"E:\DailyReportUnplanned.xml");
            //dtDailyPermission.WriteXmlSchema(@"E:\DailyReportPermission.xml");

            //dtHdr.WriteXmlSchema(@"E:\DailyReportHdr.xml");
            //return;

            ////Set the session variable that holds the report table and report header table
            //Session["Hdr"] = dtHdr;
            //Session["Source"] = dtMonthlyAttendance;
            //Session["Path"] = Server.MapPath(rm.GetString("rptMonthlyAttendance",ci));

            //Redirect the page to the report viewer
            //string strScript = "";
            //string strUrl = "TA_UI_Report_ReportViewer.aspx";
            //strScript = "<script language='javascript'>";
            //strScript = strScript + "window.open('TA_UI_Report_ReportViewer.aspx?ReportName1=MonthlyAttendance&dtFrom=" + dtFrom + "&Level=" + Level + "&ReportName=DailyReport&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]) + "');";
            //strScript = strScript + "</script>";
            //Response.Write(strScript);

            Response.Redirect("TA_UI_LeavePermissionDailyReportGrid.aspx?ReportName1=MonthlyAttendance&dtFrom=" + dtFrom + "&Level=" + Level + "&ReportName=DailyReport&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]));
        }
        // }
        //catch (Exception ex)
        //{
        //    Response.Write(ex);
        //    //
        //}


    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid == true)
            {

                string Level = string.Empty;
                //string empIdAutoId = string.Empty;

                if (intIndividualUser >= 1)
                {
                    Level = string.Empty;
                }
                else
                {
                    //empIdAutoId = txtEmployeeId.Text.Trim().ToString();
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                }



                StringBuilder strFilters = new StringBuilder();
                strFilters.Append("@fromDat=" + " Duration_From " + ",");
                strFilters.Append("@LevelID=" + Level + ",");
                strFilters.Append("@IntimationType=IntimationType,");
                strFilters.Append("@EmpAutoId=0,");
                strFilters.Append("@ReportingTo= " + Convert.ToString(ddl_ReportingToNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_ReportingToNew.SelectedValue) : 0) + ",");
                strFilters.Append("@SanctioningAuthority= " + Convert.ToString(ddl_LeaveSancAuthorityNew.SelectedIndex != 0 ? Convert.ToInt64(ddl_ReportingToNew.SelectedValue) : 0) + ",");
                strFilters.Append("@ParentId=" + Convert.ToInt16(Session["parentLevelId"]) + ",");
                strFilters.Append("@UserGroupName=" + Session["UserGroupName"].ToString());


                string strScript = "<script language=\"javascript\">";
                strScript = strScript + "{window.opener.parent.document.getElementById('ctl00_BodyContentPH_hdnFilters').value='" + strFilters + "'; window.opener.parent.document.getElementById('ctl00_BodyContentPH_hdnCompanyId').value='" + Convert.ToInt32(Session["parentLevelId"]).ToString() + "';}";
                //strScript = strScript + "self.close();";
                strScript = strScript + "self.close();";
                strScript = strScript + "</script>";
                Response.Write(strScript);
            }
        }
        catch
        {
            //
        }

    }

    protected void IDTest1_Click(object senser, EventArgs e)
    {
        if (hdnReportFilters.Value != "")
        {
            string strhdnParameters = hdnReportFilters.Value;
            string[] strArray = new string[50];
            string[] strArray1 = new string[50];
            strArray = strhdnParameters.Split(',');

            for (int i = 0; i < strArray.Length; i++)
            {
                string[] strTemp = new string[5];
                strTemp = strArray[i].Split('=');
                strArray1[i] = strTemp[1];
            }

            //txtEmployeeId.Text = strArray1[2].ToString();
            //ddlShift.SelectedValue = strArray1[3].ToString();
            //txtEmployeeName.Text = Convert.ToString(strArray1[4].ToString()).Trim().Replace("''", "'");
            //txtEmployeeName.Text = Convert.ToString(strArray1[4].ToString()).Trim().Replace("%", " ");
            //ddlEmpCatagory.SelectedValue = strArray1[6].ToString();
            //ddlEmpType.SelectedValue = strArray1[7].ToString();
            //txtSwipeCard.Text = strArray1[10].ToString();
            //ucOrganizationLevel.Visible = false;
            //Session["parentLevelId_modify"] = hdnCompanyId1.Value;
            //ddlDesignation.SelectedValue = strArray1[12].ToString();
            //ddlGender.SelectedValue = strArray1[13].ToString();

            string strScript = "";
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_divMenu').style.display = 'none';";
            strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div1').style.display = 'none';";
            strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div2').style.display = 'none';";
            strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div3').style.display = 'none';";
            strScript = strScript + "document.getElementById('ctl00_TA_uc_Header1_RptLogoHeader').style.display = 'none';";
            strScript = strScript + "document.getElementById('ctl00_BodyContentPHRpt_TimePeriod').style.display = 'none';";

            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Script", strScript);

            btnSave.Visible = true;
            btn_View.Visible = false;
            btnBack.Visible = true;
            IDTest1.Visible = false;
        }

    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        string strMsg;
        strMsg = "<script language='javascript'>";
        strMsg = strMsg + "window.close();";
        strMsg = strMsg + "</script>";
        Page.RegisterStartupScript("close report window", strMsg);
        return;
    }

    #endregion

    #region 'User Function'
    //Getting Information from resource file and display it in label
    private void fillReportingddl()
    {
        DataSet ds_Reporting = new DataSet();

        ds_Reporting = objEmployee.SelectReportingPerson_Angler();

        if (ds_Reporting != null)
        {
            if (ds_Reporting.Tables[0].Rows.Count > 0)
            {
                //ddl_ReportingToNew.DataSource = ds_Reporting;
                //ddl_ReportingToNew.DataTextField = "Name";
                //ddl_ReportingToNew.DataValueField = "employee_id";
                //ddl_ReportingToNew.DataBind();



                ddl_ReportingToNew.DataSource = ds_Reporting;
                ddl_ReportingToNew.DataTextField = "Name";
                ddl_ReportingToNew.DataValueField = "employee_id";
                ddl_ReportingToNew.DataBind();
            }
           // ds_Reporting.Dispose();
        }
    }
    private void fillSanctioningddl()
    {
        DataSet ds_Reporting = new DataSet();
        ds_Reporting = objEmployee.SelectSanctioningPerson_Angler();
        if (ds_Reporting != null)
        {
            if (ds_Reporting.Tables[0].Rows.Count > 0)
            {
                ddl_LeaveSancAuthorityNew.DataSource = ds_Reporting;
                ddl_LeaveSancAuthorityNew.DataTextField = "Name";
                ddl_LeaveSancAuthorityNew.DataValueField = "employee_id";
                ddl_LeaveSancAuthorityNew.DataBind();
            }
          //  ds_Reporting.Dispose();
        }
    }
    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        //lblShiftReport.Text = rm.GetString("Reports_Shift_ShiftReport", ci);
        //lblTimePeriod.Text = rm.GetString("Permission_PermissionDate", ci);


    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(44, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");

        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] == DBNull.Value || Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 1)
            {
                btn_View.Visible = true;
            }
            else
            {
                btn_View.Visible = false;
            }
        }
        else
        {
            Response.Redirect("ReportsLandingPage.aspx");
        }
    }

    #endregion

}
