using System;
using System.Data;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Reports_TA_UI_Report_DeviationReport : 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;
    cls_Common objCommon = new cls_Common();
    CultureInfo ci;
    int intIndividualUser = 0;
    string strFromdate, gstrDateFormat, strTodate;
    EmployeeEventData objEmployee = new EmployeeEventData();
    HeaderInformation hdrTable = new HeaderInformation();
    int ColCount = 0, EndCount = 0, rowCountval = 0;
    string sheetName, reportName = "";
    DataSet dsEmp = new DataSet();
    int rowIndex1 = 0, day = 0;
    int employeeCategory = 0, employeeType = 0;
    string empName = "", empId = "", Level = "", strScript = "", strReportType = string.Empty, ParenetLevelid = string.Empty;
    string strSwipeCard = "", strdtFromDate, strdtToDate, SelectedMonth = "", SelectedYear = "";
    DateTime dtFromDate1, dtToDate1;
    string strEmpAutoId = string.Empty;
    TimeSpan diff;
    #endregion
    #region Page Load Events
    /// <summary>
    /// On page loading
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            objCommon.menu("Attendance Reports", "309");
        }
        //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"]);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_EnterDate", ci) + "','" + rm.GetString("Alert_EnterToDate", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        //Set UserRights
        gvData.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        if (ViewState["Deviation"] != null)
        {
            gvData.DataSource = (DataSet)ViewState["Deviation"];
            gvData.DataBind();
        }

        if (!IsPostBack)
        {
            LoadStrings(ci);
            UserRights();
            string strScript = "";
            divdateTime.Visible = true;
            trView.Visible = true;
            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;
            //Included by A.Amsaveni on 18/07/2013
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            txtFromDate.Text = (Convert.ToDateTime(objCommon.CurrentMonthStartDate())).ToString(Convert.ToString(Session["MDateFormat"]));
            txtToDate.Text = (Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Convert.ToString(Session["MDateFormat"]));
            BindingEmployeeCategoryandType();
            BindDesignation();
            ddlDesignation.PreRender += LB_PreRender;
        }
        //Check whether the employee is Individual User
        if (ViewState["vs_intIndividualUser"] == null)
        {
            intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
            ViewState["vs_intIndividualUser"] = intIndividualUser;
        }
        else
        {
            intIndividualUser = (int)ViewState["vs_intIndividualUser"];
        }
        if (intIndividualUser >= 1)
        {
            PlaceHolderDetailedAttendance.Controls.Clear();
            divEmployeeDetails.Visible = false;
        }
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strFromdate = txtFromDate.Text;
        strFromdate = objCommon.DateConvertion(gstrDateFormat, strFromdate);
        strTodate = txtToDate.Text;
        strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
        if (Convert.ToString(Page.MasterPageFile) == "TA_Popup_Report_MasterPage.master")
        {
            conHeader.Visible = false;
        }
    }
    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>
    /// 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>
    /// Bindings the employee category and type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        EmployeeEventData objEmployee = new EmployeeEventData();
        // 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);
        }
    }
    private void BindTitle(DropDownList ddl)
    {
        foreach (ListItem item in ddl.Items)
        {
            item.Attributes.Add("title", item.Text);
        }
    }
    /// <summary>
    /// To get the label names according to the language selected.
    /// </summary>
    /// <param name="ci"></param>
    private void LoadStrings(CultureInfo ci)
    {
        lblFilter.Text = rm.GetString("lblFilter", ci);
        lblReport.Text = "Deviation Report";
        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);
        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);
        lblDateFilter.Text = rm.GetString("lbl_DateFilter", 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);
    }
    /// <summary>
    /// To check the user rights for the logged in user
    /// </summary>
    private void UserRights()
    {
        if (ViewState["vsUserRights"] != null)
            ds_Checkuser = (DataSet)ViewState["vsUserRights"];
        else
            ds_Checkuser = objCheckUser.checkRights(309, 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)
                lnkbtnGrid.Visible = true;
            else
                lnkbtnGrid.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
    private void GetAndSetFieldValues()
    {
        if (intIndividualUser >= 1)
        {
            empName = string.Empty;
            empId = Convert.ToString(Session["EmployeeCodeId"]);
        }
        else
        {
            empName = Convert.ToString(txtEmployeeName.Text);
            empId = Convert.ToString(txtEmployeeId.Text).Trim();
            Level = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        }
        if (Convert.ToInt32(ddlEmpCatagory.SelectedValue) != 0)
            employeeCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
        else
            employeeCategory = 0;
        if (Convert.ToInt32(ddlEmpType.SelectedValue) != 0)
            employeeType = Convert.ToInt32(ddlEmpType.SelectedValue);
        else
            employeeType = 0;
        ParenetLevelid = Convert.ToString(Session["parentLevelId"]);
        if (Session["ReportsBasedOn"] != null)
        {
            if (Convert.ToString(Session["ReportsBasedOn"]) == "False")
                strEmpAutoId = "0";
            else
                strEmpAutoId = Convert.ToString(Session["EmpAutoID"]);
        }
    }
    #region Button Events
    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;
    }
    private DataSet GetData()
    {
        DataSet dsEmp = new DataSet();
        if (ParenetLevelid == "") ParenetLevelid = "0";
        {
            dsEmp = rptEmp.GetDeviationEmployeesDetails(empId, empName, Level, Convert.ToString(employeeCategory), Convert.ToString(employeeType), Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), strSwipeCard, Convert.ToInt16(ParenetLevelid), strdtFromDate, strdtToDate, Convert.ToInt32(ddlDesignation.SelectedValue), Convert.ToString(ddlGender.SelectedValue), Convert.ToInt32(Session["EmpAutoID"]), "");
            ViewState["Deviation"] = dsEmp;
        }
        return dsEmp;
    }
    #endregion
    #region *** UserdefinedFunctions ***
    /// <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("Select valid date compare with Fromdate");
                base.Message(rm.GetString("Msg_SelectvaliddatecomparewithFromdate", ci));
                e.IsValid = false;
            }
        }
        catch
        {
            //
        }
    }
    /// <summary>
    /// Validate the ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            //strCurrentDate = objCommon.DateConvertion(gstrDateFormat, DateTime.Today.Date.ToString());
            strTodate = txtToDate.Text;
            strTodate = objCommon.DateConvertion(gstrDateFormat, strTodate);
            DateTime dtCurrentDate = Convert.ToDateTime(DateTime.Today.Date.ToString("MM/dd/yyyy"));
            DateTime dtFromDate = DateTime.Parse(strTodate);
            TimeSpan diff = dtFromDate.Subtract(dtCurrentDate);
            int day = diff.Days;
            if (day <= 0)
                e.IsValid = true;
            else
            {
                base.Message(rm.GetString("Alert_EnterValidToDate", ci));
                e.IsValid = false;
            }
        }
        catch
        {
            //
        }
    }
    /// <summary>
    /// 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 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
        {
            //
        }
    }
    #endregion
    private void clearControls()
    {
        ViewState["Deviation"] = null;
        gvData.DataSource = null;
        gvData.DataBind();
        gvData.Visible = false;

        lnkbtnpdf.Visible = false;
        lnktbnexcel.Visible = false;
        
    }
    protected void lnkbtnGrid_Click(object sender, EventArgs e)
    {
        clearControls();
        GetAndSetFieldValues();
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strdtFromDate = txtFromDate.Text;
        strdtToDate = txtToDate.Text;
        strdtFromDate = objCommon.DateConvertion(gstrDateFormat, strdtFromDate);
        strdtToDate = objCommon.DateConvertion(gstrDateFormat, strdtToDate);
        if (strdtFromDate != string.Empty && strdtToDate != string.Empty)
        {
            dtFromDate1 = Convert.ToDateTime(strdtFromDate).Date;
            dtToDate1 = DateTime.Parse(strdtToDate);
            diff = dtToDate1.Subtract(dtFromDate1);
            day = diff.Days;
        }
        day = day + 1;
        if (day > 31)
        {
            base.Message("Selected Date range should not exceed 31 Days");
            return;
        }
        else
        {
            dsEmp = GetData();
            lnktbnexcel.Visible = true;
            lnkbtnpdf.Visible = true;
            gvData.SettingsText.Title = "Deviation Report -" + txtFromDate.Text + " To " + txtToDate.Text;
            gvData.Visible = true;
            gvData.DataSource = dsEmp;
            gvData.DataBind();
            
        }
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = (LinkButton)sender;
        {
            ASPxGridViewExporter1.Landscape = true;
            ASPxGridViewExporter1.LeftMargin = 10;
            ASPxGridViewExporter1.RightMargin = 10;
            ASPxGridViewExporter1.ExportedRowType = DevExpress.Web.GridViewExportedRowType.All;
            ASPxGridViewExporter1.MaxColumnWidth = 400;
            string saveAsFileName = string.Format("Deviation Report -{0:d}", DateTime.Now).Replace("/", "-").Replace(" ", "");
            ASPxGridViewExporter1.FileName = saveAsFileName;
            ASPxGridViewExporter1.PaperKind = System.Drawing.Printing.PaperKind.A3;
            ASPxGridViewExporter1.PageHeader.Center = "Deviation report From - " + Convert.ToString(txtFromDate.Text) + " To - " + Convert.ToString(txtToDate.Text);
            switch (lnkbtn.CommandName)
            {
                case "excel":
                    ASPxGridViewExporter1.WriteXlsxToResponse();
                    break;
                case "pdf":
                    ASPxGridViewExporter1.WritePdfToResponse();
                    break;
            }
        }
    }
    protected void lnbtnClear_Click(object sender, EventArgs e)
    {
        clearControls();
    }
    protected void lnkbtnExportExcel1_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = (LinkButton)sender;
        {

        }
    }
}