using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Threading;
using System.Resources;
/****************************************************************************************************************************
* Project Name    : TimeCheck                              Started Date  : 12-Aug-2007
* Module          : Year Closure                           Last Modified : 14-Aug-2007
* Programmer      : Arun Vinoth.T
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_YearClosureModify : Base.BasePage
{
    // object creation
    EmployeeEventData objEmployee = new EmployeeEventData();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    YearClosureEventdata objYearClosureEventdata = new YearClosureEventdata();
    Rpt_Common rptcommon = new Rpt_Common();
    ResourceManager rm;
    CultureInfo ci;
    DataSet dsYearClosure = new DataSet();
    int intIndividualUser = 0;
    int myCount = 0;
    cls_Common objcls_Common = new cls_Common();
    DataSet dsYear = new DataSet();
    string strFinancialYrFromDate = string.Empty, strFinancialYrToDate = "";
    protected override void Page_Load(object sender, EventArgs e)
    {
        // session checking
        base.Page_Load(sender, e);
        //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"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_MaximumValueis365", ci) + "','" + rm.GetString("Alert_Invalidentry", ci) + "','" + rm.GetString("Alert_Availableleavesshouldnotbeempty", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        if (!IsPostBack)
        {
            btnExportExcel.Enabled = false;
            objcls_Common.menu("ExportTran", "62");
            ViewState["parentLevelId"] = 0;
            grv_YearClosure.DataSourceID = "";
            //Check whether the employee is Individual User
            intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
            if (intIndividualUser >= 1)
            {
                PlaceHolderYearClosure.Controls.Clear();
                divEmployeeDetails.Visible = false;
            }
            else
            {
                // Bindings the employee category and type.
                BindingEmployeeCategoryandType();
            }
            dsYear = objcls_Common.GetYearsetting();
            if (dsYear.Tables[0].Rows.Count <= 0)
                MessageWithReplace(rm.GetString("Alert_DefineYearSettinginOrganizationSettings", ci), "../Organization Settings/Organization_YearSetting.aspx");
            else
            {
                strFinancialYrFromDate = (Convert.ToDateTime(dsYear.Tables[0].Rows[0]["FromDate"])).ToString(Convert.ToString(Session["MDateFormat"]));
                strFinancialYrToDate = (Convert.ToDateTime(dsYear.Tables[0].Rows[0]["ToDate"])).ToString(Convert.ToString(Session["MDateFormat"]));
                //(Convert.ToDateTime(System.DateTime.Now.ToShortDateString())).ToString(Convert.ToString(Session["MDateFormat"]));
                ViewState["vsstrFinancialYrFromDate"] = strFinancialYrFromDate;
                ViewState["vsstrFinancialYrToDate"] = strFinancialYrToDate;
                dsYear.Dispose();
            }
        }
        else
        {
        }
    }
    //Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        btn_View.Text = "&nbsp;&nbsp;" + rm.GetString("btn_View", ci);
        btn_Back.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        btnExportExcel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_ExporttoExcel", ci);
        lbl_Header.Text = rm.GetString("UserGroups_YearClosure", 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);
        grv_YearClosure.Columns[1].HeaderText = rm.GetString("email_EmployeeId", ci);
        grv_YearClosure.Columns[2].HeaderText = rm.GetString("email_EmployeeName", ci);
        grv_YearClosure.Columns[3].HeaderText = rm.GetString("lbl_leavetype", ci);
        grv_YearClosure.Columns[4].HeaderText = rm.GetString("YearClosure_CarryPrevYear", ci);
        //grv_YearClosure.Columns[5].HeaderText = rm.GetString("YearClosure_CarryPrevYearCompOff", ci);
        grv_YearClosure.Columns[5].HeaderText = rm.GetString("YearClosure_CurrentQuota", ci);
        grv_YearClosure.Columns[6].HeaderText = rm.GetString("YearClosure_BorrowNextYear", ci);
        grv_YearClosure.Columns[7].HeaderText = rm.GetString("BonusLeaveAllocation_LeaveTaken", ci);
        grv_YearClosure.Columns[8].HeaderText = rm.GetString("LeaveApplication_RemainingNumberOfLeave", ci);
        grv_YearClosure.Columns[9].HeaderText = rm.GetString("Transaction_Encashment", 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);
    }
    /// <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);
            }
        }
    }
    protected void btn_View_Click(object sender, EventArgs e)
    {
        //Response.Redirect("TA_UI_Transactions_YearClosureModify.aspx?EmployeeName=Christopher");
        string employeeName = string.Empty, employeeCodeId = string.Empty, employeeCategory = string.Empty, employeeType = string.Empty, employeeLevel = string.Empty;
        employeeName = txtEmployeeName.Text;
        employeeCodeId = txtEmployeeId.Text;
        employeeCategory = ddlEmpCatagory.SelectedValue;
        employeeType = ddlEmpType.SelectedValue;
        employeeLevel = rptcommon.getNodes(Convert.ToInt16(Session["parentLevelId"]), Convert.ToString(Session["LevelRights"]));
        string strSwipeCard = "";
        strSwipeCard = txtSwipeCard.Text.ToString().Trim().Replace("'", "''");
        ViewState["vsSwipeCard"] = strSwipeCard;
        ViewState["vsEmployeeName"] = employeeName;
        ViewState["employeeCodeId"] = employeeCodeId;
        ViewState["employeeCategory"] = employeeCategory;
        ViewState["employeeType"] = employeeType;
        ViewState["employeeLevel"] = employeeLevel;
        ViewState["parentLevelId"] = Session["parentLevelId"];
        bindGridYearClosure();
    }
    protected void grv_YearClosure_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label lbl_YearClosure_Id = (Label)grv_YearClosure.Rows[e.RowIndex].FindControl("lblYearClosureId");
        Label lbl_EmployeeCode_Id = (Label)grv_YearClosure.Rows[e.RowIndex].FindControl("lblEmployee_code_Id");
        TextBox txtCarryPrevYear = (TextBox)grv_YearClosure.Rows[e.RowIndex].FindControl("txt_Carry_PrevYear");
        HiddenField hdnCarryPrevYear = (HiddenField)grv_YearClosure.Rows[e.RowIndex].FindControl("hdnCarryPrevYear");
        //TextBox txtCurrentQuota = (TextBox)grv_YearClosure.Rows[e.RowIndex].FindControl("txt_Current_Quota");
        //TextBox txtBorrowNextYear = (TextBox)grv_YearClosure.Rows[e.RowIndex].FindControl("txt_Borrow_NextYear");
        //TextBox txtLeaveTaken = (TextBox)grv_YearClosure.Rows[e.RowIndex].FindControl("txt_Leave_Taken");
        //TextBox txtAvailableLeaves = (TextBox)grv_YearClosure.Rows[e.RowIndex].FindControl("txt_Available_Leaves");
        Label lblCurrentQuota = (Label)grv_YearClosure.Rows[e.RowIndex].FindControl("lblCurrent_Quota");
        Label lblBorrowNextYear = (Label)grv_YearClosure.Rows[e.RowIndex].FindControl("lblBorrow_NextYear");
        Label lblLeaveTaken = (Label)grv_YearClosure.Rows[e.RowIndex].FindControl("lblLeave_Taken");
        Label lblAvailableLeaves = (Label)grv_YearClosure.Rows[e.RowIndex].FindControl("lblAvailable_Leaves");
        //TextBox txtEncashment = (TextBox)grv_YearClosure.Rows[e.RowIndex].FindControl("txt_Encashment");
        Label lblEncashment = (Label)grv_YearClosure.Rows[e.RowIndex].FindControl("lblEncashment");
        float fltEncashment = Convert.ToSingle(lblEncashment.Text);
        float fltAvailableLeaves = Convert.ToSingle(txtCarryPrevYear.Text) + Convert.ToSingle(lblCurrentQuota.Text) + Convert.ToSingle(lblBorrowNextYear.Text) - Convert.ToSingle(lblLeaveTaken.Text);
        if (fltEncashment > fltAvailableLeaves)
        {
            lblError.Text = "Encashment days should not be greater than calculated available leaves (" + fltAvailableLeaves.ToString() + ")";
            return;
        }
        else
        {
            fltAvailableLeaves = fltAvailableLeaves - fltEncashment;
            lblError.Text = "";
        }
        objYearClosureEventdata.updateYearClosureModify(Convert.ToInt32(lbl_YearClosure_Id.Text), Convert.ToSingle(txtCarryPrevYear.Text), Convert.ToSingle(lblCurrentQuota.Text), Convert.ToSingle(lblBorrowNextYear.Text), Convert.ToSingle(lblLeaveTaken.Text), fltAvailableLeaves, Convert.ToSingle(lblEncashment.Text));
        grv_YearClosure.EditIndex = -1;
        //objYearClosureEventdata.updateYearClosureModify();
        bindGridYearClosure();
    }
    protected void grv_YearClosure_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grv_YearClosure.EditIndex = e.NewEditIndex;
        lblError.Text = "";
        bindGridYearClosure();
    }
    private void bindGridYearClosure()
    {
        //Changing  ViewState["parentLevelId"]  from Session["parentLevelId"]
        dsYearClosure = objYearClosureEventdata.selectYearclosureDetailsForModify
                    (
                        Convert.ToString(ViewState["vsEmployeeName"]),
                        Convert.ToString(ViewState["employeeCodeId"]),
                        Convert.ToString(ViewState["employeeLevel"]),
                        Convert.ToString(ViewState["employeeCategory"]),
                        Convert.ToString(ViewState["employeeType"]),
                        Convert.ToString(Session["UserGroupName"]),
                        Convert.ToString(Session["GradeLevel"]),
                        Convert.ToString(ViewState["vsSwipeCard"]),
                        Convert.ToInt16(ViewState["parentLevelId"])
                    );
        if (dsYearClosure.Tables.Count > 0)
        {
            if (dsYearClosure.Tables[0].Rows.Count > 0)
            {
                grv_YearClosure.DataSource = dsYearClosure;
                grv_YearClosure.DataBind();
                btnExportExcel.Enabled = true;
            }
        }
        else
        {
            btnExportExcel.Enabled = false;
            Message(rm.GetString("Alert_Thereisnorecord", ci));
            return;
        }
    }
    protected void grv_YearClosure_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grv_YearClosure.EditIndex = -1;
        lblError.Text = "";
        bindGridYearClosure();
    }
    protected void grv_YearClosure_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_YearClosure.PageIndex = e.NewPageIndex;
        lblError.Text = "";
        bindGridYearClosure();
    }
    protected void btn_Back_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_YearClosureAdd.aspx");
    }
    protected void grv_YearClosure_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        e.Row.Cells[0].BorderColor = System.Drawing.Color.White;
        e.Row.Cells[0].BorderWidth = 1;
        e.Row.Cells[0].BorderStyle = BorderStyle.Solid;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lbEdit = new LinkButton();
            lbEdit = (LinkButton)e.Row.Cells[0].Controls[0];
            if (lbEdit.Text == "Edit")
            {
                lbEdit.Text = rm.GetString("Grid_Edit", ci);
            }
            else if (lbEdit.Text == "Update")
            {
                lbEdit.Text = rm.GetString("Grid_Update", ci);
                LinkButton lbCancel = new LinkButton();
                lbCancel = (LinkButton)e.Row.Cells[0].Controls[2];
                if (lbCancel.Text == "Cancel")
                {
                    lbCancel.Text = rm.GetString("btn_Cancel", ci);
                }
            }
        }
    }

    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet dsYearClosure = new DataSet();
            if (Page.IsValid == true)
            {
                dsYearClosure = objYearClosureEventdata.selectYearclosureDetailsForModify
                    (
                        Convert.ToString(ViewState["vsEmployeeName"]),
                        Convert.ToString(ViewState["employeeCodeId"]),
                        Convert.ToString(ViewState["employeeLevel"]),
                        Convert.ToString(ViewState["employeeCategory"]),
                        Convert.ToString(ViewState["employeeType"]),
                        Convert.ToString(Session["UserGroupName"]),
                        Convert.ToString(Session["GradeLevel"]),
                        Convert.ToString(ViewState["vsSwipeCard"]),
                        Convert.ToInt16(ViewState["parentLevelId"])
                    );
                if (dsYearClosure.Tables["Table"] == null || dsYearClosure.Tables["Table"].Rows.Count == 0)
                {
                    Message(rm.GetString("Alert_Thereisnorecord", ci));
                    return;
                }
                else
                {
                    Session["Export_ExcelData"] = dsYearClosure;
                    if (dsYearClosure.Tables[0].Columns.Contains("Carry_PrevYear"))
                        dsYearClosure.Tables[0].Columns["Carry_PrevYear"].ColumnName = "Carry Prev Year";
                    if (dsYearClosure.Tables[0].Columns.Contains("LeaveType"))
                        dsYearClosure.Tables[0].Columns["LeaveType"].ColumnName = "Leave Type";
                    if (dsYearClosure.Tables[0].Columns.Contains("Current_Quota"))
                        dsYearClosure.Tables[0].Columns["Current_Quota"].ColumnName = "Current Quota";
                    if (dsYearClosure.Tables[0].Columns.Contains("Borrow_NextYear"))
                        dsYearClosure.Tables[0].Columns["Borrow_NextYear"].ColumnName = "Borrow Next Year";
                    if (dsYearClosure.Tables[0].Columns.Contains("Leave_Taken"))
                        dsYearClosure.Tables[0].Columns["Leave_Taken"].ColumnName = "Leave Taken";
                    if (dsYearClosure.Tables[0].Columns.Contains("Available_Leaves"))
                        dsYearClosure.Tables[0].Columns["Available_Leaves"].ColumnName = "Available Leaves";
                    if (dsYearClosure.Tables[0].Columns.Contains("YearClosureId"))
                        dsYearClosure.Tables[0].Columns.Remove("YearClosureId");
                    if (dsYearClosure.Tables[0].Columns.Contains("LeaveTypeID"))
                        dsYearClosure.Tables[0].Columns.Remove("LeaveTypeID");
                    if (dsYearClosure.Tables[0].Columns.Contains("EmployeeAutoId"))
                        dsYearClosure.Tables[0].Columns.Remove("EmployeeAutoId");
                    if (dsYearClosure.Tables[0].Columns.Contains("Gender"))
                        dsYearClosure.Tables[0].Columns.Remove("Gender");
                    if (ViewState["vsstrFinancialYrFromDate"] != null)
                    {
                        strFinancialYrFromDate = Convert.ToString(ViewState["vsstrFinancialYrFromDate"]);
                    }
                    if (ViewState["vsstrFinancialYrToDate"] != null)
                    {
                        strFinancialYrToDate = Convert.ToString(ViewState["vsstrFinancialYrToDate"]);
                    }
                    Response.Redirect("../Reports/Excel_Export.aspx?ReportName=Year Closure&FrmDate=" + strFinancialYrFromDate + "&ToDate=" + strFinancialYrToDate);
                    //ExportExcel(dsEmp);
                }
            }
        }
        catch (Exception ex)
        {
            Message(ex.ToString());
        }
    }
}
