#region Name Spaces
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;
#endregion

public partial class Reports_TA_UI_Report_FirstInPunchDifference : Base.BasePage
{
    #region Variable Declaration
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    HeaderInformation hdrTable = new HeaderInformation();
    GetReports rptEmp = new GetReports();
    Rpt_Common rptcommon = new Rpt_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    cls_Common objCommon = new cls_Common();
    ResourceManager rm;
    CultureInfo ci;
    string dtFrom = "", dtTo = "", EmployeeId = "", gstrDateFormat, strFromdate, strTodate;
    int intIndividualUser = 0;
    string gStrLevel = string.Empty, ParenetLevelid = string.Empty;
    #endregion

    #region Page Load
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            objCommon.menu("Exception Reports", "176");
            Hidden1.Value = Session["IDateFormat"].ToString();
            base.CheckPages(0);
        }

        //get the culture info to set the language        
        string source_Language;
        source_Language = Session["Session_ActiveLanguage"].ToString();
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);

        //Set UserRights
        UserRights();

        if (!IsPostBack)
        {
            // Bindings the employee category and type.
            BindingEmployeeCategoryandType();
            string strDayName = Convert.ToString(DateTime.Now.Date.DayOfWeek).ToLower();
            double iFromDate = strDayName.Contains("monday") ? 0 : strDayName.Contains("tuesday") ? -1 : strDayName.Contains("wednesday") ? -2 : strDayName.Contains("thursday") ? -3 : strDayName.Contains("friday") ? -4 : -5;
            //txtFromDate.Text = System.DateTime.Now.Date.AddDays(iFromDate).ToString(Convert.ToString(Session["MDateFormat"]));
            //txtToDate.Text = System.DateTime.Now.Date.AddDays(iFromDate + 5).ToString(Convert.ToString(Session["MDateFormat"]));
            txtFromDate.Text = (Convert.ToDateTime(objCommon.CurrentMonthStartDate())).ToString(Convert.ToString(Session["MDateFormat"]));
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Convert.ToString(Session["MDateFormat"]));

            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)
        {
            PlaceHolderLateEntry.Controls.Clear();
            divEmployeeDetails.Visible = false;
        }


        ////Convert date time to MM/dd/YYYY format
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        strTodate = txtToDate.Text;
        strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
        IDTest1.Visible = false;
    }
    #endregion

    #region Button Event

    /// <summary>
    /// Load Late Entry report
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_View_Click(object sender, EventArgs e)
    {
        int EmpCategory = 0, EmpType = 0;
        string Level = string.Empty, EmpName = string.Empty, EmpId = string.Empty;

        try
        {
            if (Page.IsValid == true)
            {
                // set employee category and type
                if (Convert.ToInt32(ddlEmpCatagory.SelectedValue) != 0)
                    EmpCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);

                if (Convert.ToInt32(ddlEmpType.SelectedValue) != 0)
                    EmpType = Convert.ToInt32(ddlEmpType.SelectedValue);

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

                if (txtToDate.Text != "")
                    dtTo = strTodate;

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

                if (intIndividualUser >= 1)
                {
                    EmpId = Convert.ToString(Session["EmployeeCodeId"]);
                    EmployeeId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    EmpId = txtEmployeeId.Text.Trim().ToString();
                    EmployeeId = txtEmployeeId.Text.Trim().ToString();
                    EmpName = txtEmployeeName.Text.Replace("'", "''").Replace(' ', '%');
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                    gStrLevel = Level;
                }

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

                string strMaxDeviationHrs = Convert.ToString(txtDeviationHrs.Text).Trim();
                string strPunchType = string.Empty;
                for (int i = 0; i < chklstPunchType.Items.Count; i++)
                {
                    strPunchType = chklstPunchType.Items[i].Selected ? (strPunchType == string.Empty ? ":" + chklstPunchType.Items[i].Value + ":" : strPunchType + ", :" + chklstPunchType.Items[i].Value + ":") : strPunchType;
                }

                //dsWeeklyHrs = rptEmp.GetFirstInPunchDifference(EmployeeId, Level, dtFrom, dtTo, EmpName, EmpCategory, EmpType, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), Convert.ToInt32(strEmpAutoId), strMaxDeviationHrs, strPunchType);

                string strReportName = "InPunchDeviationHrs";
                string strEmpCategory = EmpCategory.ToString();
                string strEmpType = EmpType.ToString();
                string strScript = "";
                strScript = strScript + "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
                strScript = strScript + "<meta http-equiv='X-UA-Compatible' content='IE=document.documentMode;' />";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "window.open('TA_UI_Report_ReportViewer.aspx?ReportName=" + strReportName + "&dtFrom=" + dtFrom + "&dtTo=" + dtTo + "&empid=" + EmpId + "&EmpName=" + EmpName + "&Level=" + Level + "&EmpCategory=" + strEmpCategory + "&EmpType=" + strEmpType + "&MaxDeviationHrs=" + strMaxDeviationHrs + "&PunchType=" + strPunchType + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]) + "&GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + "','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
                strScript = strScript + "</script>";
                Response.Write(strScript);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }

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

                string employeeName = string.Empty;
                string empId= string.Empty;
                string levelID = string.Empty;
                if (intIndividualUser >= 1)
                {
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    empId = txtEmployeeId.Text.Trim().ToString();
                    employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    employeeName = employeeName.Replace(' ', '%');
                    levelID = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));

                }

                string strPunchType = string.Empty;
                for (int i = 0; i < chklstPunchType.Items.Count; i++)
                {
                    strPunchType = chklstPunchType.Items[i].Selected ? (strPunchType == string.Empty ? "$" + chklstPunchType.Items[i].Value + "$" : strPunchType + "~ $" + chklstPunchType.Items[i].Value + "$") : strPunchType;
                }

                StringBuilder strFilters = new StringBuilder();

                strFilters.Append("@FromDate= Duration_From ,");
                strFilters.Append("@ToDate= Duration_To ,");
                strFilters.Append("@EmployeeName = " + employeeName + ",");
                strFilters.Append("@LevelID=" + levelID + " ,");
                strFilters.Append("@EmployeeID=" + empId + ",");
                strFilters.Append("@EmployeeCategory=" + ddlEmpCatagory.SelectedValue + ",");
                strFilters.Append("@EmployeeType=" + ddlEmpType.SelectedValue + ",");
                strFilters.Append("@UserGroupName=" + Session["UserGroupName"].ToString() + ",");
                strFilters.Append("@GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + ",");
                strFilters.Append("@EmpAutoId=,");
                strFilters.Append("@MaxWorkPlaceIn=" + "00:01" + ",");
                //strFilters.Append("@ParentId=" + levelID + " ,");
                strFilters.Append("@PunchType= " + strPunchType);
                //strFilters.Append("@PunchType=");

                

                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 Define Function
    /// <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"]);
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);

            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
            {
                base.Message(rm.GetString("Alert_EnterValidFromDate", ci));
                e.IsValid = false;
            }
        }
        catch
        {
        }
    }

    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strTodate = txtToDate.Text;
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);

            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strTodate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Alert_EnterValidToDate", ci));
                e.IsValid = false;
            }
        }
        catch
        {            
        }
    }

    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            strTodate = txtToDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);

            DateTime dtToDate = DateTime.Parse(strTodate);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtToDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Msg_SelectvaliddatecomparewithFromdate", ci));
                e.IsValid = false;
            }
        }
        catch
        {
        }
    }

    //Getting Information from resource file and display it in label

    /// <summary>
    /// Bindings the employee category and type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        // employee category binding
        DataSet dsCategory = new DataSet();
        dsCategory = objEmployee.SelectCategoryDetailsEmployee("");
        if (dsCategory != null)
        {
            if (dsCategory.Tables[0].Rows.Count > 0)
            {
                ddlEmpCatagory.DataSource = dsCategory;
                ddlEmpCatagory.DataTextField = "CategoryName";
                ddlEmpCatagory.DataValueField = "CategoryId";
                ddlEmpCatagory.DataBind();
            }
            dsCategory.Dispose();
        }

        // employee type binding
        DataSet dsType = new DataSet();
        dsType = objEmployee.SelectTypeDetailsEmployee("");
        if (dsType != null)
        {
            if (dsType.Tables[0].Rows.Count > 0)
            {
                ddlEmpType.DataSource = dsType;
                ddlEmpType.DataTextField = "TypeName";
                ddlEmpType.DataValueField = "TypeId";
                ddlEmpType.DataBind();
            }
            dsType.Dispose();
        }
    }

    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        lblWeeklyWorkHours.Text = rm.GetString("Menu_FirstInPunchDifference", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblEmpCategory.Text = rm.GetString("Master_Category", ci);
        lblEmpType.Text = rm.GetString("Master_Type", ci);
        lblTimePeriod.Text = rm.GetString("Reports_TimePeriod", ci);
        lblFrom.Text = rm.GetString("email_FromDate", ci);
        lblTo.Text = rm.GetString("email_ToDate", ci);
    }

    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(176, 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 = true;
            }
        }
        else
        {
            btn_View.Visible = true;
            //Response.Redirect("ReportsLandingPage.aspx");
        }
    }
    #endregion
}