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;
public partial class Transactions_TA_UI_Transactions_BonusLeaveAllocation : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    cls_Common objCommon = new cls_Common();
    Rpt_Common rptcommon = new Rpt_Common();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    EmployeeEventData objEmployee = new EmployeeEventData();
    BonusLeave objBonusLeave = new BonusLeave();
    DataSet ds_Checkuser = new DataSet();
    DateTime gdtmCurrYrStartDate = new DateTime();
    DateTime gdtmCurrYrEndDate = new DateTime();
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        ////if Standar Edition set the visibility to false
        //if (Session["Edition"].ToString() == "1")
        //{
        //    Response.Redirect("TransactionLandingPage.aspx");
        //}
        //get the culture info to set the language        
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            objCommon.menu("LeaveTransaction", "96");
        }
        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 + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_BonusLeaveQuotashouldnotbelessthanBonusLeaveTaken", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        // Set UserRights
        UserRights();
        if (!IsPostBack)
        {
            // Bindings the employee category and type.
            BindingEmployeeCategoryandType();
        }
        if (!IsPostBack)
        {
            btn_Save.Visible = false;
        }
    }
    #endregion
    #region UserDefinedFunctions
    /// <summary>
    /// Bindings the employee category and type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        // Binding Employee Category 
        DataSet dsCategory = new DataSet();
        dsCategory = objEmployee.SelectCategoryDetailsEmployee(string.Empty);
        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);
            }
        }
        // Binding Employee Type
        DataSet dsType = new DataSet();
        dsType = objEmployee.SelectTypeDetailsEmployee(string.Empty);
        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);
            }
        }
    }
    private int GetCurrentYearSettingId()
    {
        DataSet ds_Year = new DataSet();
        int intCurrentYearSettingId = 0;
        ds_Year = objCommon.GetYearsetting();
        if (ds_Year != null)
        {
            if (ds_Year.Tables[0].Rows.Count > 0)
            {
                intCurrentYearSettingId = int.Parse(ds_Year.Tables[0].Rows[0]["YearSettings_Id"].ToString());
                gdtmCurrYrStartDate = DateTime.Parse(ds_Year.Tables[0].Rows[0]["FromDate"].ToString());
                gdtmCurrYrEndDate = DateTime.Parse(ds_Year.Tables[0].Rows[0]["ToDate"].ToString());
            }
        }
        return (intCurrentYearSettingId);
    }
    private void LoadStrings(CultureInfo ci)
    {
        lblBonusLeave.Text = rm.GetString("Transaction_BonusLeave_Title", 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);
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        btn_Save.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        gvEmpBonusLeave.Columns[1].HeaderText = rm.GetString("email_EmployeeId", ci);
        gvEmpBonusLeave.Columns[2].HeaderText = rm.GetString("email_EmployeeName", ci);
        gvEmpBonusLeave.Columns[3].HeaderText = rm.GetString("LeaveSanction_Department", ci);
        gvEmpBonusLeave.Columns[4].HeaderText = rm.GetString("BonusLeaveAllocation_BonusLeavequota", ci);
        gvEmpBonusLeave.Columns[5].HeaderText = rm.GetString("BonusLeaveAllocation_LeaveTaken", ci);
        gvEmpBonusLeave.Columns[6].HeaderText = rm.GetString("BonusLeaveAllocation_LeaveAvailable", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
        lblEmpSwipe.Text = rm.GetString("TerminalDataType_Card_No", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblLoading.Text = rm.GetString("ProgressBarText", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(96, 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("TransactionLandingPage.aspx");
        }
    }
    public void SortGrid(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        ReloadGrid();
        dtSrch = (DataTable)ViewState["DataBonusLeave"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gvEmpBonusLeave.DataSource = dvSearch;
        gvEmpBonusLeave.DataBind();
    }
    private void ReloadGrid()
    {
        DataTable dtBonusLeave = new DataTable();
        dtBonusLeave = (DataTable)ViewState["DataBonusLeave"];
        foreach (GridViewRow i in gvEmpBonusLeave.Rows)
        {
            int intBonusLeaveQuota = 0;
            string strEmployeeCodeId = Convert.ToString(((Label)i.FindControl("email_EmployeeId")).Text);
            intBonusLeaveQuota = Convert.ToInt16(((TextBox)i.FindControl("txt_BonusLeaveQuota")).Text);
            foreach (DataRow drBonusLeave in dtBonusLeave.Rows)
            {
                if (drBonusLeave["EmployeeId"].ToString() == strEmployeeCodeId)
                {
                    drBonusLeave["BonusLeaveQuota"] = intBonusLeaveQuota;
                }
            }
        }
        dtBonusLeave.AcceptChanges();
        ViewState["DataBonusLeave"] = dtBonusLeave;
    }
    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }
    #endregion
    #region ButtonEvents
    protected void btn_View_Click(object sender, EventArgs e)
    {
        DataSet dsBonusLeave = new DataSet();
        int intEmployeeCategory = 0, intEmployeeType = 0;
        int intCurrentYearSettingId = 0;
        string strEmployeeName = string.Empty;
        string strEmployeeId = string.Empty;
        string strLevelIds = string.Empty;
        if (Session["parentLevelId"] == null || Convert.ToInt32(Session["parentLevelId"]) == 0)
        {
            // strStatus = "Select a company";
            string strScript = string.Empty;
            strScript = "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_SelectCompany", ci) + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertSelectCompany", strScript);
            return;
        }
        int intParentLevelId = Convert.ToInt32(Session["parentLevelId"]);
        // Set Employee Category and Type
        if (Convert.ToInt32(ddlEmpCatagory.SelectedValue) != 0)
        {
            intEmployeeCategory = Convert.ToInt32(ddlEmpCatagory.SelectedValue);
        }
        else
        {
            intEmployeeCategory = 0;
        }
        if (Convert.ToInt32(ddlEmpType.SelectedValue) != 0)
        {
            intEmployeeType = Convert.ToInt32(ddlEmpType.SelectedValue);
        }
        else
        {
            intEmployeeType = 0;
        }
        strEmployeeId = txtEmployeeId.Text.Trim().ToString();
        strEmployeeName = this.txtEmployeeName.Text.Replace("'", "''");
        strEmployeeName = strEmployeeName.Replace(' ', '%');
        string strSwipeCard = "";
        strSwipeCard = txtSwipeCard.Text.ToString().Trim().Replace("'", "''");
        strLevelIds = rptcommon.getNodes(intParentLevelId, Convert.ToString(Session["LevelRights"]));
        intCurrentYearSettingId = GetCurrentYearSettingId();
        dsBonusLeave = objBonusLeave.SelectBonusLeaveDetails(Convert.ToInt32(Session["EmpAutoId"]), strEmployeeId, strEmployeeName, strLevelIds, intEmployeeCategory, intEmployeeType, Convert.ToString(Session["UserGroupName"]), Convert.ToString(Session["GradeLevel"]), intCurrentYearSettingId, strSwipeCard, intParentLevelId);
        DataTable dtProcessedDataCount = new DataTable();
        foreach (DataRow dRowProcessBonusLeave in dsBonusLeave.Tables[0].Rows)
        {
            dtProcessedDataCount = objBonusLeave.SelectProcessDataBonusLeaveDetails(dRowProcessBonusLeave["EmployeeId"].ToString(), gdtmCurrYrStartDate, gdtmCurrYrEndDate);
            if (dtProcessedDataCount.Rows.Count > 0)
            {
                dRowProcessBonusLeave["BonusLeaveTaken"] = Convert.ToInt32(dtProcessedDataCount.Rows[0]["BonusLeaveCount"]);
                dRowProcessBonusLeave["BonusLeaveAvailable"] = Convert.ToInt32(dRowProcessBonusLeave["BonusLeaveQuota"]) - Convert.ToInt32(dtProcessedDataCount.Rows[0]["BonusLeaveCount"]);
            }
            else
            {
                dRowProcessBonusLeave["BonusLeaveAvailable"] = dRowProcessBonusLeave["BonusLeaveQuota"];
            }
        }
        if (dsBonusLeave.Tables[0].Rows.Count > 0)
        {
            divEmployeeGrid.Visible = true;
            btn_Save.Visible = true;
        }
        else
        {
            divEmployeeGrid.Visible = false;
            btn_Save.Visible = false;
        }
        gvEmpBonusLeave.DataSource = dsBonusLeave;
        ViewState["DataBonusLeave"] = dsBonusLeave.Tables[0];
        gvEmpBonusLeave.DataBind();
    }
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        DataTable dtBonusLeave = new DataTable();
        DateTime dtmProcessFromDate = new DateTime();
        int intCurrentYearSettingId = 0;
        foreach (GridViewRow grv in gvEmpBonusLeave.Rows)
        {
            TextBox txtBonusLeaveQuota = (TextBox)grv.FindControl("txt_BonusLeaveQuota");
            Label lblLeavetaken = (Label)grv.FindControl("lbl_BonusLeaveTaken");
            if (txtBonusLeaveQuota.Text == "")
            {
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_FillBonusLeaveQuota", ci) + "');";
                //strScript = strScript + "alert('Fill Bonus Leave Quota');";
                //strScript = strScript + "location.replace('TA_UI_Transactions_BonusLeaveAllocation.aspx');";
                strScript = strScript + "</script>";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                ((ScriptManager)this.Master.FindControl("scTransaction")).SetFocus(txtBonusLeaveQuota);
                return;
            }
            try
            {
                if (Convert.ToInt32(txtBonusLeaveQuota.Text) == 0)
                {
                }
            }
            catch
            {
                //txtBonusLeaveQuota.Focus();
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_EnterValidBonusLeaveQuota", ci) + "');";
                // strScript = strScript + "alert('Enter Valid Bonus Leave Quota');";
                //strScript = strScript + "location.replace('TA_UI_Transactions_BonusLeaveAllocation.aspx');";
                strScript = strScript + "</script>";
                ((ScriptManager)this.Master.FindControl("scTransaction")).SetFocus(txtBonusLeaveQuota);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                return;
            }
            if (Convert.ToInt32(txtBonusLeaveQuota.Text) < 0 || Convert.ToInt32(txtBonusLeaveQuota.Text) > 365)
            {
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("RngOver_TimeOnHolidays", ci) + "');";
                //strScript = strScript + "location.replace('TA_UI_Transactions_BonusLeaveAllocation.aspx');";
                strScript = strScript + "</script>";
                ((ScriptManager)this.Master.FindControl("scTransaction")).SetFocus(txtBonusLeaveQuota);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                return;
            }
            if (Convert.ToInt32(lblLeavetaken.Text) < Convert.ToInt32(txtBonusLeaveQuota.Text))
            {
                txtBonusLeaveQuota.Focus();
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_BonusLeaveQuotashouldnotbelessthanBonusLeaveTaken", ci) + "');";
                //strScript = strScript + "location.replace('TA_UI_Transactions_BonusLeaveAllocation.aspx');";
                strScript = strScript + "</script>";
                ((ScriptManager)this.Master.FindControl("scMaster")).SetFocus(txtBonusLeaveQuota);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
                return;
            }
        }
        ReloadGrid();
        intCurrentYearSettingId = GetCurrentYearSettingId();
        dtBonusLeave = (DataTable)ViewState["DataBonusLeave"];
        foreach (DataRow drBonusLeave in dtBonusLeave.Rows)
        {
            objBonusLeave.InsertUpdateBonusLeave(intCurrentYearSettingId, Convert.ToInt32(drBonusLeave["EmpAutoId"].ToString()), Convert.ToInt32(drBonusLeave["BonusLeaveQuota"].ToString()), Convert.ToInt32(Session["EmpAutoId"]));
            if (DateTime.Parse(drBonusLeave["DateOfJoining"].ToString()) > gdtmCurrYrStartDate)
            {
                dtmProcessFromDate = DateTime.Parse(drBonusLeave["DateOfJoining"].ToString());
            }
            else
            {
                dtmProcessFromDate = gdtmCurrYrStartDate;
            }
            // update ta_tbl_processeddata set processflag = 0 where employee_code_id = employeeid and date > dtmProcessFromDate
            objBonusLeave.UpdateProcessFlagForBonusLeave(drBonusLeave["EmployeeId"].ToString(), Convert.ToString(dtmProcessFromDate));
        }
        //string strSaveAlert = "alert('" + rm.GetString ("Alert_BonusLeavehasbeensuccessfullyallocated",ci) + "');location.replace('TA_UI_Transactions_BonusLeaveAllocation.aspx')";
        //this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", strSaveAlert, true);
        string strScript1 = "";
        strScript1 = strScript1 + "<script language='javascript'>";
        strScript1 = strScript1 + "alert('" + rm.GetString("Alert_BonusLeavehasbeensuccessfullyallocated", ci) + "');";
        strScript1 = strScript1 + "location.replace('TA_UI_Transactions_BonusLeaveAllocation.aspx');";
        strScript1 = strScript1 + "</script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript1, false);
        //ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strSaveAlert, true);
    }
    #endregion
    #region GridviewEvents
    protected void gvEmpBonusLeave_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvEmpBonusLeave.PageIndex = e.NewPageIndex;
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        ReloadGrid();
        dtSrch = (DataTable)ViewState["DataBonusLeave"];
        dvSearch.Table = dtSrch;
        gvEmpBonusLeave.DataSource = dvSearch;
        gvEmpBonusLeave.DataBind();
    }
    protected void gvEmpBonusLeave_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrderBonusLeave"]) == string.Empty)
        {
            Session["SortOrderBonusLeave"] = "Asc";
        }
        else if (Convert.ToString(Session["SortOrderBonusLeave"]) == "Asc")
        {
            Session["SortOrderBonusLeave"] = "Desc";
        }
        else
        {
            Session["SortOrderBonusLeave"] = "Asc";
        }
        SortGrid(e.SortExpression, Convert.ToString(Session["SortOrderBonusLeave"]));
    }
    protected void gvEmpBonusLeave_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            // To display the sorted records in the new page if the Vendor has Sorted the Gridview by clicking any header
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrderBonusLeave"]);
                SortGrid(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion
}
