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 NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.HSSF.Util;
using System.Web;
using NPOI.SS.Util;
public partial class Reports_TA_UI_Report_RawData : 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();
    cls_Common objCommon = new cls_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    ResourceManager rm;
    CultureInfo ci;
    string strFromdate, gstrDateFormat, strTodate;
    int intIndividualUser = 0;
    #endregion
    #region PageLoad
    /// <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);
            objCommon.menu("Attendance Reports", "183");
        }
        //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"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        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);
        Page.RegisterStartupScript("GethiddenValue", "<script language='javascript'>GethiddenValue();</script>");
        //Set UserRights
        UserRights();
        if (!IsPostBack)
        {
            if (Session["parentLevelId"] != null || Convert.ToInt16(Session["parentLevelId"]) != 0)
            {
                Session["parentLevelId"] = null;
            }
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            BindingEmployeeCategoryandType();
            FillDesignation();
            FillDeviceIds();
            if (Request.QueryString["Source"] != null)
            {
                if (Request.QueryString["Source"].ToString() == "Email")
                {
                    divdateTime.Visible = false;
                    trView.Visible = false;
                    trSave.Visible = true;
                    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)
                            {
                                txtEmployeeName.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeName"]);
                                ddlEmpCatagory.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeCategory"]);
                                ddlDesignation.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["DesignationID"]);
                                txtEmployeeId.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeID"]);
                                ddlGender.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["Gender"]);
                                ddlEmpType.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeType"]);
                                ddlDeviceIds.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["DeviceId"]);
                                Session["EMailParentId"] = Convert.ToString(ds.Tables[0].Rows[0]["ParentID"]);
                                if (Convert.ToString(ds.Tables[0].Rows[0]["ProcessType"]) == "0")
                                {
                                    rblProcessType.Items[0].Selected = true;
                                }
                                else if (Convert.ToString(ds.Tables[0].Rows[0]["ProcessType"]) == "1")
                                {
                                    rblProcessType.Items[1].Selected = true;
                                }
                                else
                                {
                                    rblProcessType.Items[2].Selected = true;
                                }
                                //if (Convert.ToString(ds.Tables[0].Rows[0]["ReportType"]) == "0")
                                //{
                                //    rblReportType.Items[1].Selected = true;
                                //}
                                //else
                                //{
                                //    rblReportType.Items[0].Selected = true;
                                //}
                                rblReportType.SelectedValue = Convert.ToString(ds.Tables[1].Rows[0][0]);
                            }
                        }
                    }
                    else if(Request.QueryString["WhatsAppScheduleId"] !=null)
                    {
                        DataSet ds = new DataSet();
                        ds = rptEmp.GetEmailSchedulerFilterDetails(Convert.ToInt32(Request.QueryString["WhatsAppScheduleId"]));
                        if (ds.Tables.Count > 0)
                        {
                            if (ds.Tables[0].Rows.Count > 0)
                            {
                                txtEmployeeName.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeName"]);
                                ddlEmpCatagory.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeCategory"]);
                                ddlDesignation.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["DesignationID"]);
                                txtEmployeeId.Text = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeID"]);
                                ddlGender.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["Gender"]);
                                ddlEmpType.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["EmployeeType"]);
                                ddlDeviceIds.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["DeviceId"]);
                                Session["EMailParentId"] = Convert.ToString(ds.Tables[0].Rows[0]["ParentID"]);
                                if (Convert.ToString(ds.Tables[0].Rows[0]["ProcessType"]) == "0")
                                {
                                    rblProcessType.Items[0].Selected = true;
                                }
                                else if (Convert.ToString(ds.Tables[0].Rows[0]["ProcessType"]) == "1")
                                {
                                    rblProcessType.Items[1].Selected = true;
                                }
                                else
                                {
                                    rblProcessType.Items[2].Selected = true;
                                }
                                //if (Convert.ToString(ds.Tables[0].Rows[0]["ReportType"]) == "0")
                                //{
                                //    rblReportType.Items[1].Selected = true;
                                //}
                                //else
                                //{
                                //    rblReportType.Items[0].Selected = true;
                                //}
                                rblReportType.SelectedValue = Convert.ToString(ds.Tables[1].Rows[0][0]);
                            }
                        }
                    }
                    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];
                            }
                            txtEmployeeId.Text = strArray1[2].ToString().Replace("~", ",");
                            txtEmployeeName.Text = strArray1[3].ToString().Replace("~", ",");
                            ddlEmpCatagory.SelectedValue = strArray1[4].ToString();
                            ddlEmpType.SelectedValue = strArray1[5].ToString();
                            ddlDesignation.SelectedValue = Convert.ToString(strArray1[8]);
                            ddlGender.SelectedValue = Convert.ToString(strArray1[9]);
                            ddlDeviceIds.SelectedValue = Convert.ToString(strArray1[12]);
                            Session["EMailParentId"] = Convert.ToString(strArray1[7]);
                            if (Convert.ToString(strArray1[9]) == "0")
                            {
                                rblProcessType.Items[0].Selected = true;
                            }
                            else if (Convert.ToString(strArray1[9]) == "1")
                            {
                                rblProcessType.Items[1].Selected = true;
                            }
                            else
                            {
                                rblProcessType.Items[2].Selected = true;
                            }
                            if (Convert.ToString(strArray1[11]) == "0")
                            {
                                rblReportType.Items[1].Selected = true;
                            }
                            else
                            {
                                rblReportType.Items[0].Selected = true;
                            }
                        }
                    }
                }
            }
            else
            {
                divdateTime.Visible = true;
                trView.Visible = true;
                trSave.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);
            }
            ddlDesignation.PreRender += LB_PreRender;
            txtFromDate.Text = (Convert.ToDateTime(objCommon.CurrentMonthStartDate())).ToString(Session["MDateFormat"].ToString());
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
        }
        //Check whether the employee is Individual User
        intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
        if (intIndividualUser >= 1)
        {
            PlaceHolderRawData.Controls.Clear();
            divEmployeeDetails.Visible = false;
            lblEmpSwipe.Visible = false;
            txtSwipeCard.Visible = false;
        }
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        strTodate = txtToDate.Text;
        strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
        if (Page.MasterPageFile.ToString() == "TA_Popup_Report_MasterPage.master")
        {
            conHeader.Visible = false;
        }
    }
    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 function
    /// <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);
            }
        }
    }
    private void FillDeviceIds()
    {
        DataSet ds_DeviceIds = new DataSet();
        ds_DeviceIds = objEmployee.select_DevicesIds();
        if (ds_DeviceIds != null)
        {
            if (ds_DeviceIds.Tables[0].Rows.Count > 0)
            {
                ddlDeviceIds.DataSource = ds_DeviceIds;
                ddlDeviceIds.DataTextField = "DeviceId";
                ddlDeviceIds.DataValueField = "DeviceId";
                ddlDeviceIds.DataBind();
            }
            ds_DeviceIds.Dispose();
            foreach (ListItem item in ddlDeviceIds.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();
            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.ToString("MM/dd/yyyy")); ;
            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>
    /// 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>
    /// To assign the label names according to the selected language
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        lblRawData.Text = rm.GetString("Report_RawData", 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);
        lblEmpSwipe.Text = rm.GetString("TerminalDataType_Card_No", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
        reqToDate.ErrorMessage = rm.GetString("Alert_PleaseselectToDate", 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);
        lblReportType.Text = rm.GetString("EmployeeInOutReportType", ci);
        lbl_ProcessType.Text = rm.GetString("lbl_ProcessType", ci);
        lblFilter.Text = rm.GetString("lblFilter", 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);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        rblReportType.Items[0].Text = rm.GetString("rbt_RecentRawPunches", ci);
        rblReportType.Items[1].Text = rm.GetString("rbt_DetailedRawPunches", ci);
        rblProcessType.Items[0].Text = rm.GetString("ExportData_All", ci);
        rblProcessType.Items[1].Text = rm.GetString("rbt_Processed", ci);
        rblProcessType.Items[2].Text = rm.GetString("rbt_NonProcessed", ci);
        lblDeviceIds.Text = rm.GetString("lbl_DeviceIds", ci);
    }
    /// <summary>
    /// To check rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(183, 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>
    /// 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);
        }
    }
    /// <summary>
    /// Export to excel Functionality operation
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ExportExcel(DataSet dsEmp, DataTable dtLevelName)
    {
        string SheetName = "";
        if (Convert.ToString(rblReportType.SelectedValue) == "1")
        { SheetName = "Raw Data Report Recent Punches "; }
        else
        { SheetName = "Raw Data Report Detailed Punches"; }

        string NewTimeFormat = string.Empty;
        string TimeFormat = Convert.ToString(Session["ITimeFormat"]);
        if (TimeFormat == "HH:mm")
        {
            NewTimeFormat = "HH:mm";
        }
        else
        {
            NewTimeFormat = "hh:mm tt";
        }

        HSSFWorkbook workbook = new HSSFWorkbook();
        ISheet sheet = workbook.CreateSheet(SheetName);
        int rowIndex = 0;

        NPOI.SS.UserModel.IRow row = sheet.CreateRow(rowIndex);
        HSSFFont hFont = (HSSFFont)workbook.CreateFont();
        hFont.Boldweight = (short)FontBoldWeight.Bold;
        hFont.Color = HSSFColor.Maroon.Index;
        hFont.FontHeightInPoints = 10;
        HSSFCellStyle hStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        hStyle.SetFont(hFont);
        hStyle.FillForegroundColor = IndexedColors.White.Index;
        hStyle.FillPattern = FillPattern.SolidForeground;
        hStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        hStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        hStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        hStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        HSSFCellStyle MainStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        MainStyle.SetFont(hFont);
        MainStyle.Alignment = HorizontalAlignment.Center;
        HSSFCellStyle hStyle2 = (HSSFCellStyle)workbook.CreateCellStyle();
        hStyle2.SetFont(hFont);
        HSSFCellStyle IStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        IStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        IStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        IStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        IStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;

        if (dtLevelName.Rows.Count > 0)
        {
            row.CreateCell(0).SetCellValue(Convert.ToString(dtLevelName.Rows[0][0]));
            if (Convert.ToString(rblReportType.SelectedValue) == "1")
            {
                sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 7));
            }
            else
            {
                sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 7));
            }
            row.GetCell(0).CellStyle = MainStyle;
            rowIndex++;
            row = sheet.CreateRow(rowIndex);
        }
        if (Convert.ToString(rblReportType.SelectedValue) == "1")
        {
            row.CreateCell(0).SetCellValue("Raw Data Recent Punches Report From - " + Convert.ToString(txtFromDate.Text) + " To - " + Convert.ToString(txtToDate.Text));
            row.GetCell(0).CellStyle = MainStyle;
            sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 7));
            rowIndex++;
        }
        else
        {
            row.CreateCell(0).SetCellValue("Raw Data Detailed Report From - " + Convert.ToString(txtFromDate.Text) + " To - " + Convert.ToString(txtToDate.Text));
            row.GetCell(0).CellStyle = MainStyle;
            sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 7));
            rowIndex++;
        }
        row = sheet.CreateRow(rowIndex);
        rowIndex++;
        row = sheet.CreateRow(rowIndex);
        if (Convert.ToString(rblReportType.SelectedValue) == "1")
        {
            row.CreateCell(0).SetCellValue("Sl.No");
            row.CreateCell(1).SetCellValue("Card Id");
            row.CreateCell(2).SetCellValue("Employee Name");
            row.CreateCell(3).SetCellValue("Punch Date");
            row.CreateCell(4).SetCellValue("Terminal ID");
            row.CreateCell(5).SetCellValue("Punch Time");
            row.CreateCell(6).SetCellValue("Punch Type (Value)");
            row.CreateCell(7).SetCellValue("Status");
            row.CreateCell(8).SetCellValue("Remedy");

            //row.RowStyle = hStyle;
            for (int i = 0; i <= 8; i++)
            {
                row.GetCell(i).CellStyle = hStyle;
            }
            rowIndex++;
            string strPre = string.Empty; int EmployeeDatacount = 1;
            //string OldEmployeeId = "0";
            //string PreviousEmployeeId = "-1";
            //Int64 Total = 0;
            //string column = "";
            foreach (DataRow DR in dsEmp.Tables[0].Rows)
            {
                row = sheet.CreateRow(rowIndex);

                if (strPre == string.Empty || strPre != Convert.ToString(DR["Employee_Code_Id"]))
                {
                    row.CreateCell(0).SetCellValue(Convert.ToString(EmployeeDatacount));
                    EmployeeDatacount++;
                }
                else
                {
                    row.CreateCell(0).SetCellValue(string.Empty);
                }
                row.CreateCell(1).SetCellValue(Convert.ToString(DR["Employee_Code_Id"]));
                row.CreateCell(2).SetCellValue(Convert.ToString(DR["EmployeeName"]));
                row.CreateCell(3).SetCellValue(Convert.ToString(DR["PunchDate"]));
                row.CreateCell(4).SetCellValue(Convert.ToString(DR["Terminal_Name"]));
                if (Convert.ToString(DR["PunchTime"]) == String.Empty)
                    row.CreateCell(5).SetCellValue(Convert.ToString(DR["PunchTime"]));
                else
                {
                    row.CreateCell(5).SetCellValue((Convert.ToDateTime(Convert.ToString(DR["PunchTime"]))).ToString(NewTimeFormat));
                }
                row.CreateCell(6).SetCellValue(Convert.ToString(DR["PunchType"]));
                row.CreateCell(7).SetCellValue(Convert.ToString(DR["Process"]));
                if (Convert.ToString(DR["Resolution"]) == "Processed")
                    row.CreateCell(8).SetCellValue(Convert.ToString(""));
                else
                { row.CreateCell(8).SetCellValue(Convert.ToString(DR["Resolution"])); }

                strPre = Convert.ToString(DR["Employee_Code_Id"]);
                for (int i = 0; i <= 8; i++)
                {
                    row.GetCell(i).CellStyle = IStyle;
                    sheet.AutoSizeColumn(i);
                }
                rowIndex++;
            }
        }
        else
        {
            row.CreateCell(0).SetCellValue("Sl.No");
            row.CreateCell(1).SetCellValue("Card Id");
            row.CreateCell(2).SetCellValue("Employee Name");
            row.CreateCell(3).SetCellValue("Terminal Name(Terminal ID)");
            row.CreateCell(4).SetCellValue("Punch Date");
            row.CreateCell(5).SetCellValue("Punch Type (Value)");
            row.CreateCell(6).SetCellValue("Punch Time");
            row.CreateCell(7).SetCellValue("Status");
            row.CreateCell(8).SetCellValue("Remedy");

            //row.RowStyle = hStyle;
            for (int i = 0; i <= 8; i++)
            {
                row.GetCell(i).CellStyle = hStyle;
            }
            rowIndex++;
            string strPre = string.Empty; int EmployeeDatacount = 1;
            //string OldEmployeeId = "0";
            //string PreviousEmployeeId = "-1";
            //Int64 Total = 0;
            //string column = "";
            foreach (DataRow DR in dsEmp.Tables[0].Rows)
            {
                row = sheet.CreateRow(rowIndex);

                if (strPre == string.Empty || strPre != Convert.ToString(DR["Employee_Code_Id"]))
                {
                    row.CreateCell(0).SetCellValue(Convert.ToString(EmployeeDatacount));
                    EmployeeDatacount++;
                }
                else
                {
                    row.CreateCell(0).SetCellValue(string.Empty);
                }
                row.CreateCell(1).SetCellValue(Convert.ToString(DR["Employee_Code_Id"]));
                row.CreateCell(2).SetCellValue(Convert.ToString(DR["EmployeeName"]));
                row.CreateCell(3).SetCellValue(Convert.ToString(DR["Terminal_Name"]));
                row.CreateCell(4).SetCellValue(Convert.ToString(DR["PunchDate"]));
                row.CreateCell(5).SetCellValue(Convert.ToString(DR["PunchType"]));
                //row.CreateCell(6).SetCellValue(Convert.ToString(DR["PunchTime"]));
                if (Convert.ToString(DR["PunchTime"]) == String.Empty)
                    row.CreateCell(6).SetCellValue(Convert.ToString(DR["PunchTime"]));
                else
                {
                    row.CreateCell(6).SetCellValue((Convert.ToDateTime(Convert.ToString(DR["PunchTime"]))).ToString(NewTimeFormat));
                }
                row.CreateCell(7).SetCellValue(Convert.ToString(DR["Process"]));
                if (Convert.ToString(DR["Resolution"]) == "Processed")
                    row.CreateCell(8).SetCellValue(Convert.ToString(""));
                else
                { row.CreateCell(8).SetCellValue(Convert.ToString(DR["Resolution"])); }

                strPre = Convert.ToString(DR["Employee_Code_Id"]);
                for (int i = 0; i <= 8; i++)
                {
                    row.GetCell(i).CellStyle = IStyle;
                    sheet.AutoSizeColumn(i);
                }
                rowIndex++;
            }
        }

        using (MemoryStream exportData = new MemoryStream())
        {
            workbook.Write(exportData);
            string saveAsFileName;
            if (Convert.ToString(rblReportType.SelectedValue) == "1")
            { saveAsFileName = string.Format("RawDataReportRecentPunches-{0:d}.xls", DateTime.Now).Replace("/", "-"); }
            else
            { saveAsFileName = string.Format("RawDataReportDetailedPunches-{0:d}.xls", DateTime.Now).Replace("/", "-"); }
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
            Response.Clear();
            Response.BinaryWrite(exportData.GetBuffer());
            //Response.End();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
    }

    #endregion
    #region Button Event
    /// <summary>
    /// To pass the filter parameters to the report viewer page.
    /// </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 = strFromdate;
                string dtTo = strTodate;
                string Level = string.Empty;
                string employeeName = string.Empty;
                string empName = string.Empty;
                string empId = string.Empty;
                if (intIndividualUser >= 1)
                {
                    empName = string.Empty;
                    Level = string.Empty;
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    empName = txtEmployeeName.Text.ToString();
                    empId = txtEmployeeId.Text.Trim().ToString();
                    employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    employeeName = employeeName.Replace(' ', '%');
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                }

                string DeviceId = ddlDeviceIds.SelectedValue.ToString();

                if (Convert.ToString(rblReportType.SelectedValue) == "1")
                {
                    //this is for Recent Raw Punches
                    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=RawData_Latest&dtFrom=" + dtFrom + "&dtTo=" + dtTo + "&empid=" + empId + "&EmpName=" + employeeName + "&EmpCategory=" + Convert.ToInt32(ddlEmpCatagory.SelectedValue) + "&EmpType=" + Convert.ToInt32(ddlEmpType.SelectedValue) + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]).ToString() + "&UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + "&Designation=" + Convert.ToInt32(ddlDesignation.SelectedValue) + "&Gender=" + ddlGender.SelectedValue + "&RawDataDashboard=" + 1 + "&ProcessType=" + rblProcessType.SelectedValue + "&DeviceId=" + DeviceId + "','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
                    strScript = strScript + "</script>";
                    Response.Write(strScript);
                }
                else
                {
                    //this is for Detailed Raw Punches
                    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=RawData&dtFrom=" + dtFrom + "&dtTo=" + dtTo + "&empid=" + empId + "&EmpName=" + employeeName + "&EmpCategory=" + Convert.ToInt32(ddlEmpCatagory.SelectedValue) + "&EmpType=" + Convert.ToInt32(ddlEmpType.SelectedValue) + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]).ToString() + "&UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + "&Designation=" + Convert.ToInt32(ddlDesignation.SelectedValue) + "&Gender=" + ddlGender.SelectedValue + "&RawDataDashboard=" + 1 + "&ProcessType=" + rblProcessType.SelectedValue + "&DeviceId=" + DeviceId + "','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
                    strScript = strScript + "</script>";
                    Response.Write(strScript);
                }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btn_Export_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid == true)
            {
                DataSet dsRawData = new DataSet();
                string dtFrom = strFromdate;
                string dtTo = strTodate;
                string Level = string.Empty;
                string employeeName = string.Empty;
                string empName = string.Empty;
                string empId = string.Empty;
                if (intIndividualUser >= 1)
                {
                    empName = string.Empty;
                    Level = string.Empty;
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    empName = txtEmployeeName.Text.ToString();
                    empId = txtEmployeeId.Text.Trim().ToString();
                    employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    employeeName = employeeName.Replace(' ', '%');
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                }
                string DeviceId = ddlDeviceIds.SelectedValue.ToString();
                if (Convert.ToString(rblReportType.SelectedValue) == "1")
                {
                    dsRawData = rptEmp.RawData(dtFrom, dtTo, empId, employeeName, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt16(ddlEmpCatagory.SelectedValue), Convert.ToInt16(ddlEmpType.SelectedValue), Convert.ToInt32(ddlDesignation.SelectedValue), ddlGender.SelectedValue, Convert.ToInt16(rblProcessType.SelectedValue), Convert.ToInt32(Session["EmpAutoID"]), DeviceId);
                }
                else
                {
                    dsRawData = rptEmp.RawData(dtFrom, dtTo, empId, employeeName, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt16(ddlEmpCatagory.SelectedValue), Convert.ToInt16(ddlEmpType.SelectedValue), Convert.ToInt32(ddlDesignation.SelectedValue), ddlGender.SelectedValue, Convert.ToInt16(rblProcessType.SelectedValue), Convert.ToInt32(Session["EmpAutoID"]), DeviceId);
                }

                DataTable dtLevelName = new DataTable();
                if (Convert.ToInt16(Session["parentLevelId"]) != 0)
                {
                    dtLevelName = rptEmp.getHeader(Convert.ToInt16(Session["parentLevelId"]));
                }

                if (dsRawData.Tables["Table"].Rows.Count == 0)
                {
                    Message(rm.GetString("Alert_Thereisnorecord", ci));
                    return;
                }
                else
                {
                    ExportExcel(dsRawData, dtLevelName);
                    //Session["Export_ExcelData"] = dsRawData;
                    //Response.Redirect("Excel_Export.aspx?ReportName=Raw Data&FrmDate=" + Convert.ToString(txtFromDate.Text) + "&toDate=" + Convert.ToString(txtToDate.Text) + "");
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string strSwipeCard = "";
            if (Page.IsValid == true)
            {
                string dtFrom = "", dtTo = "";
                if (txtFromDate.Text != "")
                    dtFrom = strFromdate;
                if (txtToDate.Text != "")
                    dtTo = strTodate;
                string Level = string.Empty;
                string employeeName = string.Empty;
                string empName = string.Empty;
                string empId = string.Empty;
                int shift;
                if (intIndividualUser >= 1)
                {
                    empName = string.Empty;
                    Level = string.Empty;
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    empName = txtEmployeeName.Text.ToString();
                    empId = txtEmployeeId.Text.Trim().ToString();
                    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(",", "~");
                    }
                }
                int ProcessType = 0;
                if (rblProcessType.Items[0].Selected)
                {
                    ProcessType = 0;
                }
                else if (rblProcessType.Items[1].Selected)
                {
                    ProcessType = 1;
                }
                else
                {
                    ProcessType = 2;
                }
                StringBuilder strFilters = new StringBuilder();
                strFilters.Append("@FromDate=" + " Duration_From " + ",");
                strFilters.Append("@ToDate=" + " Duration_To " + ",");
                strFilters.Append("@EmployeeId=" + empId + ",");
                strFilters.Append("@EmployeeName=" + employeeName + ",");
                strFilters.Append("@employeeCategory=" + Convert.ToInt32(ddlEmpCatagory.SelectedValue) + ",");
                strFilters.Append("@employeeType=" + Convert.ToInt32(ddlEmpType.SelectedValue) + ",");
                strFilters.Append("@UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + ",");
                strFilters.Append("@ParentID=" + Convert.ToInt32(Session["parentLevelId"]) + ",");
                strFilters.Append("@DesignationID=" + ddlDesignation.SelectedValue + ",");
                strFilters.Append("@ProcessType=" + ProcessType + ",");
                strFilters.Append("@EmpAutoId=0" + ",");
                strFilters.Append("@Gender=" + ddlGender.SelectedValue + ",");
                strFilters.Append("@DeviceId=" + ddlDeviceIds.SelectedValue);
                int reporttype = rblReportType.Items[0].Selected == true ? 1 : 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"]).ToString() + "';window.top.parent.document.getElementById('ctl00_BodyContentPH_hdnReportType').value='" + reporttype + "';}";
                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;
    }

    #endregion

    protected void GetTime(object sender, EventArgs e)
    {
        //lblTime.Text = DateTime.Now.ToString("hh:mm:ss tt");
    }
}
