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;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.Util;
using System.Web;
public partial class Reports_TA_UI_Report_DailyAttendance : 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();
    ResourceManager rm;
    CultureInfo ci;
    cls_Common objCommon = new cls_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    string strFromdate, gstrDateFormat, strTodate;
    int payrollConfig = 0;
    int intIndividualUser = 0;
    string strSwipeCard = "";
    string dtFrom = "", dtTo = "";
    string Level = string.Empty;
    string employeeName = string.Empty;
    string empName = string.Empty;
    string empId = string.Empty;
    int shift;
    string strEmpAutoId = "0";
    string MinWorkHours = "";
    HSSFFont pageheaderFont;
    HSSFCellStyle empDetailStyle, DetailStyle, MainStyle, fieldHeaderStyle, totalStyle;
    #endregion

    #region Page Load event
    /// <summary>
    /// On page loading
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            objCommon.menu("Attendance Reports", "266");
            payrollConfig = objCommon.CheckPageExistsInLicense(185);
            /*Below parameter is used for Angler*/
            if (payrollConfig == 1)
            {
                divProduct.Style.Add("display", "none");
            }
        }
        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) + "','" + rm.GetString("Alert_EntervalidMinimumWorkHours", ci) + "');";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", 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);
        UserRights();

        if (!IsPostBack)
        {
            BindingEmployeeCategoryandType();
            BindShift();
            BindDesignation();

            BindLocation();

            if (Request.QueryString["Source"] != null)
                if (Session["parentLevelId"] != null || Convert.ToInt16(Session["parentLevelId"]) != 0)
                    Session["parentLevelId"] = null;
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            ddlDesignation.PreRender += LB_PreRender;
            txtFromDate.Text = (Convert.ToDateTime(objCommon.CurrentMonthStartDate())).ToString(Session["MDateFormat"].ToString());
        }

        if (ViewState["vsintIndividualUser"] != null)
        {
            intIndividualUser = Convert.ToInt16(ViewState["vsintIndividualUser"]);
        }
        else
        {
            intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
            ViewState["vsintIndividualUser"] = intIndividualUser;
        }
        if (intIndividualUser >= 1)
        {
            PlaceHolderMonthlyAttendance.Controls.Clear();
            divEmployeeDetails.Visible = false;
        }
        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>
    /// Load Shift DropDown
    /// </summary>
    public void BindShift()
    {
        ShiftEvenData getShift = new ShiftEvenData();
        DataSet ds = new DataSet();
        string strusergroup = string.Empty;
        ds = getShift.SelectShift(Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["LevelRights"]), 0);
        foreach (DataRow drRow in ds.Tables[0].Rows)
        {
            switch (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();
        }
        ListItem lstItem = new ListItem();
        lstItem.Value = "0";
        lstItem.Text = rm.GetString("ExportData_All", ci);
        ddlShift.Items.Insert(0, lstItem);
        BindTitle(ddlShift);
    }

    private void BindTitle(DropDownList ddl)
    {
        foreach (ListItem item in ddl.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }

    /// <summary>
    /// Fills the designation in the drop down
    /// </summary>
    private void BindDesignation()
    {
        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();
            BindTitle(ddlDesignation);
        }
    }

    /// <summary>
    /// Fills the designation in the drop down
    /// </summary>
    private void BindLocation()
    {
        DataSet ds_location = new DataSet();
        ds_location = objEmployee.select_Location();
        if (ds_location != null)
        {
            if (ds_location.Tables[0].Rows.Count > 0)
            {
                ddlLocation.DataSource = ds_location;
                ddlLocation.DataTextField = "LocationName";
                ddlLocation.DataValueField = "LocationId";
                ddlLocation.DataBind();
            }
            ds_location.Dispose();
            BindTitle(ddlLocation);
        }
    }
    /// <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();
            BindTitle(ddlEmpCatagory);
        }
        // employee type binding
        DataSet dsType = new DataSet();
        dsType = objEmployee.SelectTypeDetailsEmployee("");
        if (dsType != null)
        {
            if (dsType.Tables[0].Rows.Count > 0)
            {
                ddlEmpType.DataSource = dsType;
                ddlEmpType.DataTextField = "TypeName";
                ddlEmpType.DataValueField = "TypeId";
                ddlEmpType.DataBind();
            }
            dsType.Dispose();
            BindTitle(ddlEmpType);
        }
    }
    /// <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 if (day > 0)
            {
                base.Message("Future Dates Not Valid ! Please select Current date or passed date !!!");
                e.IsValid = false;
            }
            else
            {
                base.Message(rm.GetString("Alert_EnterValidFromDate", ci));
                e.IsValid = false;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>

    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>

    /// <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);
        lblTimePeriod.Text = rm.GetString("Reports_TimePeriod", ci);
        lblFrom.Text = rm.GetString("email_FromDate", ci);
        lblDailyAttendanceReport.Text = rm.GetString("DailyAttendanceReport", 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);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
        lblDesignation.Text = rm.GetString("EmployeeMaster_Designation", ci);
        lblGender.Text = rm.GetString("EmployeeMaster_Gender", ci);
        ddlGender.Items[0].Text = rm.GetString("Caption_Both", ci);
        ddlGender.Items[1].Text = rm.GetString("rbtn_EmployeeMaster_Male", ci);
        ddlGender.Items[2].Text = rm.GetString("rbtn_EmployeeMaster_Female", ci);
        ddlDesignation.Items[0].Text = rm.GetString("ExportData_All", ci);
        lblShift.Text = rm.GetString("Menu_Reports_Shift", ci);
        lblShift.Text = rm.GetString("Menu_Reports_Shift", ci);
        btn_Export.Text = "&nbsp;&nbsp;" + rm.GetString("btn_ExporttoExcel", ci);
        ;
    }
    /// <summary>
    /// To check rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        if (ViewState["vsUserRights"] != null)
            ds_Checkuser = (DataSet)ViewState["vsUserRights"];
        else
       
            ds_Checkuser = objCheckUser.checkRights(266, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            ViewState["vsUserRights"] = ds_Checkuser;
            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);
        }
    }
    #endregion
    #region Button Events
    private void commonfieldsAndValues()
    {
        string strdtFromDate;
        strdtFromDate = txtFromDate.Text.Trim();
        if (txtFromDate.Text != "")
            dtFrom = strFromdate;

        shift = Convert.ToInt32(ddlShift.SelectedValue);
        if (intIndividualUser >= 1)
        {
            empName = string.Empty;
            Level = string.Empty;
            empId = Convert.ToString(Session["EmployeeCodeId"]);
        }
        else
        {
            empName = Convert.ToString(txtEmployeeName.Text);
            empId = Convert.ToString(txtEmployeeId.Text.Trim());
            employeeName = this.txtEmployeeName.Text.Replace("'", "''");

            Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        }
        if (Session["ReportsBasedOn"] != null)
        {
            switch (Convert.ToString(Session["ReportsBasedOn"]))
            {
                case "False":
                    strEmpAutoId = "0";
                    break;
                default:
                    strEmpAutoId = Convert.ToString(Session["EmpAutoID"]);
                    break;
            }
        }

    }
    private DataSet getAttendanceData()
    {
        DataSet dsEmp = new DataSet();

        dsEmp = rptEmp.SelectDailyAttendanceReport("Proc_TA_RptDailyAttendance", "", strFromdate, empName, empId,
         Convert.ToInt32(ddlEmpCatagory.SelectedValue), Convert.ToInt32(ddlEmpType.SelectedValue),
           Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]),
           Convert.ToInt16(Session["parentLevelId"]), Convert.ToInt32(ddlDesignation.SelectedValue),
           ddlGender.SelectedValue, shift, Convert.ToInt64(strEmpAutoId), Convert.ToInt32(ddlLocation.SelectedValue));

        return dsEmp;
    }
    protected void btn_View_Click(object sender, EventArgs e)
    {
        BindDataToReport("View", 0);
    }
    private void BindDataToReport(string whichBtn, int isgrid)
    {

        if (Page.IsValid == true)
        {
            DataSet dsEmp = new DataSet();
            commonfieldsAndValues();
            dsEmp = getAttendanceData();
            if (dsEmp.Tables["Table"] == null || dsEmp.Tables["Table"].Rows.Count == 0)
            {
                Message(rm.GetString("Alert_Thereisnorecord", ci));
                return;
            }
            else
            {
                LoadReport(dsEmp, isgrid);
            }
        }

    }
    private void LoadReport(DataSet dsEmp, int grid)
    {
        Session["DailyAttendanceHorizontal"] = dsEmp;

        OpenreportViewer("window.open('TA_UI_Report_ReportViewer.aspx?ReportName=DailyAttendanceReport&dtFrom=" + strFromdate + "&empid=" + empId + "&shft=" + shift + "&EmpName=" + employeeName + "&Level=" + Level + "&EmpCategory=" + Convert.ToInt32(ddlEmpCatagory.SelectedValue) + "&EmpType=" + Convert.ToInt32(ddlEmpType.SelectedValue) + "&ParentLevelId=" + Convert.ToInt16(Session["parentLevelId"]) + "&GradeLevel=" + Convert.ToString(Session["GradeLevel"]) + "&Designation=" + Convert.ToInt32(ddlDesignation.SelectedValue) + "&Gender=" + ddlGender.SelectedValue + "','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');");
    }

    private void DisableControls()
    {
    }

    private void OpenreportViewer(string redirection)
    {
        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 + redirection;
        strScript = strScript + "</script>";
        Response.Write(strScript);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        //No need code since UI control removed for this report
    }
    protected void getStyles(HSSFWorkbook workbook)
    {
        #region objectCreation
        pageheaderFont = (HSSFFont)workbook.CreateFont();
        empDetailStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        DetailStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        MainStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        fieldHeaderStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        totalStyle = (HSSFCellStyle)workbook.CreateCellStyle();
        #endregion
        #region PageHeaderStyles
        pageheaderFont.Boldweight = (short)FontBoldWeight.Bold;
        pageheaderFont.Color = HSSFColor.Maroon.Index;
        pageheaderFont.FontHeightInPoints = 16;
        MainStyle.SetFont(pageheaderFont);
        MainStyle.Alignment = HorizontalAlignment.Center;
        #endregion
        #region EmpHeaderStyle
        empDetailStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        empDetailStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        empDetailStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        empDetailStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        empDetailStyle.Alignment = HorizontalAlignment.Center;
        empDetailStyle.VerticalAlignment = VerticalAlignment.Center;
        empDetailStyle.WrapText = true;
        empDetailStyle.FillPattern = FillPattern.SolidForeground;
        HSSFFont empheaderfont = (HSSFFont)workbook.CreateFont();
        empheaderfont.Boldweight = (short)FontBoldWeight.Bold;
        empheaderfont.Color = HSSFColor.Black.Index;
        empheaderfont.FontHeightInPoints = 12;
        empDetailStyle.SetFont(empheaderfont);
        #endregion
        #region fieldHeaderStyle
        fieldHeaderStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        fieldHeaderStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        fieldHeaderStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        fieldHeaderStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        fieldHeaderStyle.Alignment = HorizontalAlignment.Center;
        fieldHeaderStyle.VerticalAlignment = VerticalAlignment.Center;
        fieldHeaderStyle.FillForegroundColor = HSSFColor.Aqua.Index;
        fieldHeaderStyle.WrapText = true;
        fieldHeaderStyle.FillPattern = FillPattern.SolidForeground;
        HSSFFont h2font = (HSSFFont)workbook.CreateFont();
        h2font.Boldweight = (short)FontBoldWeight.Bold;
        h2font.Color = HSSFColor.White.Index;
        h2font.FontHeightInPoints = 10;
        fieldHeaderStyle.SetFont(h2font);
        #endregion
        #region DetailsStyle
        DetailStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        DetailStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        DetailStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        DetailStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        DetailStyle.VerticalAlignment = VerticalAlignment.Center;
        DetailStyle.Alignment = HorizontalAlignment.Center;
        #endregion
        #region TotalFieldStyle
        totalStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
        totalStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
        totalStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
        totalStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
        totalStyle.FillPattern = FillPattern.SolidForeground;
        totalStyle.VerticalAlignment = VerticalAlignment.Center;
        totalStyle.FillForegroundColor = HSSFColor.Grey25Percent.Index;
        HSSFFont h3font = (HSSFFont)workbook.CreateFont();
        h3font.Boldweight = (short)FontBoldWeight.Bold;
        h3font.FontHeightInPoints = 12;
        totalStyle.SetFont(h3font);
        #endregion
    }
    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)
    {
        BindDataToReport("Export", 0);
    }
    private void ExportToExcelHorizontal(DataSet dsEmp)
    {

    }


    protected void btnExport_Click(object sender, EventArgs e)
    {

    }
    #endregion
}
