using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;
using System.Text;
public partial class Reports_TA_UI_Report_WorkedDays : Base.BasePage
{
    #region Variable Declaration
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    HeaderInformation hdrTable = new HeaderInformation();
    GetReports rptEmp = new GetReports();
    Rpt_Common rptcommon = new Rpt_Common();
    EmployeeEventData objEmployee = new EmployeeEventData();
    cls_Common objCommon = new cls_Common();
    ResourceManager rm;
    CultureInfo ci;
    string dtFrom = "", dtTo = "", EmployeeId = "", gstrDateFormat, strFromdate, strTodate;
    int intIndividualUser = 0;
    string gStrLevel = string.Empty, ParenetLevelid = string.Empty;
    #endregion
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        //get the culture info to set the language        
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            objCommon.menu("Attendance Reports", "184");
        }
        string source_Language;
        source_Language = Session["Session_ActiveLanguage"].ToString();
        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 + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_SelectDuration", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        //Set UserRights
        //  UserRights();
        if (!Page.IsPostBack)
        {
            hdndate.Value = Convert.ToString(Session["IDateFormat"]);
            // Bindings the employee category and type.
            BindingEmployeeCategoryandType();
            FillDesignation();
            ddlDesignation.PreRender += LB_PreRender;
            string strDayName = Convert.ToString(DateTime.Now.Date.DayOfWeek).ToLower();
            double iFromDate = strDayName.Contains("monday") ? 0 : strDayName.Contains("tuesday") ? -1 : strDayName.Contains("wednesday") ? -2 : strDayName.Contains("thursday") ? -3 : strDayName.Contains("friday") ? -4 : -5;
            //txtFromDate.Text = System.DateTime.Now.Date.AddDays(iFromDate).ToString(Convert.ToString(Session["MDateFormat"]));
            //txtToDate.Text = System.DateTime.Now.Date.AddDays(iFromDate + 5).ToString(Convert.ToString(Session["MDateFormat"]));
            txtFromDate.Text = (Convert.ToDateTime(objCommon.CurrentMonthStartDate())).ToString(Session["MDateFormat"].ToString());
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Session["MDateFormat"].ToString());
        }
        ////Convert date time to MM/dd/YYYY format
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        strTodate = txtToDate.Text;
        strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
    }
    #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);
            }
        }
    }
    /// <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>
    /// Getting Information from resource file and display it in label
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        lblPayrollReport.Text = rm.GetString("Menu_Reports_WorkedDays", 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);
        lblEmpSwipe.Text = rm.GetString("TerminalDataType_Card_No", 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);
        reqFromDate.ErrorMessage = rm.GetString("Alert_PleaseselectFromDate", ci);
        reqToDate.ErrorMessage = rm.GetString("Alert_PleaseselectToDate", ci);
        lblTimePeriod.Text = rm.GetString("Reports_TimePeriod", ci);
        lblFrom.Text = rm.GetString("email_FromDate", ci);
    }
    /// <summary>
    /// To check rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(184, 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>
    /// Validate the FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        e.IsValid = false;
        try
        {
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtFromDate = DateTime.Parse(strFromdate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            //e.IsValid = (dtFromDate.ToLongDateString().Split(',')[0].Equals("Monday"));
            e.IsValid = (dtFromDate.DayOfWeek.ToString() == "Monday" ? true : false);
            if (!e.IsValid)
                base.Message("Select Monday in From Date");
        }
        catch
        {
            base.Message("Enter Valid From Date");
        }
    }
    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        e.IsValid = false;
        try
        {
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date);
            DateTime dtToDate = DateTime.Parse(strTodate);
            TimeSpan diff = dtToDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            e.IsValid = (dtToDate.DayOfWeek.ToString() == "Saturday" ? true : false);
            if (!e.IsValid)
                base.Message("Select Saturday in To Date");
        }
        catch
        {
            base.Message("Enter Valid To Date");
        }
    }
    /// <summary>
    /// Compare ToDate with FromDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        e.IsValid = false;
        try
        {
            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;
            if (!e.IsValid)
                base.Message("To date should be greater than From date");
        }
        catch
        {
            base.Message("Select saturday in To date");
        }
    }
    #endregion
    #region Button Event
    /// <summary>
    /// Load Late Entry report
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btn_View_Click(object sender, EventArgs e)
    {
        int EmpCategory = 0, EmpType = 0;
        string Level = string.Empty, EmpName = string.Empty, EmpId = string.Empty, SwipeCard = string.Empty;
        try
        {
            if (Page.IsValid == true)
            {
                // set employee category and type
                if (Convert.ToInt32(ddlEmpCatagory.SelectedValue) != 0)
                    EmpCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
                if (Convert.ToInt32(ddlEmpType.SelectedValue) != 0)
                    EmpType = Convert.ToInt32(ddlEmpType.SelectedValue);
                if (txtFromDate.Text != "")
                    dtFrom = strFromdate;
                if (txtToDate.Text != "")
                    dtTo = strTodate;
                //Get the Report source from the Server and load this into the report table\
                DataSet dsWeeklyHrs = new DataSet();
                if (intIndividualUser >= 1)
                {
                    EmpId = Convert.ToString(Session["EmployeeCodeId"]);
                    EmployeeId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    EmpId = txtEmployeeId.Text.Trim().ToString();
                    EmployeeId = txtEmployeeId.Text.Trim().ToString();
                    EmpName = txtEmployeeName.Text.Replace("'", "''").Replace(' ', '%');
                    SwipeCard = txtSwipeCard.Text.Trim().ToString().Replace("'", "''");
                    Level = rptcommon.getNodes(Convert.ToInt32(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                    gStrLevel = Level;
                }
                DateTime dtToDate = DateTime.Parse(strTodate);
                DateTime dtFromDate = DateTime.Parse(strFromdate);
                TimeSpan diff = dtToDate.Subtract(dtFromDate);
                int day = diff.Days;
                if (day > 35)
                {
                    base.Message("Select Valid From and Todate");
                    return;
                }
                Session["LateInsLevel"] = Level;
                string strEmpAutoId = string.Empty;
                int iReportType = 0;
                string strReportName = "ForPayroll";
                string strEmpCategory = Convert.ToString(EmpCategory);
                string strEmpType = Convert.ToString(EmpType);
                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=" + strReportName + "&dtFrom=" + Cryptographys.Cryptography.Encrypt(dtFrom, "AnglerReports") + "&dtTo=" + Cryptographys.Cryptography.Encrypt(dtTo, "AnglerReports") + "&empid=" + Cryptographys.Cryptography.Encrypt(EmpId, "AnglerReports") + "&EmpName=" + Cryptographys.Cryptography.Encrypt(EmpName, "AnglerReports") + "&Level=" + Cryptographys.Cryptography.Encrypt(Level, "AnglerReports") + "&EmpCategory=" + strEmpCategory + "&EmpType=" + strEmpType + "&ParentLevelId=" + Cryptographys.Cryptography.Encrypt(Convert.ToInt32(Session["parentLevelId"]).ToString(), "AnglerReports") + "&SwipeCard=" + Cryptographys.Cryptography.Encrypt(SwipeCard, "AnglerReports") + "&ReportType=" + Cryptographys.Cryptography.Encrypt(iReportType.ToString(), "AnglerReports") + "','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
                strScript = strScript + "window.open('TA_UI_Report_ReportViewer.aspx?ReportName=" + strReportName + "&dtFrom=" + dtFrom + "&dtTo=" + dtTo + "&empid=" + EmpId + "&EmpName=" + EmpName + "&Level=" + Level + "&EmpCategory=" + strEmpCategory + "&EmpType=" + strEmpType + "&ParentLevelId=" + Convert.ToInt32(Session["parentLevelId"]).ToString() + "&SwipeCard=" + SwipeCard + "&ReportType=" + iReportType.ToString() + "&Gender=" + ddlGender.SelectedValue + "','','left=10px, top=60px, width=1000px, height=600px, scrollbars=yes, status=no, resizable=yes');";
                strScript = strScript + "</script>";
                Response.Write(strScript);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    #endregion
    protected void Button1_Click(object sender, EventArgs e)
    {
        int EmpCategory = 0, EmpType = 0;
        string Level = string.Empty, EmpName = string.Empty, EmpId = string.Empty, SwipeCard = string.Empty;
        try
        {
            if (Page.IsValid == true)
            {
                // set employee category and type
                if (Convert.ToInt32(ddlEmpCatagory.SelectedValue) != 0)
                    EmpCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
                if (Convert.ToInt32(ddlEmpType.SelectedValue) != 0)
                    EmpType = Convert.ToInt32(ddlEmpType.SelectedValue);
                if (txtFromDate.Text != "")
                    dtFrom = strFromdate;
                if (txtToDate.Text != "")
                    dtTo = strTodate;
                //Get the Report source from the Server and load this into the report table\
                DataSet dsWeeklyHrs = new DataSet();
                //shft = Convert.ToInt32(this.ddlShift.SelectedValue);
                if (intIndividualUser >= 1)
                {
                    EmpId = Convert.ToString(Session["EmployeeCodeId"]);
                    EmployeeId = Convert.ToString(Session["EmployeeCodeId"]);
                }
                else
                {
                    EmpId = txtEmployeeId.Text.Trim().ToString();
                    EmployeeId = txtEmployeeId.Text.Trim().ToString();
                    EmpName = txtEmployeeName.Text.Replace("'", "''").Replace(' ', '%');
                    SwipeCard = txtSwipeCard.Text.Trim().ToString().Replace("'", "''");
                    Level = rptcommon.getNodes(Convert.ToInt32(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
                    gStrLevel = Level;
                }
                DateTime dtToDate = DateTime.Parse(strTodate);
                DateTime dtFromDate = DateTime.Parse(strFromdate);
                TimeSpan diff = dtToDate.Subtract(dtFromDate);
                int day = diff.Days;
                if (day > 35)
                {
                    base.Message("Select Valid From and Todate");
                    return;
                }
                Session["LateInsLevel"] = Level;
                string strEmpAutoId = string.Empty;
                string strEmpCategory = Convert.ToString(EmpCategory);
                string strEmpType = Convert.ToString(EmpType);
                DataSet dsEmp = new DataSet();
                dsEmp = rptEmp.SelectWorkedDaysDetailsWithDeviationsExport_Angler
                    (
                        EmpId,
                        Level,
                        dtFrom,
                        dtTo,
                        EmpName,
                        EmpCategory,
                        EmpType,
                        Session["UserGroupName"].ToString(),
                        Convert.ToString(Session["GradeLevel"]),
                        SwipeCard,
                       0,
                        Convert.ToInt32(ddlDesignation.SelectedValue),
                        Convert.ToInt32(Session["parentLevelId"]),
                        ddlGender.SelectedValue
                    );
                if (dsEmp.Tables[0].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;
                }
                string strHead = "";
                strHead = "<HTML xmlns:x='urn:schemas-microsoft-com:office:excel'>";
                strHead += "<HEAD><meta charset='utf-8'><style type=\"text/css\">  <!--table";
                strHead += "  @page {mso-header-data:'&CMultiplication Table\\000ADate\\: &D\\000APage &P';mso-page-orientation:landscape;}";
                strHead += "br{mso-data-placement:same-cell;}";
                strHead += ".td{mso-width-source:auto;}";
                strHead += "--></style>";
                strHead += "<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>";
                strHead += "<x:Name></x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo/>";
                strHead += "</x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>";
                strHead += "</xml><![endif]--></HEAD><body><table border=\"1\"><tr>";
                dsEmp.Tables[0].TableName = "Sheet 1";
                DataTable dt = dsEmp.Tables[0];
                dt.TableName = "Sheet 1";
                string attachment = "attachment; filename=Payroll_" + txtFromDate.Text + "_" + txtToDate.Text + ".xls";
                Response.ClearContent();
                Response.AddHeader("content-disposition", attachment);
                Response.ContentType = "application/vnd.ms-excel";
                string tab = "";
                Response.Write(strHead);
                foreach (DataColumn dc in dt.Columns)
                {
                    Response.Write("<td>" + dc.ColumnName + "</td>");
                }
                Response.Write("</tr><tr>");
                int i;
                foreach (DataRow dr in dt.Rows)
                {
                    tab = "";
                    for (i = 0; i < dt.Columns.Count; i++)
                    {
                        Response.Write("<td>" + dr[i].ToString() + "</td>");
                        // tab = "\t";
                    }
                    Response.Write("</tr><tr>");
                }
                Response.Write("</tr></BODY></HTML>");
                Response.End();
            }
        }
        catch
        {

        }
    }
}