using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Text;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Reports_TA_UI_Report_Absentes : Base.BasePage
{
    #region Variable Declaration
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    GetReports rptEmp = new GetReports();
    Rpt_Common rptcommon = new Rpt_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    ResourceManager rm;
    cls_Common objCommon = new cls_Common();
    string strFromdate, gstrDateFormat, strTodate;
    DataSet dsEmp = new DataSet();
    CultureInfo ci;
    int intIndividualUser = 0;
    string dtFrom = "", dtTo = "";
    string empName = "", empId = "";
    int shft;
    string Level = string.Empty;
    string employeeName = string.Empty;
    int type = 0; bool blnNormal = true;
    string strEmpAutoId = "0";
    #endregion
    #region Page Load Events
    /// <summary>
    /// On page loading
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        //get the culture info to set the language     
        string source_Language;
        gvAbsent.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            //Todo: need to add below lines into main applications
            objCommon.menu("Exception Reports", "34");
            LoadStrings(ci);
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_EnterDate", ci) + "','" + rm.GetString("Alert_EnterToDate", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
            strSetAlert = strSetAlert + "</script>";
            Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
            //Set UserRights
            UserRights();
            Cache.Remove("AbsentData");
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            FillDesignation();
            // Bindings the employee category and type.
            BindingEmployeeCategoryandType();
            fillShift();
            ddlDesignation.PreRender += LB_PreRender;
            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 (Convert.ToString(Request.QueryString["Source"]) == "Email" || Request.QueryString["Source"].ToString() == "WhatsApp")
                {
                    ToShowEmailControls();
                    IDTest1.Visible = false;
                    divgraph.Visible = false;
                    if ((Request.QueryString["ScheduleId"] != null && Convert.ToString(Session["hdnReportFilters"]) == string.Empty) || (Request.QueryString["WhatsAppScheduleID"] != null && Convert.ToString(Session["hdnReportFilters"]) == string.Empty))
                    {
                        DataSet ds = new DataSet();
                        if (Request.QueryString["ScheduleId"] != null)
                        {
                            ds = rptEmp.GetEmailSchedulerFilterDetails(Convert.ToInt32(Request.QueryString["ScheduleId"]));
                        }
                        else
                        {
                            ds = rptEmp.GetWhatsAppSchedulerFilterDetails(Convert.ToInt32(Request.QueryString["WhatsAppScheduleID"]));
                        }
                        if (ds.Tables.Count > 0)
                        {
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                Session["parentLevelId_modify"] = Convert.ToString(ds.Tables[0].Rows[0]["ParentId"]);
                                txtEmployeeId.Text = Convert.ToString(ds.Tables[0].Rows[0]["empid"]);
                                txtEmployeeName.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeName"]);
                                ddlDesignation.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["DesignationID"]);
                                ddlGender.SelectedItem.Text = Convert.ToString(ds.Tables[0].Rows[0]["Gender"]);
                                ddlShift.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["shift"]);
                                ddlEmpCatagory.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeCategory"]);
                                ddlEmpType.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeType"]);
                                Session["EMailParentId"] = Convert.ToString(ds.Tables[0].Rows[0]["ParentID"]);
                                TickParticularSession(Convert.ToInt16(ds.Tables[0].Rows[0]["Session"]));
                            }
                        }
                    }
                    else
                    {
                        if (Convert.ToString(Session["hdnReportFilters"]) != string.Empty)
                        {
                            string strhdnParameters = Convert.ToString(Session["hdnReportFilters"]);
                            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];
                            }
                            ddlShift.SelectedValue = Convert.ToString(strArray1[3]);
                            txtEmployeeName.Text = Convert.ToString(strArray1[4]).Replace("~", ",");
                            txtEmployeeId.Text = Convert.ToString(strArray1[2]).Replace("~", ",");
                            ddlEmpCatagory.SelectedValue = Convert.ToString(strArray1[6]);
                            ddlEmpType.SelectedValue = Convert.ToString(strArray1[7]);
                            ddlDesignation.SelectedValue = Convert.ToString(strArray1[12]);
                            ddlGender.SelectedValue = Convert.ToString(strArray1[13]);
                            Session["EMailParentId"] = Convert.ToInt16(strArray1[11]);
                            TickParticularSession(Convert.ToInt16(strArray1[14]));
                        }
                    }
                }
            }
            else
            {
                ToShowReportFilters();
                string strScript = string.Empty;
                strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "document.getElementById('ctl00_BodyContentPH_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 = false;
            }
            if (Session["parentLevelId"] != null || Convert.ToInt16(Session["parentLevelId"]) != 0)
            {
                Session["parentLevelId"] = null;
            }
        }
        else
        {
            if (Request.QueryString["Source"] != null)
            {
                if (Convert.ToString(Request.QueryString["Source"]) == "Email")
                {
                    ToShowEmailControls();
                }
            }
            else
            {
                ToShowReportFilters();
            }
        }
        //Check whether the employee is Individual User
        intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
        if (intIndividualUser >= 1)
        {
            PlaceHolderAbsentees.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);
        strTodate = txtToDate.Text;
        strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
        if (Convert.ToString(Page.MasterPageFile) == "TA_Popup_Report_MasterPage.master")
        {
            conHeader.Visible = false;
        }
        if (Cache["AbsentData"] != null)
        {
            gvAbsent.DataSource = (DataSet)Cache["AbsentData"];
            //gvData.DataBind();
        }
    }
    private void ToShowReportFilters()
    {
        divdateTime.Visible = true;
        trView.Visible = true;
        trSave.Visible = false;
    }
    private void ToShowEmailControls()
    {
        divdateTime.Visible = false;
        trView.Visible = false;
        trSave.Visible = true;
    }
    private void TickParticularSession(int sessionValue)
    {
        switch (sessionValue)
        {
            case 0:
                rbtnAnyone.Checked = true;
                break;
            case 1:
                rbtnFH.Checked = true;
                break;
            case 2:
                rbtnSH.Checked = true;
                break;
            case 3:
                rbtnAll.Checked = true;
                break;
        }
    }
    protected void Page_PreInit(object sender, EventArgs e)
    {
        if (Request.QueryString["Source"] != null)
            this.Page.MasterPageFile = "TA_Popup_Report_MasterPage.master";
    }
    #endregion
    #region User Defined Functions
    /// <summary>
    /// Fills the designation in the drop down
    /// </summary>
    private void FillDesignation()
    {
        DataSet ds_designation = new DataSet();
        ds_designation = objEmployee.select_CommonDesignation();
        if (ds_designation != null)
        {
            if (ds_designation.Tables[0].Rows.Count > 0)
            {
                ddlDesignation.DataSource = ds_designation;
                ddlDesignation.DataTextField = "TitleName";
                ddlDesignation.DataValueField = "TitleId";
                ddlDesignation.DataBind();
            }
            ds_designation.Dispose();
            addTitle(ddlDesignation);
        }
    }

    private void addTitle(DropDownList ddl)
    {
        foreach (System.Web.UI.WebControls.ListItem item in ddl.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }

    /// <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();
            addTitle(ddlEmpCatagory);
        }
        // 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();
            addTitle(ddlEmpType);
        }
    }
    /// <summary>
    /// To fill the shift in the frop down
    /// </summary>
    public void fillShift()
    {
        ShiftEvenData getShift = new ShiftEvenData();
        DataSet ds = new DataSet();
        string strusergroup = string.Empty;
        ds = getShift.SelectShift(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), 0);
        foreach (DataRow drRow in ds.Tables[0].Rows)
        {
            switch (Convert.ToString(drRow["Shift_Name"]))
            {
                case "No Shift":
                    drRow["Shift_Name"] = rm.GetString("Caption_NoShift", ci);
                    break;
            }
        }
        if (ds.Tables[0].Rows.Count > 0)
        {
            this.ddlShift.DataSource = ds;
            this.ddlShift.DataTextField = "Shift_Name";
            this.ddlShift.DataValueField = "Shift_Id";
            this.ddlShift.DataBind();
        }
        System.Web.UI.WebControls.ListItem lstItem = new System.Web.UI.WebControls.ListItem();
        lstItem.Value = "0";
        //lstItem.Text = "All";
        lstItem.Text = rm.GetString("ExportData_All", ci);
        ddlShift.Items.Insert(0, lstItem);
        addTitle(ddlShift);
    }
    /// <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
        {            //
        }
    }
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lblFilter.Text = rm.GetString("lblFilter", ci);
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        lblAbsentReport.Text = rm.GetString("Reports_Absent_AbsentReport", ci);
        lblShift.Text = rm.GetString("Menu_Reports_Shift", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeCL", ci);
        lblEmployeeId.Text = rm.GetString("email_EmployeeCLId", 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);
        lblEmpSwipe.Text = rm.GetString("TerminalDataType_Card_No", ci);
        RequiredFieldValidator1.ErrorMessage = rm.GetString("Alert_SelectShift", ci);
        reqFromDate.ErrorMessage = rm.GetString("Alert_PleaseselectFromDate", ci);
        reqToDate.ErrorMessage = rm.GetString("Alert_PleaseselectToDate", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
        lblDesignation.Text = rm.GetString("EmployeeMaster_Designation", ci);
        lblGender.Text = rm.GetString("EmployeeMaster_Gender", ci);
        ddlGender.Items[0].Text = rm.GetString("Caption_Both", ci);
        ddlGender.Items[1].Text = rm.GetString("rbtn_EmployeeMaster_Male", ci);
        ddlGender.Items[2].Text = rm.GetString("rbtn_EmployeeMaster_Female", ci);
        ddlDesignation.Items[0].Text = rm.GetString("ExportData_All", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        lblDateFilter.Text = rm.GetString("lbl_DateFilter", ci);
        btn_Export.Text = "&nbsp;&nbsp;" + rm.GetString("btn_ExporttoExcel", ci);
        rbCustom.Text = rm.GetString("rb_Custom", ci);
        rbpreviousMonth.Text = rm.GetString("rb_PreviousMonth", ci);
        rbpreviousweek.Text = rm.GetString("rb_PreviousWeek", ci);
        rbThisMonth.Text = rm.GetString("rb_ThisMonth", ci);
        rbThisweek.Text = rm.GetString("rb_ThisWeek", ci);
        rbtnAnyone.Text = rm.GetString("rbt_Ab_AnyoneSession", ci);
        rbtnFH.Text = rm.GetString("rbt_Ab_FirstSession", ci);
        rbtnSH.Text = rm.GetString("rbt_Ab_SecondSession", ci);
        rbtnAll.Text = rm.GetString("rbt_Ab_BothSession", ci);
        rbtNormalReport.Text = rm.GetString("lbl_NormalReport", ci);
        rbtGraphReport.Text = rm.GetString("lbl_GraphReport", ci);
    }
    /// <summary>
    /// To apply tooltip for the designation in the drop down
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void LB_PreRender(object sender, System.EventArgs e)
    {
        foreach (System.Web.UI.WebControls.ListItem item in ddlDesignation.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// To check the user rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(34, 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
    public void GetAndSetFieldValues()
    {
        if (txtFromDate.Text != "")
            dtFrom = strFromdate;
        if (txtToDate.Text != "")
            dtTo = strTodate;
        shft = Convert.ToInt16(this.ddlShift.SelectedValue);
        if (intIndividualUser >= 1)
        {
            empName = string.Empty;
            Level = string.Empty;
            empId = Convert.ToString(Session["EmployeeCodeId"]);
        }
        else
        {
            empName = Convert.ToString(txtEmployeeName.Text);
            empId = Convert.ToString(txtEmployeeId.Text.Trim());
            employeeName = this.txtEmployeeName.Text.Replace("'", "''");
            Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        }
        if (rbtnFH.Checked == true)
            type = 1;
        else if (rbtnSH.Checked == true)
            type = 2;
        else if (rbtnAll.Checked == true)
            type = 3;
        if (rbtNormalReport.Checked == true)
            blnNormal = true;
        else
            blnNormal = false;
        if (Session["ReportsBasedOn"] != null)
        {
            if (Convert.ToString(Session["ReportsBasedOn"]) == "False")
                strEmpAutoId = "0";
            else
                strEmpAutoId = Convert.ToString(Session["EmpAutoID"]);
        }
    }
    #region Button Events
    /// <summary>
    /// Load the Punchality report
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_View_Click(object sender, EventArgs e)
    {
        bool blnNormal;
        try
        {
            if (Page.IsValid == true)
            {
                GetAndSetFieldValues();
                dsEmp = GetAbsentData(strEmpAutoId);
                if (dsEmp.Tables["Table"] == null || dsEmp.Tables["Table"].Rows.Count == 0)
                {
                    Message(rm.GetString("Alert_Thereisnorecord", ci));
                    return;
                }
                else
                {
                    Session["Absent_Data"] = dsEmp;
                    string strScript = "";
                    blnNormal = true;
                    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=edge' />";
                    strScript = strScript + "<script language='javascript'>";
                    int continueAbsentDays = 0;
                    if (txtContinuousAbsentDays.Text != "") continueAbsentDays = Convert.ToInt32(txtContinuousAbsentDays.Text);
                    if (rbtNormalReport.Checked == true)
                        strScript = strScript + "window.open('TA_UI_Report_ReportViewer.aspx?ReportName=Absentees&dtFrom=" + dtFrom + "&dtTo=" + dtTo + "&empid=" + empId + "&shft=" + shft + "&EmpName=" + employeeName + "&Level=" + Level + "&EmpCategory=" + Convert.ToInt32(ddlEmpCatagory.SelectedValue) + "&EmpType=" + Convert.ToInt32(ddlEmpType.SelectedValue) + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]) + "&UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + "&GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + "&Normal=" + blnNormal + "&SwipeCard=" + Convert.ToString(txtSwipeCard.Text).Trim().Replace("'", "''") + "&Designation=" + Convert.ToInt32(ddlDesignation.SelectedValue) + "&Gender=" + ddlGender.SelectedValue + "&ContAbsentDays=" + continueAbsentDays + "&absentType=" + type + "','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
                    else
                    {
                        DataTable dtLevelName = new DataTable();
                        if (Convert.ToInt16(Session["parentLevelId"]) != 0)
                            dtLevelName = rptEmp.getHeader(Convert.ToInt16(Session["parentLevelId"]));
                        string strreportHeader = "";
                        if (dtLevelName.Rows.Count > 0)
                            strreportHeader = Convert.ToString(dtLevelName.Rows[0][0]);
                        else
                            strreportHeader = "";
                        strScript = strScript + "window.open('TA_UI_Report_Graphical_View.aspx?ReportName=Absentees&dtFrom=" + Convert.ToString(txtFromDate.Text) + "&dtTo=" + Convert.ToString(txtToDate.Text) + "&empid=" + empId + "&shft=" + shft + "&EmpName=" + employeeName + "&Level=" + Level + "&EmpCategory=" + Convert.ToInt32(ddlEmpCatagory.SelectedValue) + "&EmpType=" + Convert.ToInt32(ddlEmpType.SelectedValue) + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]) + "&UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + "&GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + "&SwipeCard=" + Convert.ToString(txtSwipeCard.Text).Trim().Replace("'", "''") + "&Designation=" + Convert.ToInt32(ddlDesignation.SelectedValue) + "&ContAbsentDays=" + continueAbsentDays + "&Gender=" + ddlGender.SelectedValue + "&absentType=" + type + "&ReportHeaderName=" + strreportHeader + "','','left=10px, top=60px, width=1200px, height=600px, scrollbars=yes, status=no, resizable=yes');";
                    }
                    strScript = strScript + "</script>";
                    Response.Write(strScript);
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());       //
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid == true)
            {
                GetAndSetFieldValues();
                if (Level.Contains(","))
                    Level = Level.Replace(",", "~");
                if (employeeName.Contains(","))
                    employeeName = employeeName.Replace(",", "~");
                if (empId.Contains(","))
                    empId = empId.Replace(",", "~");
                StringBuilder strFilters = new StringBuilder();
                strFilters.Append("@fromDat=" + " Duration_From " + ",");
                strFilters.Append("@ToDat=" + " Duration_To " + ",");
                strFilters.Append("@empId=" + empId + ",");
                strFilters.Append("@shift=" + ddlShift.SelectedValue + ",");
                strFilters.Append("@EmployeeName=" + employeeName + ",");
                strFilters.Append("@LevelID=" + "0,");
                strFilters.Append("@EmployeeCategory=" + ddlEmpCatagory.SelectedValue + ",");
                strFilters.Append("@EmployeeType=" + ddlEmpType.SelectedValue + ",");
                strFilters.Append("@UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + ",");
                strFilters.Append("@GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + ",");
                strFilters.Append("@EmpSwipeCard=" + Convert.ToString(txtSwipeCard.Text).Trim().Replace("'", "''") + ",");
                strFilters.Append("@ParentId=" + Convert.ToInt32(Session["parentLevelId"]) + ",");
                strFilters.Append("@DesignationID=" + ddlDesignation.SelectedValue + ",");
                strFilters.Append("@Gender=" + ddlGender.SelectedValue + ",");
                strFilters.Append("@session=" + type + ",");
                strFilters.Append("@EmpAutoId=0" + ",");
                strFilters.Append("@ContinueAbsentDays=" + Convert.ToString(txtContinuousAbsentDays.Text) + ",");
                strFilters.Append("@ExportType=0");
                Session["hdnReportFilters"] = string.Empty;
                Session["hdnReportFilters"] = strFilters;
                string strScript = "<script language=\"javascript\">";
                strScript = strScript + "{window.top.parent.document.getElementById('ctl00_BodyContentPH_hdnFilters').value='" + strFilters + "'; window.top.parent.document.getElementById('ctl00_BodyContentPH_hdnCompanyId').value='" + Convert.ToInt32(Session["parentLevelId"]) + "';}";
                strScript = strScript + "parent.$('#myModalReport').modal('hide');";
                strScript = strScript + "</script>";
                Response.Write(strScript);
            }
        }
        catch
        {
            //
        }
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        string strMsg;
        strMsg = "<script language='javascript'>";
        strMsg = strMsg + "parent.$('#myModalReport').modal('hide');";
        strMsg = strMsg + "</script>";
        Page.RegisterStartupScript("close report window", strMsg);
        return;
    }
    protected void btn_Export_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet dsEmp = new DataSet();
            if (Page.IsValid == true)
            {
                GetAndSetFieldValues();
                dsEmp = GetAbsentData(strEmpAutoId);
                if (dsEmp.Tables["Table"] == null || dsEmp.Tables["Table"].Rows.Count == 0)
                {
                    Message(rm.GetString("Alert_Thereisnorecord", ci));
                    return;
                }
                else
                {
                    Session["Export_ExcelData"] = dsEmp;
                    if (dsEmp.Tables[0].Columns.Contains("Name"))
                        dsEmp.Tables[0].Columns["Name"].ColumnName = "Department";
                    if (dsEmp.Tables[0].Columns.Contains("Gender"))
                        dsEmp.Tables[0].Columns.Remove("Gender");
                    Response.Redirect("Excel_Export.aspx?ReportName=Absent&FrmDate=" + Convert.ToString(txtFromDate.Text) + "&toDate=" + Convert.ToString(txtToDate.Text) + "");
                    //ExportExcel(dsEmp);
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
    private DataSet GetAbsentData(string strEmpAutoId)
    {
        int continuousAbentDays = 0;
        if (txtContinuousAbsentDays.Text != "") continuousAbentDays = Convert.ToInt32(txtContinuousAbsentDays.Text);
        return rptEmp.SelectAbsent(dtFrom, dtTo, empId, shft, employeeName, Level, Convert.ToInt32(ddlEmpCatagory.SelectedValue),
            Convert.ToInt32(ddlEmpType.SelectedValue), Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]),
            Convert.ToString(txtSwipeCard.Text).Trim().Replace("'", "''"), Convert.ToInt16(Session["parentLevelId"]), 
            Convert.ToInt32(ddlDesignation.SelectedValue), Convert.ToString(ddlGender.SelectedValue), type, Convert.ToInt64(strEmpAutoId),
            1, continuousAbentDays);
    }
    #endregion
    protected void btnExport_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = (LinkButton)sender;  //Called From  Grid Report Icon click / both excel and pdf
        ASPxGridViewExporter1.Landscape = true;
        ASPxGridViewExporter1.LeftMargin = 10;
        ASPxGridViewExporter1.RightMargin = 10;
        ASPxGridViewExporter1.ExportedRowType = DevExpress.Web.GridViewExportedRowType.All;
        ASPxGridViewExporter1.MaxColumnWidth = 400;
        ASPxGridViewExporter1.GridViewID = "gvAbsent";
        string saveAsFileName = string.Format("Absent Report -{0:d}", DateTime.Now).Replace("/", "-").Replace(" ", "");
        ASPxGridViewExporter1.FileName = saveAsFileName;
        ASPxGridViewExporter1.PaperKind = System.Drawing.Printing.PaperKind.A3;
        ASPxGridViewExporter1.PageHeader.Center = "Absent report From - " + Convert.ToString(txtFromDate.Text) + " To - " + Convert.ToString(txtToDate.Text);
        switch (lnkbtn.CommandName)
        {
            case "excel":
                ASPxGridViewExporter1.WriteXlsxToResponse();
                break;
            case "pdf":
                ASPxGridViewExporter1.WritePdfToResponse();
                break;
        }
    }
    protected void lnkbtnGrid_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid == true)
            {
                GetAndSetFieldValues();
                dsEmp = GetAbsentData(strEmpAutoId);
                if (dsEmp.Tables["Table"] == null || dsEmp.Tables["Table"].Rows.Count == 0)
                {
                    Message(rm.GetString("Alert_Thereisnorecord", ci));
                    return;
                }
                else
                {
                    gvAbsent.Visible = true;
                    gvAbsent.DataSource = dsEmp;
                    gvAbsent.DataBind();
                    Cache["AbsentData"] = dsEmp;
                    lnkbtnpdf.Visible = true;
                    lnktbnexcel.Visible = true;
                    lnbtnClear.Visible = true;
                    lblmanual.Visible = true;
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
        
    }

    private void AbsentLoadforemailnotification()
    {
        dsEmp = GetAbsentData(strEmpAutoId);
    }

    protected void lnbtnClear_Click(object sender, EventArgs e)
    {
        gvAbsent.DataSource = null;
        gvAbsent.DataBind();
        Cache.Remove("AbsentData");
        gvAbsent.Visible = false;
        lnkbtnpdf.Visible = false;
        lnktbnexcel.Visible = false;
        lblmanual.Visible = false;
        lnbtnClear.Visible = false;
        gvAbsent.FilterExpression = "";
    }
}