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 NPOI.HSSF.Util;
using NPOI.SS.Util;
using System.IO;
public partial class Reports_TA_UI_Report_Summary : 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();
    string strFromdate, gstrDateFormat, strTodate;
    ResourceManager rm;
    CultureInfo ci;
    int intIndividualUser = 0;
    double PFS, PSS, AFS, ASS, LFS, LSS, LOPFS, LOPSS, TotalEmployee = 0.0;
    #endregion
    #region Page Load Events
    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", "118");
        }
        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 + "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") + "','" + rm.GetString("Alert_Invalidtimeformat1") + "','" + rm.GetString("Alert_PleaseentervalidDateandTime") + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM") + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT") + "','" + rm.GetString("Alert_PleaseentervalidDateandTime") + "','" + rm.GetString("Alert_Invalidvalueforhours") + "','" + rm.GetString("Alert_Invalidvalueforminites") + "','" + rm.GetString("Alert_SelectFromDate") + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        //Set UserRights
        UserRights();
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        if (!IsPostBack)
        {
            if (Request.QueryString["Source"] != null)
            {
                if (Request.QueryString["Source"].ToString() == "Email")
                {
                    trView.Visible = false;
                    rbtNormalReport.Visible = false;
                    rbtGraphReport.Visible = false;
                    trSave.Visible = true;
                    string strScript = "";
                    strScript = strScript + "<script language='javascript'>";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_divMenu').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div1').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div2').style.display = 'none';";
                    strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div3').style.display = 'none';";
                    strScript = strScript + "document.getElementById('trView').style.display = 'none';";
                    strScript = strScript + "document.getElementById('trSave').style.display = 'block';";
                    strScript = strScript + "</script>";
                    Page.RegisterStartupScript("Script", strScript);
                }
            }
            else
            {
                trView.Visible = true;
                trSave.Visible = false;
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "document.getElementById('trSave').style.display = 'none';";
                strScript = strScript + "document.getElementById('trView').style.display = 'block';";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Script", strScript);
                strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "document.getElementById('ctl00_BodyContentPH_Modifylevel').style.display = 'none';";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Script", strScript);
            }
            if (Session["parentLevelId"] != null || Convert.ToInt16(Session["parentLevelId"]) != 0)
            {
                Session["parentLevelId"] = null;
            }
            txtFromDate.Text = Session["SearchFromDate"].ToString();
            txtFromDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
            fillShift();
            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);
                DataSet ds = new DataSet();
                ds = rptEmp.GetEmailSchedulerFilterDetails(Convert.ToInt32(Request.QueryString["ScheduleId"]));
                if (ds.Tables.Count > 0)
                {
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        ddlShift.SelectedValue = Convert.ToString(ds.Tables[0].Rows[0]["shiftid"]);
                        //txtFromDate.Text = Convert.ToString(ds.Tables[0].Rows[0]["Date"]);
                        Session["parentLevelId_modify"] = Convert.ToString(ds.Tables[0].Rows[0]["ParentId"]);
                        Session["EMailParentId"] = 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];
                    }
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    //txtFromDate.Text = objCommon.DateConvertion(gstrDateFormat, strArray1[0].ToString());
                    ddlShift.SelectedValue = strArray1[1].ToString();
                    Session["EMailParentId"] = Convert.ToString(strArray1[3]);
                }
            }
        }
        else
        {
            if (Request.QueryString["Source"] != null)
            {
                if (Request.QueryString["Source"].ToString() == "Email")
                {
                    string strScript = "";
                    strScript = strScript + "<script language='javascript'>";
                    strScript = strScript + "document.getElementById('trView').style.display = 'none';";
                    strScript = strScript + "document.getElementById('trSave').style.display = 'block';";
                    strScript = strScript + "</script>";
                    Page.RegisterStartupScript("Script", strScript);
                }
            }
            else
            {
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "document.getElementById('trView').style.display = 'block';";
                strScript = strScript + "document.getElementById('trSave').style.display = 'none';";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Script", strScript);
            }
        }
        //Check whether the employee is Individual User
        intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
        if (intIndividualUser >= 1)
        {
            PlaceHolderSecretariatSummary.Controls.Clear();
        }
        //Convert date time to MM/dd/YYYY format
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        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 Functions
    /// <summary>
    /// Validate the FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            strFromdate = txtFromDate.Text;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            //strCurrentDate = objCommon.DateConvertion(gstrDateFormat,DateTime.Today.Date.ToString());
            strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
            //strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            //DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date.ToString("MM/dd/yyyy")); ;
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
            {
                //base.Message("Enter Valid From Date");
                e.IsValid = false;
            }
        }
        catch
        {
            //
        }
    }
    /// <summary>
    /// Getting Information from resource file and display it in label
    /// </summary>    
    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        lblSummary.Text = rm.GetString("Report_SummaryReport", ci);
        lblDate.Text = rm.GetString("Reports_Date", ci);
        lblShift.Text = rm.GetString("Menu_Reports_Shift", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Cancel", ci);
        btn_Export.Text = "&nbsp;&nbsp;" + rm.GetString("btn_ExporttoExcel", ci);
        rbtNormalReport.Text = rm.GetString("lbl_NormalReport", ci);
        rbtGraphReport.Text = rm.GetString("lbl_GraphReport", ci);

    }
    /// <summary>
    /// Setting user rights
    /// </summary>    
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(118, 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>
    /// Load Shift Dropdown
    /// </summary>
    public void fillShift()
    {
        ShiftEvenData getShift = new ShiftEvenData();
        DataSet ds = new DataSet();
        string strusergroup = string.Empty;
        //ds = getShift.SelectShift(strusergroup, Convert.ToString(Session["LevelRights"]));
        ds = getShift.SelectShift(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), 0);
        foreach (DataRow drRow in ds.Tables[0].Rows)
        {
            switch (drRow["Shift_Name"].ToString())
            {
                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();
        }
        foreach (ListItem item in ddlShift.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
        //ListItem lstItem = new ListItem();
        //lstItem.Value = "0";
        ////lstItem.Text = "All";
        //lstItem.Text = rm.GetString("ExportData_All", ci);
        //ddlShift.Items.Insert(0, lstItem);
    }
    #endregion
    #region Button Events
    /// <summary>
    /// Button click event
    /// </summary>
    protected void btn_View_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid == true)
            {
                string dtFrom = strFromdate;
                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
                {
                    employeeName = employeeName.Replace(' ', '%');
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                }
                DataSet dsSecretariatSummary = new DataSet();
                dsSecretariatSummary = rptEmp.SelectSummaryReportCount(dtFrom, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]));
                int intReportCount = 0;
                if (dsSecretariatSummary.Tables["Table"].Rows.Count > 0)
                {
                    intReportCount = Convert.ToInt32(dsSecretariatSummary.Tables["Table"].Rows[0]["ReportCount"]);
                }
                //Check the Empty table
                if (dsSecretariatSummary.Tables["Table"].Rows.Count == 0 || intReportCount == 0)
                {
                    string strMsg;
                    strMsg = "<script language='javascript'>";
                    strMsg = strMsg + "alert('" + rm.GetString("Alert_Thereisnorecord", ci) + "');";
                    strMsg = strMsg + "</script>";
                    Page.RegisterStartupScript("Display Message", strMsg);
                    return;
                }
                string strReportType = string.Empty;
                if (rbtnDetails.Checked == true)
                {
                    strReportType = "DetailsReport";
                }
                else if (rbtnSummary.Checked == true)
                {
                    strReportType = "SummaryReport";
                }
                strReportType = "SummaryReport";
                //Redirect the page to the report viewer
                if (rbtNormalReport.Checked == true)
                {
                    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'>";
                    Level = "";
                    strScript = strScript + "window.open('TA_UI_Report_ReportViewer.aspx?ReportName=SummaryReport&dtFrom="
                        + dtFrom + "&Shft=" + Convert.ToInt32(ddlShift.SelectedValue) + "&empid=" + empId + "&EmpName=" + employeeName + "&Level=" + Level + "&EmpCategory=" + 0
                        + "&EmpType=" + 0 + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]).ToString() + "&UserGroupName="
                        + Convert.ToString(Session["UserGroupName"]) + "&ReportType=" + strReportType.ToString() + "&GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + "&SwipeCard=" + ""
                        + "','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
                    strScript = strScript + "</script>";
                    Response.Write(strScript);
                }
                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 = "";
                    }
                    //string strMsg = "";
                    //strMsg = "<script language='javascript'>";
                    //strMsg = strMsg + "window.location.href=\"TA_UI_Report_Graphical_View.aspx?ReportName=SummaryReport&dtFrom=" 
                    //    + Convert.ToString(txtFromDate.Text)  + "&empid=" + empId + "&shft=" + Convert.ToInt32(ddlShift.SelectedValue) + "&EmpName=" + employeeName 
                    //    + "&Level=" + Level + "&EmpCategory=" + 0 + "&EmpType=" 
                    //    + 0 + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]) 
                    //    + "&UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + "&GradeLevel=" 
                    //    + Convert.ToString(Session["GradeLevel"]) + "&SwipeCard=" 
                    //    + "" + "&ReportHeaderName=" + strreportHeader + "\"";
                    //strMsg = strMsg + "</script>";
                    //Page.RegisterStartupScript("Display Message", strMsg);


                    //iframePopup.Attributes.Add("src", "TA_UI_Report_Graphical_View.aspx?ReportName=SummaryReport&dtFrom="
                    //    + Convert.ToString(txtFromDate.Text) + "&empid=" + empId + "&shft=" + Convert.ToInt32(ddlShift.SelectedValue) + "&EmpName=" + employeeName
                    //    + "&Level=" + Level + "&EmpCategory=" + 0 + "&EmpType="
                    //    + 0 + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"])
                    //    + "&UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + "&GradeLevel="
                    //    + Convert.ToString(Session["GradeLevel"]) + "&SwipeCard="
                    //    + "" + "&ReportHeaderName=" + strreportHeader + "");
                    //string strSetAlert1 = "";
                    //strSetAlert1 = strSetAlert1 + "<script language='javascript'>";
                    //strSetAlert1 = strSetAlert1 + "OpenPop();";
                    //strSetAlert1 = strSetAlert1 + "</script>";
                    //Page.RegisterStartupScript("SetAlertMessagesx", strSetAlert1);


                    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_Graphical_View.aspx?ReportName=SummaryReport&dtFrom="
                        + Convert.ToString(txtFromDate.Text) + "&empid=" + empId + "&shft=" + Convert.ToInt32(ddlShift.SelectedValue) + "&EmpName=" + employeeName
                        + "&Level=" + Level + "&EmpCategory=" + 0 + "&EmpType="
                        + 0 + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"])
                        + "&UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + "&GradeLevel="
                        + Convert.ToString(Session["GradeLevel"]) + "&SwipeCard="
                        + "" + "&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)
        {
            throw ex;
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid == true)
            {
                string employeeName = string.Empty;
                string empId = string.Empty;
                string Level = string.Empty;
                if (intIndividualUser >= 1)
                {
                    empId = Convert.ToString(Session["EmployeeCodeId"]);
                    Level = string.Empty;
                }
                else
                {
                    // empId = txtEmployeeId.Text.Trim().ToString();
                    //  employeeName = this.txtEmployeeName.Text.Replace("'", "''");
                    // employeeName = employeeName.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("@Date=" + " Duration_From " + ",");
                strFilters.Append("@shiftId=" + ddlShift.SelectedValue + ",");
                // strFilters.Append("@LevelID=" + Level + ",");
                strFilters.Append("@UserGroupName=" + Convert.ToString(Session["UserGroupName"]) + ",");
                // strFilters.Append("@GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + ",");
                strFilters.Append("@ParentId=" + Convert.ToInt32(Session["parentLevelId"]).ToString() + ",");
                strFilters.Append("@ExportType=1,");
                strFilters.Append("@EmpAutoId=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() + "';}";
                //strScript = strScript + "self.close();";
                strScript = strScript + "parent.$('#myModalReport').modal('hide');";
                strScript = strScript + "</script>";
                Response.Write(strScript);
            }
        }
        catch
        {
            //
        }
    }
    //protected void IDTest1_Click(object senser, EventArgs e)
    //{
    //    if (hdnReportFilters.Value != "")
    //    {
    //        string strhdnParameters = hdnReportFilters.Value;
    //        string[] strArray = new string[50];
    //        string[] strArray1 = new string[50];
    //        strArray = strhdnParameters.Split(',');
    //        for (int i = 0; i < strArray.Length; i++)
    //        {
    //            string[] strTemp = new string[5];
    //            strTemp = strArray[i].Split('=');
    //            strArray1[i] = strTemp[1];
    //        }
    //        //   txtEmployeeId.Text = strArray1[2].ToString();
    //        // ddlShift.SelectedValue = strArray1[3].ToString();
    //        //  txtEmployeeName.Text = Convert.ToString(strArray1[4].ToString()).Trim().Replace("''", "'");
    //        // txtEmployeeName.Text = Convert.ToString(strArray1[4].ToString()).Trim().Replace("%", " ");
    //        // ddlEmpCatagory.SelectedValue = strArray1[6].ToString();
    //        //  ddlEmpType.SelectedValue = strArray1[7].ToString();
    //        // txtSwipeCard.Text = strArray1[10].ToString();
    //        ucOrganizationLevel.Visible = false;
    //        Session["parentLevelId_modify"] = hdnCompanyId1.Value;
    //        //  ddlDesignation.SelectedValue = strArray1[12].ToString();
    //        //  ddlGender.SelectedValue = strArray1[13].ToString();
    //        string strScript = "";
    //        strScript = strScript + "<script language='javascript'>";
    //        strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_divMenu').style.display = 'none';";
    //        strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div1').style.display = 'none';";
    //        strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div2').style.display = 'none';";
    //        strScript = strScript + "document.getElementById('ctl00_TA_uc_MainMenu1_Div3').style.display = 'none';";
    //        //strScript = strScript + "document.getElementById('ctl00_TA_uc_Header1_RptLogoHeader').style.display = 'none';";
    //        //strScript = strScript + "document.getElementById('ctl00_BodyContentPH_TimePeriod').style.display = 'none';";
    //        strScript = strScript + "</script>";
    //        Page.RegisterStartupScript("Script", strScript);
    //        btnSave.Visible = true;
    //        btn_View.Visible = false;
    //        btnBack.Visible = true;
    //        IDTest1.Visible = false;
    //    }
    //}
    protected void btnBack_Click(object sender, EventArgs e)
    {
        string strMsg;
        strMsg = "<script language='javascript'>";
        strMsg = strMsg + "parent.$('#myModalReport').modal('hide');";
        strMsg = strMsg + "</script>";
        Page.RegisterStartupScript("close report window", strMsg);
        return;
    }
    protected void btn_Export_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid == true)
            {
                DataSet dsEmp = new DataSet();
                string dtFrom = strFromdate;
                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
                {
                    employeeName = employeeName.Replace(' ', '%');
                    Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                }
                DataSet dsSecretariatSummary = new DataSet();
                if (rbtnDetails.Checked == true)
                {
                }
                else
                {
                    dsEmp = rptEmp.SelectSummaryReport(dtFrom, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt32(ddlShift.SelectedValue), 1, Convert.ToInt32(Session["EmpAutoID"]));
                    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
                    {
                        ExportExcel(dsEmp);
                    }
                }

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    #endregion
    #region Export Excel
    protected void ExportExcel(DataSet dsEmp)
    {
        DataTable dtLevelName = new DataTable();
        if (Convert.ToInt16(Session["parentLevelId"]) != 0)
        {
            dtLevelName = rptEmp.getHeader(Convert.ToInt16(Session["parentLevelId"]));
        }
        HSSFWorkbook workbook = new HSSFWorkbook();
        ISheet sheet = workbook.CreateSheet("Head Count Summary Report");
        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;
        hStyle.Alignment = HorizontalAlignment.Center;
        hStyle.VerticalAlignment = VerticalAlignment.Center;
        HSSFCellStyle MainHStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        MainHStyle.SetFont(hFont);
        MainHStyle.Alignment = HorizontalAlignment.Center;
        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]));
            sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 10));
            row.GetCell(0).CellStyle = MainHStyle;
            rowIndex++;
            row = sheet.CreateRow(rowIndex);
        }
        row.CreateCell(0).SetCellValue("Head Count Summary From - " + Convert.ToString(txtFromDate.Text) + " for " + Convert.ToString(ddlShift.SelectedItem.Text));
        row.GetCell(0).CellStyle = MainHStyle;
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 10));
        rowIndex++;
        row = sheet.CreateRow(rowIndex);
        rowIndex++;
        row = sheet.CreateRow(rowIndex);
        row.CreateCell(0).SetCellValue("Sl.No");
        row.CreateCell(1).SetCellValue("Organization Level");
        row.CreateCell(2).SetCellValue("Present");
        row.CreateCell(3).SetCellValue("");
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 2, 3));
        row.CreateCell(4).SetCellValue("Absent");
        row.CreateCell(5).SetCellValue("");
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 4, 5));
        row.CreateCell(6).SetCellValue("Leave");
        row.CreateCell(7).SetCellValue("");
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 6, 7));
        row.CreateCell(8).SetCellValue("LOP");
        row.CreateCell(9).SetCellValue("");
        row.CreateCell(10).SetCellValue("TotalEmployees");
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 8, 9));
        for (int i = 0; i <= 10; i++)
        {
            row.GetCell(i).CellStyle = hStyle;
            sheet.AutoSizeColumn(i);
        }
        rowIndex++;
        row = sheet.CreateRow(rowIndex);
        row.CreateCell(0).SetCellValue("");
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex - 1, rowIndex, 0, 0));
        row.CreateCell(1).SetCellValue("");
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex - 1, rowIndex, 1, 1));
        row.CreateCell(2).SetCellValue("First Session");
        row.CreateCell(3).SetCellValue("Second Session");
        row.CreateCell(4).SetCellValue("First Session");
        row.CreateCell(5).SetCellValue("Second Session");
        row.CreateCell(6).SetCellValue("First Session");
        row.CreateCell(7).SetCellValue("Second Session");
        row.CreateCell(8).SetCellValue("First Session");
        row.CreateCell(9).SetCellValue("Second Session");
        row.CreateCell(10).SetCellValue("Second Session");
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex - 1, rowIndex, 10, 10));
        //row.RowStyle = hStyle;
        for (int i = 0; i <= 10; i++)
        {
            row.GetCell(i).CellStyle = hStyle;
            sheet.AutoSizeColumn(i);
        }
        rowIndex++;
        row = sheet.CreateRow(rowIndex);
        Int32 SlNo = 0;

        foreach (DataRow DR in dsEmp.Tables[0].Rows)
        {
            row = sheet.CreateRow(rowIndex);
            SlNo++;
            row.CreateCell(0).SetCellValue(SlNo);
            row.CreateCell(1).SetCellValue(Convert.ToString(DR["OrgLevel"]));
            row.CreateCell(2).SetCellValue(Convert.ToDouble(DR["PresentFS"]));
            row.CreateCell(3).SetCellValue(Convert.ToDouble(DR["PresentSS"]));
            row.CreateCell(4).SetCellValue(Convert.ToDouble(DR["AbsentFS"]));
            row.CreateCell(5).SetCellValue(Convert.ToDouble(DR["AbsentSS"]));
            row.CreateCell(6).SetCellValue(Convert.ToDouble(DR["LeaveFS"]));
            row.CreateCell(7).SetCellValue(Convert.ToDouble(DR["LeaveSS"]));
            row.CreateCell(8).SetCellValue(Convert.ToDouble(DR["LOPFS"]));
            row.CreateCell(9).SetCellValue(Convert.ToDouble(DR["LOPSS"]));
            row.CreateCell(10).SetCellValue(Convert.ToDouble(DR["TotalEmployees"]));
            PFS = PFS + Convert.ToDouble(DR["PresentFS"]);
            PSS = PSS + Convert.ToDouble(DR["PresentSS"]);
            AFS = AFS + Convert.ToDouble(DR["AbsentFS"]);
            ASS = ASS + Convert.ToDouble(DR["AbsentSS"]);
            LFS = LFS + Convert.ToDouble(DR["LeaveFS"]);
            LSS = LSS + Convert.ToDouble(DR["LeaveSS"]);
            LOPFS = LOPFS + Convert.ToDouble(DR["LOPFS"]);
            LOPSS = LOPSS + Convert.ToDouble(DR["LOPSS"]);
            TotalEmployee = TotalEmployee + Convert.ToDouble(DR["TotalEmployees"]);
            //Style Added the created Headers.
            for (int i = 0; i <= 10; i++)
            {
                row.GetCell(i).CellStyle = IStyle;
                sheet.AutoSizeColumn(i);
            }
            rowIndex++;

        }

        row = sheet.CreateRow(rowIndex);
        row.CreateCell(0).SetCellValue("Total");
        row.GetCell(0).CellStyle = hStyle;
        row.CreateCell(1).SetCellValue("");
        row.GetCell(1).CellStyle = hStyle;
        sheet.AddMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0, 1));
        row.CreateCell(2).SetCellValue(PFS);
        row.CreateCell(3).SetCellValue(PSS);
        row.CreateCell(4).SetCellValue(AFS);
        row.CreateCell(5).SetCellValue(ASS);
        row.CreateCell(6).SetCellValue(LFS);
        row.CreateCell(7).SetCellValue(LSS);
        row.CreateCell(8).SetCellValue(LOPFS);
        row.CreateCell(9).SetCellValue(LOPSS);
        row.CreateCell(10).SetCellValue(TotalEmployee);
        for (int i = 2; i <= 10; i++)
        {
            row.GetCell(i).CellStyle = IStyle;
        }

        using (MemoryStream exportData = new MemoryStream())
        {
            workbook.Write(exportData);
            string saveAsFileName = string.Format("HeadCountSummaryReport-{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();
        }
    }
    #endregion
}
