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;
using System.IO;

public partial class Reports_TA_UI_Report_DetailAttendance : 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();
    CultureInfo ci;
    string strFromdate, gstrDateFormat, strTodate;
    int intIndividualUser = 0;
    TimeSpan result;
    bool blnNormal;
    int intXML = 1;
    #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);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            //Todo: need to add below lines into main applications
            objCommon.menu("Attendance Reports", "30");
        }
        btn_EporttoXML.Visible = false;
        //get the culture info to set the language
        string source_Language;
        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"]);
        gvData.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        if (!IsPostBack)
        {
            UserRights();
            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);
            Cache.Remove("DetailedAttendanceData");
            //Set UserRights
            BindingEmployeeCategoryandType();
            FillDesignation();
            if (Request.QueryString["Source"] != null)
            {
                if (Convert.ToString(Request.QueryString["Source"]) == "Email")
                {
                    divdateTime.Visible = false;
                    trView.Visible = false;
                    trSave.Visible = true;
                }
            }
            else
            {
                divdateTime.Visible = true;
                trView.Visible = true;
                trSave.Visible = false;
            }
            if (Request.QueryString["ScheduleId"] != null && Convert.ToString(Session["hdnReportFilters"]) == string.Empty)
            {
                string strGet = hdnReportFilters.Value;
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "GethiddenValue();";
                strScript += " </script>";
                this.RegisterStartupScript("setScript", strScript);
                if (Request.QueryString["ScheduleId"] != null)
                {
                    DataSet ds = new DataSet();
                    ds = rptEmp.GetEmailSchedulerFilterDetails(Convert.ToInt32(Request.QueryString["ScheduleId"]));
                    if (ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            txtEmpId.Text = Convert.ToString(ds.Tables[0].Rows[0]["empid"]);
                            txtEmployeeName.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeName"]);
                            ddlEmpCatagory.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeCategory"]);
                            ddlEmpType.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeType"]);
                            txtSwipeCard.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmpSwipeCard"]);
                            ddlDesignation.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["DesignationID"]);
                            ddlGender.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["Gender"]);
                            Session["EMailParentId"] = Convert.ToString(ds.Tables[0].Rows[0]["ParentID"]);
                            //Session["parentLevelId_modify"] = Convert.ToString(ds.Tables[0].Rows[0]["ParentId"]);
                        }
                    }
                }
            }
            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];
                    }
                    txtEmployeeName.Text = Convert.ToString(strArray1[3]).Replace("~", ",");
                    txtEmpId.Text = Convert.ToString(strArray1[2]).Replace("~", ",");
                    ddlEmpCatagory.SelectedValue = Convert.ToString(strArray1[8]);
                    ddlEmpType.SelectedValue = Convert.ToString(strArray1[9]);
                    ddlDesignation.SelectedValue = Convert.ToString(strArray1[11]);
                    ddlGender.SelectedValue = Convert.ToString(strArray1[12]);
                    Session["EMailParentId"] = Convert.ToString(strArray1[10]);
                }
            }
            if (Session["parentLevelId"] != null || Convert.ToInt16(Session["parentLevelId"]) != 0)
            {
                Session["parentLevelId"] = null;
            }
            ddlDesignation.PreRender += LB_PreRender;
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            txtFromDate.Text = (Convert.ToDateTime(objCommon.CurrentMonthStartDate())).ToString(Convert.ToString(Session["MDateFormat"]));
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Convert.ToString(Session["MDateFormat"]));
        }
        else
        {
            if (Request.QueryString["Source"] != null)
            {
                if (Convert.ToString(Request.QueryString["Source"]) == "Email")
                {
                    divdateTime.Visible = false;
                    trView.Visible = false;
                    trSave.Visible = true;
                }
            }
            else
            {
                divdateTime.Visible = true;
                trView.Visible = true;
                trSave.Visible = false;
            }
        }
        //Check whether the employee is Individual User
        intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
        if (intIndividualUser >= 1)
        {
            PlaceHolderDetailedAttendance.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["DetailedAttendanceData"] != null)
        {
            gvData.DataSource = (DataSet)Cache["DetailedAttendanceData"];
            //gvData.DataBind();
        }
    }
    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
    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();
            foreach (ListItem item in ddlEmpCatagory.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
        // 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();
            foreach (ListItem item in ddlEmpType.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    /// <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);
        lblDetailedAttendanceReport.Text = rm.GetString("Reports_DetailedAttendance_DetailedAttendanceReport", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeId.Text = rm.GetString("email_EmployeeId", 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);
        reqFromDate.ErrorMessage = rm.GetString("Alert_PleaseselectFromDate", ci);
        reqToDate.ErrorMessage = rm.GetString("Alert_PleaseselectToDate", ci);
        lblDesignation.Text = rm.GetString("EmployeeMaster_Designation", ci);
        lblGender.Text = rm.GetString("EmployeeMaster_Gender", ci);
        lblEmpCategory.Text = rm.GetString("Master_Category", ci);
        lblEmpType.Text = rm.GetString("Master_Type", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", 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);
        btn_EporttoXML.Text = "&nbsp;&nbsp;" + rm.GetString("Caption_ExportToXML", 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);
    }
    /// <summary>
    /// To check rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(30, 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");
        }
    }
    /// <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();
            foreach (ListItem item in ddlDesignation.Items)
            {
                item.Attributes.Add("title", item.Text);
            }
        }
    }
    /// <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 (ListItem item in ddlDesignation.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    #endregion
    #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)
    {
        try
        {
            if (Page.IsValid == true)
            {
                string dtFrom = "", dtTo = "";
                if (txtFromDate.Text != "")
                    dtFrom = strFromdate;
                if (txtToDate.Text != "")
                    dtTo = strTodate;
                string empName = "", empId = "";
                string employeeName = string.Empty;
                string Level = string.Empty;
                if (intIndividualUser >= 1)
                {
                    empName = string.Empty;
                    Level = string.Empty;
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    empName = Convert.ToString(txtEmployeeName.Text);
                    empId = Convert.ToString(txtEmpId.Text).Trim();
                    employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                }
                blnNormal = (rbtNormalReport.Checked == true) ? true : false;
                //Redirect the page to the report viewer
                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=edge' />";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "window.open('TA_UI_Report_ReportViewer.aspx?ReportName=DetailedAttendance&dtFrom=" + dtFrom + "&dtTo=" + dtTo + "&empid=" + empId + "&shft=0&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=" + txtSwipeCard.Text.Trim() + "&Designation=" + Convert.ToInt32(ddlDesignation.SelectedValue) + "&Gender=" + ddlGender.SelectedValue + "','','left=10px, top=60px, width=1000px, 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)
            {
                string empName = "", empId = "";
                string employeeName = string.Empty;
                string Level = string.Empty;
                if (intIndividualUser >= 1)
                {
                    empName = string.Empty;
                    Level = string.Empty;
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    empName = Convert.ToString(txtEmployeeName.Text);
                    empId = Convert.ToString(txtEmpId.Text).Trim();
                    employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                    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("@EmployeeName=" + employeeName + ",");
                strFilters.Append("@LevelID=" + Level + ",");
                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("@EmployeeCategory=" + ddlEmpCatagory.SelectedValue + ",");
                strFilters.Append("@EmployeeType=" + ddlEmpType.SelectedValue + ",");
                strFilters.Append("@ParentId=" + Convert.ToInt32(Session["parentLevelId"]) + ",");
                strFilters.Append("@DesignationID=" + ddlDesignation.SelectedValue + ",");
                strFilters.Append("@EmpAutoId=0,");
                strFilters.Append("@Gender=" + ddlGender.SelectedValue);
                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 + "self.close();";
                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 dsDetailedAttendanceData = new DataSet();
            if (Page.IsValid == true)
            {
                dsDetailedAttendanceData = GetDataFromDatabase();
                DataTable dtLevelName = new DataTable();
                if (Convert.ToInt16(Session["parentLevelId"]) != 0)
                {
                    dtLevelName = rptEmp.getHeader(Convert.ToInt16(Session["parentLevelId"]));
                }
                if (dsDetailedAttendanceData.Tables["Table"] == null || dsDetailedAttendanceData.Tables["Table"].Rows.Count == 0)
                {
                    Message(rm.GetString("Alert_Thereisnorecord", ci));
                    return;
                }
                else
                {
                    ToRemoveUnknownColumns(dsDetailedAttendanceData);
                    Session["Export_ExcelData"] = dsDetailedAttendanceData;
                    Response.Redirect("Excel_Export.aspx?ReportName=Detailed Attendance&FrmDate=" + Convert.ToString(txtFromDate.Text) + "&toDate=" + Convert.ToString(txtToDate.Text) + "");
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }

    private DataSet GetDataFromDatabase()
    {
        DataSet dsEmp = new DataSet();
        int payrollConfig = 0;
        string strEmpAutoId = "";
        if (Session["ReportsBasedOn"] != null)
        {
            if (Convert.ToString(Session["ReportsBasedOn"]) == "False")
            {
                strEmpAutoId = "0";
            }
            else
            {
                strEmpAutoId = Convert.ToString(Session["EmpAutoID"]);
            }
        }
        string dtFrom = "", dtTo = "";
        if (txtFromDate.Text != "")
            dtFrom = strFromdate;
        if (txtToDate.Text != "")
            dtTo = strTodate;
        string empName = "", empId = "";
        string employeeName = string.Empty;
        string Level = string.Empty;
        if (intIndividualUser >= 1)
        {
            empName = string.Empty;
            Level = string.Empty;
            empId = Convert.ToString(Session["EmployeeCodeId"]);
        }
        else
        {
            empName = Convert.ToString(txtEmployeeName.Text);
            empId = Convert.ToString(txtEmpId.Text).Trim();
            employeeName = this.txtEmployeeName.Text.Replace("'", "''");
            Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        }
        blnNormal = (rbtNormalReport.Checked == true) ? true : false;
        //Create the datatable ,that holds the header information
        payrollConfig = objCommon.CheckPageExistsInLicense(185);
        /*Below parameter is used for Angler*/
        if (payrollConfig == 0)
        {
            dsEmp = rptEmp.SelectDetailAttend(dtFrom, dtTo, empId, employeeName, Level, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), txtSwipeCard.Text, Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt32(ddlDesignation.SelectedValue), ddlGender.SelectedValue, Convert.ToInt16(ddlEmpCatagory.SelectedValue), Convert.ToInt32(ddlEmpType.SelectedValue), Convert.ToInt32(Session["EmpAutoID"]));
        }
        else
        {
            dsEmp = rptEmp.SelectDetailAttend_Old(dtFrom, dtTo, empId, employeeName, Level, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), txtSwipeCard.Text, Convert.ToInt64(strEmpAutoId), Convert.ToInt32(ddlDesignation.SelectedValue), ddlGender.SelectedValue, Convert.ToInt16(Session["parentLevelId"]), 1);
        }
        return dsEmp;
    }

    protected void btn_XMl_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet dsEmp = new DataSet();
            string strEmpAutoId = "0";
            if (Page.IsValid == true)
            {
                if (Session["ReportsBasedOn"] != null)
                {
                    if (Convert.ToString(Session["ReportsBasedOn"]) == "False")
                    {
                        strEmpAutoId = "0";
                    }
                    else
                    {
                        strEmpAutoId = Convert.ToString(Session["EmpAutoID"]);
                    }
                }
                string dtFrom = "", dtTo = "";
                if (txtFromDate.Text != "")
                    dtFrom = strFromdate;
                if (txtToDate.Text != "")
                    dtTo = strTodate;
                string empName = "", empId = "";
                string employeeName = string.Empty;
                string Level = string.Empty;
                if (intIndividualUser >= 1)
                {
                    empName = string.Empty;
                    Level = string.Empty;
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    empName = Convert.ToString(txtEmployeeName.Text);
                    empId = Convert.ToString(txtEmpId.Text).Trim();
                    employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                }
                if (rbtNormalReport.Checked == true)
                {
                    blnNormal = true;
                }
                else
                {
                    blnNormal = false;
                }
                //Create the datatable ,that holds the header information
                dsEmp = rptEmp.Select_DetailAttendanceforExportTally(dtFrom, dtTo, empId, employeeName, Level, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), txtSwipeCard.Text, Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt32(ddlDesignation.SelectedValue), ddlGender.SelectedValue, Convert.ToInt16(ddlEmpCatagory.SelectedValue), Convert.ToInt32(ddlEmpType.SelectedValue), Convert.ToInt32(Session["EmpAutoID"]));
                DataTable dtLevelName = new DataTable();
                if (Convert.ToInt16(Session["parentLevelId"]) != 0)
                {
                    dtLevelName = rptEmp.getHeader(Convert.ToInt16(Session["parentLevelId"]));
                }
                //dsEmp = rptEmp.SelectDetailAttend(dtFrom, dtTo, empId, employeeName, Level, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), txtSwipeCard.Text, Convert.ToInt64(strEmpAutoId), Convert.ToInt32(ddlDesignation.SelectedValue), ddlGender.SelectedValue, Convert.ToInt16(Session["parentLevelId"]), 1);
                if (dsEmp.Tables["Table"] == null || dsEmp.Tables["Table"].Rows.Count == 0)
                {
                    string strMsg;
                    strMsg = "<script language='javascript'>";
                    strMsg = strMsg + "alert('" + rm.GetString("Alert_Thereisnorecord", ci) + "');window.close();";
                    strMsg = strMsg + "</script>";
                    Page.RegisterStartupScript("Display Message", strMsg);
                    return;
                }
                else
                {
                    string strXML = string.Empty;
                    strXML = "<ENVELOPE><HEADER><TALLYREQUEST>Import Data</TALLYREQUEST></HEADER><BODY><IMPORTDATA><REQUESTDATA>";
                    intXML = 1;
                    foreach (DataRow DR in dsEmp.Tables[0].Rows)
                    {
                        strXML = strXML + "<TALLYMESSAGE xmlns:UDF=\"TallyUDF\"><VOUCHER><DATE>" + Convert.ToDateTime(dtFrom).ToString("yyyyMMdd") + "</DATE><EFFECTIVEDATE>" + Convert.ToDateTime(dtTo).ToString("yyyyMMdd") + "</EFFECTIVEDATE><VOUCHERTYPENAME>Attendance</VOUCHERTYPENAME><VOUCHERNUMBER>" + Convert.ToString(intXML) + "</VOUCHERNUMBER><ATTENDANCEENTRIES.LIST><NAME>" + Convert.ToString(DR["Employee Name"]) + "</NAME><ATTENDANCETYPE>Absent</ATTENDANCETYPE><ATTDTYPETIMEVALUE>" + Convert.ToString(DR["Absent"]) + "</ATTDTYPETIMEVALUE></ATTENDANCEENTRIES.LIST><ATTENDANCEENTRIES.LIST><NAME>" + Convert.ToString(DR["Employee Name"]) + "</NAME><ATTENDANCETYPE>WeeklyOff</ATTENDANCETYPE><ATTDTYPETIMEVALUE>" + Convert.ToString(DR["WeeklyOff"]) + "</ATTDTYPETIMEVALUE></ATTENDANCEENTRIES.LIST><ATTENDANCEENTRIES.LIST><NAME>" + Convert.ToString(DR["Employee Name"]) + "</NAME><ATTENDANCETYPE>Holiday</ATTENDANCETYPE><ATTDTYPETIMEVALUE>" + Convert.ToString(DR["Holiday"]) + "</ATTDTYPETIMEVALUE></ATTENDANCEENTRIES.LIST><ATTENDANCEENTRIES.LIST><NAME>" + Convert.ToString(DR["Employee Name"]) + "</NAME><ATTENDANCETYPE>Leave</ATTENDANCETYPE><ATTDTYPETIMEVALUE>" + Convert.ToString(DR["Leave"]) + "</ATTDTYPETIMEVALUE></ATTENDANCEENTRIES.LIST><ATTENDANCEENTRIES.LIST><NAME>" + Convert.ToString(DR["Employee Name"]) + "</NAME><ATTENDANCETYPE>LOP</ATTENDANCETYPE><ATTDTYPETIMEVALUE>" + Convert.ToString(DR["LOP"]) + "</ATTDTYPETIMEVALUE></ATTENDANCEENTRIES.LIST><ATTENDANCEENTRIES.LIST><NAME>" + Convert.ToString(DR["Employee Name"]) + "</NAME><ATTENDANCETYPE>OverTime</ATTENDANCETYPE><ATTDTYPEVALUE>" + Convert.ToString(DR["Total OT Hours"]) + "</ATTDTYPEVALUE></ATTENDANCEENTRIES.LIST><ATTENDANCEENTRIES.LIST><NAME>" + Convert.ToString(DR["Employee Name"]) + "</NAME><ATTENDANCETYPE>Present</ATTENDANCETYPE><ATTDTYPETIMEVALUE>" + Convert.ToString(DR["Present"]) + "</ATTDTYPETIMEVALUE></ATTENDANCEENTRIES.LIST></VOUCHER></TALLYMESSAGE>";
                        intXML = intXML + 1;
                    }
                    strXML = strXML + "</REQUESTDATA></IMPORTDATA></BODY></ENVELOPE>";
                    //XmlDocument xmlDoc = new XmlDocument();
                    //xmlDoc.LoadXml(strXML);
                    string strFilePath = Server.MapPath("Uploads").ToString();
                    File.WriteAllText(strFilePath + "/DayBook.xml", strXML);
                    string strFullPath = strFilePath + "/DayBook.xml";
                    string strContents = null;
                    System.IO.StreamReader objReader = default(System.IO.StreamReader);
                    objReader = new System.IO.StreamReader(strFullPath);
                    strContents = objReader.ReadToEnd();
                    objReader.Close();
                    string attachment = "attachment; filename=DayBook.xml";
                    Response.ClearContent();
                    Response.ContentType = "application/xml";
                    Response.AddHeader("content-disposition", attachment);
                    Response.Write(strContents);
                    Response.End();

                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
            //Response.Write(ex);
        }
    }
    #endregion

    protected void lnkbtnGrid_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet dsDetailedAttendanceData = new DataSet();
            if (Page.IsValid == true)
            {
                dsDetailedAttendanceData = GetDataFromDatabase();
                if (dsDetailedAttendanceData.Tables["Table"] == null || dsDetailedAttendanceData.Tables["Table"].Rows.Count == 0)
                {
                    Message(rm.GetString("Alert_Thereisnorecord", ci));
                    return;
                }
                else
                {
                    ToRemoveUnknownColumns(dsDetailedAttendanceData);
                    Cache["DetailedAttendanceData"] = dsDetailedAttendanceData;
                    gvData.Visible = true;
                    lnkbtnExpand.Visible = true;
                    lnkbtnCollapse.Visible = true;
                    BindCaption(dsDetailedAttendanceData);
                    btnCustWindow.Visible = true;
                    lnktbnexcel.Visible = true;
                    lnkbtnpdf.Visible = true;
                    lnbtnClear.Visible = true;
                    gvData.SettingsText.Title = "Detailed Attendance Report : " + txtFromDate.Text + " - " + txtToDate.Text;
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }

    private void BindCaption(DataSet dsEmp)
    {
        //dynamic report
        int iField = 1;
        int iInc = 0;
        DataTable dtHeaderLabel = new DataTable();
        dtHeaderLabel.TableName = "HeaderLabels";
        int iDiff = 0;
        if (dsEmp.Tables[0].Columns.Count < 33)
        {
            iDiff = (33 - dsEmp.Tables[0].Columns.Count);
            for (int iDum = 0; iDum < iDiff; iDum++)
            {
                dsEmp.Tables[0].Columns.Add(new DataColumn("iField" + iInc, System.Type.GetType("System.String")));
                iInc = iInc + 1;
            }
        }
        DataRow dsRow = dtHeaderLabel.NewRow();
        int iIcont = 1;
        for (int iRow = 0; iRow < dsEmp.Tables[0].Columns.Count; iRow++)
        {
            dtHeaderLabel.Columns.Add(new DataColumn("Header" + iIcont, System.Type.GetType("System.String")));
            if (dsEmp.Tables[0].Columns[iRow].ColumnName != "Others")
            {
                dsRow[iRow] = dsEmp.Tables[0].Columns[iRow].ColumnName;
            }
            else if (dsEmp.Tables[0].Columns[iRow].ColumnName == "Others")
            {
                dsRow[iRow] = rm.GetString("Employee_Others", ci);
            }
            iIcont = iIcont + 1;
        }
        dtHeaderLabel.Rows.InsertAt(dsRow, 0);
        for (int iCol = 23; iCol < dsEmp.Tables[0].Columns.Count; iCol++)
        {
            dsEmp.Tables[0].Columns[iCol].ColumnName = "Field" + iField;
            iField = iField + 1;
        }
        gvData.DataSource = dsEmp;
        gvData.DataBind();
        ApplyLayout(0);
        for (int iCol = 23; iCol < dtHeaderLabel.Columns.Count; iCol++)
        {
            gvData.Columns[iCol].Caption = dtHeaderLabel.Rows[0][iCol].ToString();
        }
        for (int i = (33 - iDiff); i < 33; i++)
        {
            gvData.Columns[i].Visible = false;
        }
    }

    private static void ToRemoveUnknownColumns(DataSet dsDetailedAttendanceData)
    {
        if (dsDetailedAttendanceData.Tables[0].Columns.Contains("SwipeCardNo"))
        {
            dsDetailedAttendanceData.Tables[0].Columns.Remove("SwipeCardNo");
        }
        if (dsDetailedAttendanceData.Tables[0].Columns.Contains("Gender"))
        {
            dsDetailedAttendanceData.Tables[0].Columns.Remove("Gender");
        }
        if (dsDetailedAttendanceData.Tables[0].Columns.Contains("WD Spec.OT1"))
        {
            dsDetailedAttendanceData.Tables[0].Columns.Remove("WD Spec.OT1");
        }
        if (dsDetailedAttendanceData.Tables[0].Columns.Contains("WD Spec.OT2"))
        {
            dsDetailedAttendanceData.Tables[0].Columns.Remove("WD Spec.OT2");
        }
        if (dsDetailedAttendanceData.Tables[0].Columns.Contains("WO Spec.OT1"))
        {
            dsDetailedAttendanceData.Tables[0].Columns.Remove("WO Spec.OT1");
        }
        if (dsDetailedAttendanceData.Tables[0].Columns.Contains("WO Spec.OT2"))
        {
            dsDetailedAttendanceData.Tables[0].Columns.Remove("WO Spec.OT2");
        }
        if (dsDetailedAttendanceData.Tables[0].Columns.Contains("H Spec.OT1"))
        {
            dsDetailedAttendanceData.Tables[0].Columns.Remove("H Spec.OT1");
        }
        if (dsDetailedAttendanceData.Tables[0].Columns.Contains("H Spec.OT2"))
        {
            dsDetailedAttendanceData.Tables[0].Columns.Remove("H Spec.OT2");
        }
    }

    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;
        string saveAsFileName = string.Format("Detailed Attendance Report -{0:d}", DateTime.Now).Replace("/", "-").Replace(" ", "");
        ASPxGridViewExporter1.FileName = saveAsFileName;
        ASPxGridViewExporter1.PaperKind = System.Drawing.Printing.PaperKind.A3;

        //ASPxGridViewExporter1.PageHeader.Center = "Detailed Attendance 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 lnbtnClear_Click(object sender, EventArgs e)
    {
        gvData.DataSource = null;
        gvData.DataBind();
        Cache.Remove("DetailedAttendanceData");
        gvData.Visible = false;
        lnkbtnpdf.Visible = false;
        lnktbnexcel.Visible = false;
        lblmanual.Visible = false;
        lnbtnClear.Visible = false;
        lnkbtnExpand.Visible = false;
        lnkbtnCollapse.Visible = false;
        btnCustWindow.Visible = false;
        gvData.FilterExpression = "";
    }
    void ApplyLayout(int layoutIndex)
    {
        gvData.BeginUpdate();
        try
        {
            gvData.ClearSort();
            switch (layoutIndex)
            {
                case 0:
                    gvData.GroupBy(gvData.Columns["Month"]);
                    break;
                case 1:
                    gvData.GroupBy(gvData.Columns["Employee Id"]);
                    gvData.GroupBy(gvData.Columns["Month"]);
                    break;
                case 2:                    
                    gvData.GroupBy(gvData.Columns["Month"]);
                    gvData.GroupBy(gvData.Columns["Employee Id"]);
                    break;
                case 3:
                    gvData.GroupBy(gvData.Columns["Employee Id"]);
                    gvData.GroupBy(gvData.Columns["Month"]);
                    gvData.GroupBy(gvData.Columns["Shift Name"]);
                    break;
                case 4:
                    gvData.GroupBy(gvData.Columns["Month"]);
                    gvData.GroupBy(gvData.Columns["Employee Id"]);
                    gvData.GroupBy(gvData.Columns["Shift Name"]);
                    break;
            }
        }
        finally
        {
            gvData.EndUpdate();
        }
        gvData.ExpandAll();
    }

    protected void gvData_CustomCallback(object sender, DevExpress.Web.ASPxGridViewCustomCallbackEventArgs e)
    {
        ApplyLayout(Int32.Parse(e.Parameters));
    }
}
