using System;
using System.Data;
using System.Globalization;
using System.IO;
using System.Resources;
using System.Threading;
using System.Web.UI;
using System.Web.UI.WebControls;
/****************************************************************************************************************************
* Project Name    : TimeCheck                                                          Started Date  : 24-July-2007
* Module          : Payroll Process                                                    Last Modified : 12-Aug-2007
* Programmer      : Kumuthini.L
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          : \\windev\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_MonthClosureView : Base.BasePage
{
    #region "Variable Declaration"
    ResourceManager rm;
    CultureInfo ci;
    DataSet ds_Checkuser = new DataSet();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    MonthClosureEventData objMonthClosure = new MonthClosureEventData();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    ShiftExchangeEventData objShiftExchangeEventData = new ShiftExchangeEventData();
    ShiftEvenData objShiftEvenData = new ShiftEvenData();
    HolidayEventData objHolidayEventData = new HolidayEventData();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    LeaveEventData objLeaveEventData = new LeaveEventData();
    cls_Common objcls_Common = new cls_Common();
    Rpt_Common rptcommon = new Rpt_Common();
    int gintUserId, MonthCloseID = 0;
    string strGroupName = string.Empty;
    string strStartDate, strEndDate, gstrDateFormat, closedDate;
    string gstrLevels = string.Empty;
    string gstrEmployeeId = string.Empty, gstrDate = string.Empty;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        grv_MonthClosure.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        if (Session["Session_ActiveLanguage"] == null)
        {
            Response.Redirect("../index.aspx");
        }
        else
        {
            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"]);
        gintUserId = Int32.Parse(Session["EmpAutoID"].ToString());
        MonthCloseID = Convert.ToInt32(Request.QueryString["MonthClose_Id"]);        
        strGroupName = objEmployeeEventData.GetEmployeeGroupName(gintUserId);
        if (strGroupName == "SuperAdmin")
        {
            btn_IndividualReprocess.Visible = true;
            btn_LevelwiseReprocess.Visible = true;
        }
        else
        {
            btn_IndividualReprocess.Visible = false;
            btn_LevelwiseReprocess.Visible = false;
        }      
        if (!IsPostBack)
        {
            userrights();
            
            LoadStrings(ci);
            objcls_Common.menu("ExportTran", "27");
            grv_MonthClosure.Visible = false;
            btn_Delete.OnClientClick = "javascript:return confirm('" + rm.GetString("Alert_confirmdeleteselectedmonthclosuredetails", ci) + "')";
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            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);
        }
        LoadMonthCloseDetails();
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strStartDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_StartDate.Text);
        strEndDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_EndDate.Text);
        closedDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_ClosedDate.Text);
        int count = 0;
        count = objMonthClosure.CheckMonthClosureProcessFlag(MonthCloseID);
        if (count != 0)
        {
            btn_IndividualReprocess.Attributes.Add("onclick", " document.getElementById('ctl00_BodyContentPH_iframePopup').src ='PayrollReprocessPopup.aspx?MonthCloseID=" + MonthCloseID + "&LevelId=" + Convert.ToInt16(lbl_LevelId.Text) + "&FromDate=" + strStartDate + "&ToDate=" + strEndDate + "','Test';return false;");
            //"window.open('PayrollReprocessPopup.aspx?MonthCloseID=" + MonthCloseID + "&LevelId=" + gstrLevels + "&FromDate=" + strStartDate + "&ToDate=" + strEndDate + "','Test','height=500,top=200,left=250,width=500');return false;");
        }
        if (Session["MonthClosure"] != string.Empty && Session["MonthClosure"] != string.Empty)
        {
            grv_MonthClosure.DataSource = (DataSet)Session["MonthClosure"];
        }
    }
    #endregion
    #region UserDefinedFunctions
    // **********************************************************************************************************************
    // Function Name : LoadMonthCloseDetails
    // Purpose :
    //     The LoadMonthCloseDetails Method is used to get the Details of the Payroll Process Details for a particular 
    //     Month Closure ID and the details are assigned to the appropriate Labels for View
    // **********************************************************************************************************************
    private void LoadMonthCloseDetails()
    {
        DataSet dsMonthCloseDetails = new DataSet();
        DataTable dtMonthCloseDetails = new DataTable();
        dsMonthCloseDetails = objMonthClosure.SelectMonthCloseDetailsByIDview(MonthCloseID);
        dtMonthCloseDetails = dsMonthCloseDetails.Tables[0];
        if (dtMonthCloseDetails.Rows.Count > 0)
        {
            if (dtMonthCloseDetails.Rows[0]["OrgLevel_Id"] != DBNull.Value)
            {
                lbl_LevelId.Text = dtMonthCloseDetails.Rows[0]["OrgLevel_Id"].ToString();
            }
            if (dtMonthCloseDetails.Rows[0]["name"] != DBNull.Value)
            {
                lbl_LevelName.Text = dtMonthCloseDetails.Rows[0]["name"].ToString();
            }
            if (dtMonthCloseDetails.Rows[0]["MonthClosure_Month"] != DBNull.Value)
            {
                lbl_Month.Text = dtMonthCloseDetails.Rows[0]["MonthClosure_Month"].ToString();
                switch (lbl_Month.Text)
                {
                    case "January":
                        lbl_Month.Text = rm.GetString("January", ci);
                        break;
                    case "February":
                        lbl_Month.Text = rm.GetString("February", ci);
                        break;
                    case "March":
                        lbl_Month.Text = rm.GetString("March", ci);
                        break;
                    case "April":
                        lbl_Month.Text = rm.GetString("April", ci);
                        break;
                    case "May":
                        lbl_Month.Text = rm.GetString("May", ci);
                        break;
                    case "June":
                        lbl_Month.Text = rm.GetString("June", ci);
                        break;
                    case "July":
                        lbl_Month.Text = rm.GetString("July", ci);
                        break;
                    case "August":
                        lbl_Month.Text = rm.GetString("August", ci);
                        break;
                    case "September":
                        lbl_Month.Text = rm.GetString("September", ci);
                        break;
                    case "October":
                        lbl_Month.Text = rm.GetString("October", ci);
                        break;
                    case "November":
                        lbl_Month.Text = rm.GetString("November", ci);
                        break;
                    case "December":
                        lbl_Month.Text = rm.GetString("December", ci);
                        break;
                }
            }
            if (dtMonthCloseDetails.Rows[0]["MonthClosure_Year"] != DBNull.Value)
            {
                lbl_Year.Text = dtMonthCloseDetails.Rows[0]["MonthClosure_Year"].ToString();
            }
            if (dtMonthCloseDetails.Rows[0]["MonthClosure_StartDate"] != DBNull.Value)
            {
                lbl_StartDate.Text = (DateTime.Parse(dtMonthCloseDetails.Rows[0]["MonthClosure_StartDate"].ToString())).ToString(Session["MDateFormat"].ToString());
            }
            if (dtMonthCloseDetails.Rows[0]["MonthClosure_EndDate"] != DBNull.Value)
            {
                lbl_EndDate.Text = (DateTime.Parse(dtMonthCloseDetails.Rows[0]["MonthClosure_EndDate"].ToString())).ToString(Session["MDateFormat"].ToString());
            }
            if (dtMonthCloseDetails.Rows[0]["MonthClosure_ClosingDate"] != DBNull.Value)
            {
                lbl_ClosedDate.Text = (DateTime.Parse(dtMonthCloseDetails.Rows[0]["MonthClosure_ClosingDate"].ToString())).ToString(Session["MDateFormat"].ToString());
            }
        }
        gstrLevels = rptcommon.getNodes(Convert.ToInt16(lbl_LevelId.Text), Convert.ToString(Session["LevelRights"]));
    }
    public void PayrollProcess(string inType, string strEmployees)
    {
        try
        {
            string strStartDate, strEndDate;
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strStartDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_StartDate.Text);
            strEndDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_EndDate.Text);
            DateTime dtmStartDate = DateTime.Parse(strStartDate);
            DateTime dtmEndDate = DateTime.Parse(strEndDate);
            DataSet dsEmpDetails = new DataSet();
            DataTable dtPayroll = new DataTable();
            int intProcessedCount = 0;
            intProcessedCount = objMonthClosure.CheckMonthClosureProcessFlag(MonthCloseID);
            dsEmpDetails = objEmployeeEventData.Select_EmployeeDetailsForMonthClosure(strEndDate, gstrLevels, Convert.ToString(Session["UserGroupName"]), Convert.ToInt32(lbl_LevelId.Text), MonthCloseID, gintUserId, intProcessedCount, inType, strEmployees, "", "");
            if (inType == "Process")
            {
                objMonthClosure.UpdateMonthClosureProcessFlag(MonthCloseID);
            }
            else if (inType == "Preview")
            {
                Response.Redirect("TA_UI_Transactions_MonthClosurePreview.aspx?MonthClose_Id=" + MonthCloseID + "");
            }
            else
            {
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = string.Empty;
            string strErrorMessage = "<script language='javascript' type='text/javascript'>";
            strErrorMessage += "alert('" + ex.Message + "');";
            strErrorMessage += "</script>";
            this.RegisterStartupScript("setScript", strErrorMessage);
        }
    }
    // Function to Convert hh:mm format to Total Minutes
    public double ConvertHoursMinsToMinutes(string inHoursMins)
    {
        int intTotalMinutes = 0, intHours = 0, intMinutes = 0;
        string[] HoursMins = inHoursMins.Split(':');
        intHours = Int16.Parse(HoursMins[0]);
        intMinutes = Int16.Parse(HoursMins[1]);
        intTotalMinutes = (intHours * 60) + intMinutes;
        return (double.Parse(intTotalMinutes.ToString()));
    }
    // Function to Convert Total Minutes to hh:mm format
    public string TimeFormat(double TotMins)
    {
        string strHrsMins = string.Empty;
        double dHrs = Math.Floor(TotMins / 60);
        double dMins = TotMins % 60;
        int iHrs = Convert.ToInt32(dHrs);
        int iMins = Convert.ToInt32(dMins);
        if (Convert.ToInt32(dMins) >= 60)
        {
            iMins = Convert.ToInt32(dMins) % 60;
            iHrs += Convert.ToInt32(dMins) / 60;
        }
        strHrsMins = iHrs.ToString("00") + ":" + iMins.ToString("00");
        return (strHrsMins);
    }
    /// <summary>
    /// GetShiftId Function is used to get the Shift Id for the particular Employee
    /// </summary>
    /// <param name="strEmployee">Employee Id</param>
    /// <param name="dtmDate">Date</param>
    /// <returns></returns>
    /// 
    private int GetShiftId(string strEmployee, DateTime dtmDate)
    {
        int intShiftId = 0;
        DataTable dtTempShift = new DataTable();
        dtTempShift = objShiftExchangeEventData.SelectTemporaryShiftId(strEmployee, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
        DataTable dtActualShift = new DataTable();
        dtActualShift = objShiftExchangeEventData.SelectPermanentShiftId(strEmployee, dtmDate.Year.ToString(), dtmDate.Month.ToString(), dtmDate.Day.ToString());
        if (dtTempShift.Rows.Count > 0)
        {
            if (dtTempShift.Rows[0][0] != DBNull.Value && dtTempShift.Rows[0][0].ToString() == string.Empty)
            {
                intShiftId = int.Parse(dtTempShift.Rows[0][0].ToString());
            }
        }
        if (intShiftId == 0)
        {
            if (dtActualShift.Rows.Count > 0)
            {
                if (dtActualShift.Rows[0][0] != DBNull.Value && dtActualShift.Rows[0][0].ToString() == string.Empty)
                {
                    intShiftId = int.Parse(dtActualShift.Rows[0][0].ToString());
                }
            }
        }
        return (intShiftId);
    }
    // Function to Convert Total Minutes to hh:mm format
    public string ConvertMinutesToHoursMins(double inTotalMinutes)
    {
        string strHoursMins = "00:00";
        double dTotHrs = Math.Floor(inTotalMinutes / 60);
        double dTotMins = inTotalMinutes % 60;
        int iTotHrs = Convert.ToInt32(dTotHrs);
        int iTotMins = Convert.ToInt32(dTotMins);
        if (Convert.ToInt32(dTotMins) >= 60)
        {
            iTotMins = Convert.ToInt32(dTotMins) % 60;
            iTotHrs += Convert.ToInt32(dTotMins) / 60;
        }
        strHoursMins = iTotHrs.ToString("00") + ":" + iTotMins.ToString("00");
        return (strHoursMins);
    }
    // Function to check Additional Weekly Off
    public int CheckAdditionalWeekOff(DateTime dtmDate, string EmployeeId)
    {
        DateTime startOfMonth;
        string strStartOfMonth;
        int DaysToAdd, NthWeek = 0, TargetDayOfWeek = 0;
        string flag = "NE";
        try
        {
            DataTable dtAdditionalWeekOff = new DataTable();
            dtAdditionalWeekOff = objMonthClosure.GetAdditionalWeekOff(EmployeeId, dtmDate.ToShortDateString());
            if (dtAdditionalWeekOff.Rows.Count > 0)
            {
                foreach (DataRow drRow in dtAdditionalWeekOff.Rows)
                {
                    if (drRow["Addl_WeekOff_Day"] != DBNull.Value && drRow["Addl_WeekOff_Day"].ToString() != string.Empty)
                    {
                        TargetDayOfWeek = GetWeekDay(drRow["Addl_WeekOff_Day"].ToString());
                    }
                    if (drRow["Addl_WeekOff_Week"] != DBNull.Value && drRow["Addl_WeekOff_Week"].ToString() != string.Empty)
                    {
                        string strTargetDayOfWeek = Convert.ToString(drRow["Addl_WeekOff_Week"]);
                        switch (strTargetDayOfWeek)
                        {
                            case "First Week":
                                NthWeek = 1;
                                break;
                            case "Second Week":
                                NthWeek = 2;
                                break;
                            case "Third Week":
                                NthWeek = 3;
                                break;
                            case "Fourth Week":
                                NthWeek = 4;
                                break;
                            case "Fifth Week":
                                NthWeek = 5;
                                break;
                            default:
                                NthWeek = 0;
                                break;
                        }
                    }
                    if (NthWeek != 0 && TargetDayOfWeek != 0)
                    {
                        strStartOfMonth = dtmDate.Month + "/01/" + dtmDate.Year;
                        startOfMonth = DateTime.Parse(strStartOfMonth);
                        string WeekDayName = startOfMonth.DayOfWeek.ToString();
                        int WeekDay = GetWeekDay(WeekDayName);
                        DaysToAdd = (7 - (WeekDay + (7 - TargetDayOfWeek)) % 7) % 7;
                        DateTime dtmResult = startOfMonth.AddDays(DaysToAdd + ((NthWeek - 1) * 7));
                        if (dtmResult == dtmDate)
                        {
                            flag = "E";
                        }
                    }
                }
            }
            if (flag == "E")
            {
                return (1);
            }
            else
            {
                return (0);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public int GetWeekDay(string WeekDayName)
    {
        int intWeekDay = 0;
        switch (WeekDayName)
        {
            case "Sunday":
                intWeekDay = 1;
                break;
            case "Monday":
                intWeekDay = 2;
                break;
            case "Tuesday":
                intWeekDay = 3;
                break;
            case "Wednesday":
                intWeekDay = 4;
                break;
            case "Thursday":
                intWeekDay = 5;
                break;
            case "Friday":
                intWeekDay = 6;
                break;
            case "Saturday":
                intWeekDay = 7;
                break;
        }
        return (intWeekDay);
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("UserGroups_MonthClosure", ci);
        lbl_ClosedDate1.Text = rm.GetString("PayrollProcess_ClosedDate", ci);
        lbl_EndDate1.Text = rm.GetString("PayrollProcess_EndDate", ci);
        lbl_Month1.Text = rm.GetString("PayrollProcess_Month", ci);
        lbl_StartDate1.Text = rm.GetString("PayrollProcess_StartDate", ci);
        lbl_Year1.Text = rm.GetString("PayrollProcess_Year", ci);
        lbl_LevelName1.Text = rm.GetString("LevelDetails_LevelName", ci);
        btn_Save.Text = "&nbsp&nbsp" + rm.GetString("btn_Process", ci);
        btn_LevelwiseReprocess.Text = "&nbsp" + rm.GetString("btn_LevelwiseReprocess", ci);
        btn_IndividualReprocess.Text = "&nbsp" + rm.GetString("btn_IndividualReprocess", ci);
        btnPreview.Text = "&nbsp&nbsp" + rm.GetString("btn_Preview", ci);
        btn_View.Text = "&nbsp&nbsp" + rm.GetString("btn_View", ci);
        btn_Delete.Text = "&nbsp&nbsp" + rm.GetString("btn_Delete", ci);
        btn_Cancel.Text = "&nbsp&nbsp" + rm.GetString("btn_Back", ci);
        grv_MonthClosure.Columns[0].Caption = rm.GetString("lbl_EmpID", ci);
        grv_MonthClosure.Columns[1].Caption = rm.GetString("lbl_EmpName", ci);
        grv_MonthClosure.Columns[2].Caption = rm.GetString("lbl_P", ci);
        grv_MonthClosure.Columns[2].ToolTip = "Present Days";
        grv_MonthClosure.Columns[3].Caption = rm.GetString("lbl_A", ci);
        grv_MonthClosure.Columns[3].ToolTip = "Absent Days";
        grv_MonthClosure.Columns[4].Caption = rm.GetString("lbl_L", ci);
        grv_MonthClosure.Columns[4].ToolTip = "Leave Days";
        grv_MonthClosure.Columns[5].Caption = rm.GetString("lbl_Off", ci);
        grv_MonthClosure.Columns[5].ToolTip = "Week End Days";
        grv_MonthClosure.Columns[6].Caption = rm.GetString("lbl_LOP", ci);
        grv_MonthClosure.Columns[6].ToolTip = "LOP Days"; ;
        grv_MonthClosure.Columns[7].Caption = rm.GetString("lbl_H", ci);
        grv_MonthClosure.Columns[7].ToolTip = "Holiday";

        grv_MonthClosure.Columns[8].Caption = rm.GetString("lbl_HW", ci);
        grv_MonthClosure.Columns[9].Caption = rm.GetString("lbl_EH", ci);
        grv_MonthClosure.Columns[10].Caption = rm.GetString("lbl_LH", ci);
        grv_MonthClosure.Columns[11].Caption = rm.GetString("lbl_NOT", ci);
        grv_MonthClosure.Columns[12].Caption = rm.GetString("lbl_WOT", ci);
        grv_MonthClosure.Columns[13].Caption = rm.GetString("lbl_HOT", ci);
        grv_MonthClosure.Columns[14].Caption = rm.GetString("lbl_PH", ci);
        grv_MonthClosure.Columns[15].Caption = rm.GetString("lbl_LIH", ci);
        grv_MonthClosure.Columns[16].Caption = rm.GetString("lbl_EOH", ci);

        //grv_MonthClosure.Columns[18].Caption = "N-SOT1";
        //grv_MonthClosure.Columns[19].Caption = "N-SOT2";
        //grv_MonthClosure.Columns[20].Caption = "WO-SOT1";
        //grv_MonthClosure.Columns[21].Caption = "WO-SOT2";
        //grv_MonthClosure.Columns[22].Caption = "H-SOT1";
        //grv_MonthClosure.Columns[23].Caption = "H-SOT2";


        lbl_Mon_Individual_Reprocess.Text = rm.GetString("lbl_Month_Closure_Individual", ci);
        lbl_PresentDays.Text = rm.GetString("MonthClose_Present", ci);
        lbl_AbsentDays.Text = rm.GetString("MonthClose_Absent", ci);
        lbl_LeaveDays.Text = rm.GetString("MonthClose_LeaveDays", ci);
        lbl_WeeklyOffDays.Text = rm.GetString("MonthClose_WeeklyOffDays", ci);
        lbl_LOPDays.Text = rm.GetString("MonthClose_LOPDays", ci);
        lbl_Holidays.Text = rm.GetString("MonthClose_Holidays", ci);
        lbl_HoursWorked.Text = rm.GetString("MonthClose_HoursWorked", ci);
        lbl_ExtraHours.Text = rm.GetString("MonthClose_ExtraHours", ci);
        lbl_LessHoursWorked.Text = rm.GetString("MonthClose_LessHoursWorked", ci);
        lbl_NormalOT.Text = rm.GetString("MonthClose_NormalOT", ci);
        lbl_WeeklyOffOT.Text = rm.GetString("MonthClose_WeeklyOffOT", ci);
        lbl_HolidayOT.Text = rm.GetString("MonthClose_HolidayOT", ci);
        lbl_PermissionHours.Text = rm.GetString("MonthClose_PermissionHours", ci);
        lbl_LateInHours.Text = rm.GetString("MonthClose_LateInHours", ci);
        lbl_EarlyOutHours.Text = rm.GetString("MonthClose_EarlyOutHours", ci);
    }
    private void userrights()
    {
        try
        {
            ds_Checkuser = objCheckUser.checkRights(27, Convert.ToInt32(Session["userGroup_Id"]), string.Empty);
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] == DBNull.Value || Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) != 1)
            {
                Response.Redirect("TA_UI_Transactions_MonthClosure.aspx");
            }
        }
        catch
        {
        }
    }
    private void BindingMonthClosureGrid(int monthClosureId, int levelId, string strStartDate, string strEndDate, string closedDate)
    {
        DataSet dsMonthClosure = objMonthClosure.SelectMonthClosureDetailsForModifyGrid(monthClosureId, levelId, strStartDate, strEndDate, closedDate);
        grv_MonthClosure.DataSource = dsMonthClosure;
        Session["MonthClosure"] = dsMonthClosure;
        grv_MonthClosure.DataBind();
        if (dsMonthClosure.Tables.Count > 0)
        {
            if (dsMonthClosure.Tables[0].Rows.Count == 0)
            {
                base.Message(rm.GetString("Alert_Norecordsfound", ci));
            }
            else
            {
                btnExport.Enabled = true;
                btnExportPdf.Enabled = true;
            }
        }
        legends.Style.Add("display", "block");
    }
    #endregion
    #region ButtonEvents
    protected void btn_Save_Click(object sender, EventArgs e)
    {
        lblMessage.Text = string.Empty;
        string strLevels = string.Empty;
        DataTable dtDiscrepancies = new DataTable();
        int count = 0;
        count = objMonthClosure.CheckMonthClosureProcessFlag(MonthCloseID);
        if (count == 0)
        {
            // Check in the Clock Details Table for Discrepancies for specified Start Date and End Date
            //dtDiscrepancies = objMonthClosure.GetDiscrepanciesForPayroll(strStartDate, strEndDate, gstrLevels);
            dtDiscrepancies = objMonthClosure.GetDiscrepanciesForPayroll(strStartDate, strEndDate, gstrLevels, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
            // If there Discrepancies, then the Datas cannot be Processed. So Before Processing, Discrepancies should be Closed through 
            // Manual Time Entry
            // If there is no Records i.e., No Discrepancies
            if (dtDiscrepancies.Rows.Count == 0)
            {
                try
                {
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    strStartDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_StartDate.Text);
                    strEndDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_EndDate.Text);
                    DateTime dtmStartDate = DateTime.Parse(strStartDate);
                    DateTime dtmEndDate = DateTime.Parse(strEndDate);
                    DataSet dsProcess = new DataSet();
                    DataTable dtProcess = new DataTable("ReprocessEmployees");
                    DataColumn dcProcess = new DataColumn();
                    dcProcess.DataType = System.Type.GetType("System.String");
                    dcProcess.ColumnName = "EmployeeId";
                    dtProcess.Columns.Add(dcProcess);
                    dsProcess.Tables.Add(dtProcess);
                    StringWriter strWriteXML = new StringWriter();
                    dsProcess.Tables[0].WriteXml(strWriteXML);
                    string strResult = string.Empty;
                    if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_EN")
                    {
                        strResult = objMonthClosure.ProcessDataCountEmployees(gstrLevels, dtmStartDate, dtmEndDate, strWriteXML.ToString(), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
                    }
                    else if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_AR")
                    {
                        strResult = objMonthClosure.ProcessDataCountEmployees_Arabic(gstrLevels, dtmStartDate, dtmEndDate, strWriteXML.ToString(), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
                    }
                    if (strResult == string.Empty)
                    {
                        PayrollProcess("Process", strWriteXML.ToString());
                        base.Message(rm.GetString("Msg_DatahasbeenProcessedforPayroll", ci));
                    }
                    else
                    {
                        base.Message(strResult);
                        return;
                    }
                }
                catch
                {
                }
            }
            // If there are Records i.e., there are Discrepancies. 
            else if (dtDiscrepancies.Rows.Count > 0)
            {
                lblMessage.Text = rm.GetString("Alert_ClosealltheDiscrepanciestoprocesstheData", ci);
                Response.Redirect("TA_UI_Transactions_PayrollProcessGrid.aspx?StartDate=" + strStartDate + "&EndDate=" + strEndDate + "&LevelID=" + Convert.ToInt16(lbl_LevelId.Text) + "&MonClosureId=" + MonthCloseID + "");
                return;
            }
        }
        else
        {
            base.Message(rm.GetString("Msg_DatahasalreadybeenProcessed", ci));
            return;
        }
    }
    protected void btnPreview_Click(object sender, EventArgs e)
    {
        lblMessage.Text = string.Empty;
        string strLevels = string.Empty;
        DataTable dtDiscrepancies = new DataTable();
        // Check in the Clock Details Table for Discrepancies for specified Start Date and End Date
        dtDiscrepancies = objMonthClosure.GetDiscrepanciesForPayroll(strStartDate, strEndDate, gstrLevels, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
        // If there Discrepancies, then the Datas cannot be Processed. So Before Processing, Discrepancies should be Closed through 
        // Manual Time Entry
        // If there is no Records i.e., No Discrepancies
        if (dtDiscrepancies.Rows.Count == 0)
        {
            try
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strStartDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_StartDate.Text);
                strEndDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_EndDate.Text);
                DateTime dtmStartDate = DateTime.Parse(strStartDate);
                DateTime dtmEndDate = DateTime.Parse(strEndDate);
                DataSet dsProcess = new DataSet();
                DataTable dtProcess = new DataTable("ReprocessEmployees");
                DataColumn dcProcess = new DataColumn();
                dcProcess.DataType = System.Type.GetType("System.String");
                dcProcess.ColumnName = "EmployeeId";
                dtProcess.Columns.Add(dcProcess);
                dsProcess.Tables.Add(dtProcess);
                StringWriter strWriteXML = new StringWriter();
                dsProcess.Tables[0].WriteXml(strWriteXML);
                string strResult = string.Empty;
                if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_EN")
                {
                    strResult = objMonthClosure.ProcessDataCountEmployees(gstrLevels, dtmStartDate, dtmEndDate, strWriteXML.ToString(), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
                }
                else if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_AR")
                {
                    strResult = objMonthClosure.ProcessDataCountEmployees_Arabic(gstrLevels, dtmStartDate, dtmEndDate, strWriteXML.ToString(), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
                }
                if (strResult == string.Empty)
                {
                    PayrollProcess("Preview", strWriteXML.ToString());
                }
                else
                {
                    base.Message(strResult);
                    return;
                }
            }
            catch
            {
            }
        }
        // If there are Records i.e., there are Discrepancies. 
        else if (dtDiscrepancies.Rows.Count > 0)
        {
            lblMessage.Text = rm.GetString("Alert_ClosealltheDiscrepanciestopreviewtheData", ci);
            Response.Redirect("TA_UI_Transactions_PayrollProcessGrid.aspx?StartDate=" + strStartDate + "&EndDate=" + strEndDate + "&LevelID=" + Convert.ToInt16(lbl_LevelId.Text) + "&MonClosureId=" + MonthCloseID + "");
            return;
        }
    }
    // **********************************************************************************************************************
    // Function Name : PayrollProcess
    // Purpose :
    //     The Process Method takes the Data in the ProcessedData Table for a specified Start Date and End Date
    //     and calculates the Cumulative Hours Worked, Hours OT, Normal OT, WeekOff OT, Holiday OT, Early Out, Late In,
    //     Work Hours, Hours Less, Hours Extra which is required for Payroll Generation
    // **********************************************************************************************************************
    protected void btn_Reprocess_Click(object sender, EventArgs e)
    {
        lblMessage.Text = string.Empty;
        DataTable dtDiscrepancies = new DataTable();
        try
        {
            int count = 0;
            // Check whether Payroll Details are already Processed or not by passing MonthClocsureId
            count = objMonthClosure.CheckMonthClosureProcessFlag(MonthCloseID);
            // If count is 0 i.e., Data is not Processed
            if (count == 0)
            {
                base.Message(rm.GetString("Msg_CannotReProcessClickProcessButtontotheprocesstheData", ci));
                return;
            }
            else
            {
                // Check in the Clock Details Table for Discrepancies for specified Start Date and End Date
                dtDiscrepancies = objMonthClosure.GetDiscrepanciesForPayroll(strStartDate, strEndDate, gstrLevels, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
                // If there Discrepancies, then the Datas cannot be Processed. So Before Processing, Discrepancies should be Closed through 
                // Manual Time Entry
                // If there is no Records i.e., No Discrepancies
                if (dtDiscrepancies.Rows.Count == 0)
                {
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    strStartDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_StartDate.Text);
                    strEndDate = objcls_Common.DateConvertion(gstrDateFormat, lbl_EndDate.Text);
                    DateTime dtmStartDate = DateTime.Parse(strStartDate);
                    DateTime dtmEndDate = DateTime.Parse(strEndDate);
                    DataSet dsProcess = new DataSet();
                    DataTable dtProcess = new DataTable("ReprocessEmployees");
                    DataColumn dcProcess = new DataColumn();
                    dcProcess.DataType = System.Type.GetType("System.String");
                    dcProcess.ColumnName = "EmployeeId";
                    dtProcess.Columns.Add(dcProcess);
                    dsProcess.Tables.Add(dtProcess);
                    StringWriter strWriteXML = new StringWriter();
                    dsProcess.Tables[0].WriteXml(strWriteXML);
                    string strResult = string.Empty;
                    if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_EN")
                    {
                        strResult = objMonthClosure.ProcessDataCountEmployees(gstrLevels, dtmStartDate, dtmEndDate, strWriteXML.ToString(), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
                    }
                    else if (Convert.ToString(Session["Session_ActiveLanguage"]) == "Resources.Resource_AR")
                    {
                        strResult = objMonthClosure.ProcessDataCountEmployees_Arabic(gstrLevels, dtmStartDate, dtmEndDate, strWriteXML.ToString(), Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(lbl_LevelId.Text));
                    }
                    if (strResult == string.Empty)
                    {
                        objMonthClosure.DeletePayrollLeaveDetails(MonthCloseID);
                        PayrollProcess("Process", strWriteXML.ToString());
                        base.Message(rm.GetString("Msg_DatahasbeensuccessfullyReprocessed", ci));
                    }
                    else
                    {
                        base.Message(strResult);
                        return;
                    }
                }
                else if (dtDiscrepancies.Rows.Count > 0)
                {
                    lblMessage.Text = rm.GetString("Alert_ClosealltheDiscrepanciestoprocesstheData", ci);
                    Response.Redirect("TA_UI_Transactions_PayrollProcessGrid.aspx?StartDate=" + strStartDate + "&EndDate=" + strEndDate + "&LevelID=" + Convert.ToInt16(lbl_LevelId.Text) + "&MonClosureId=" + MonthCloseID + "");
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_MonthClosure.aspx");
    }
    protected void btn_Delete_Click(object sender, EventArgs e)
    {
        objMonthClosure.DeleteMonthCloureDetails(MonthCloseID.ToString(), gintUserId);
        string strScript = "";
        strScript = strScript + "<script language='javascript'>";
        strScript = strScript + "alert('" + rm.GetString("Alert_MonthClosureDatahasbeendeletedsuccessfully", ci) + "');";
        strScript = strScript + "location.replace('TA_UI_Transactions_MonthClosure.aspx');";
        strScript = strScript + "</script>";
        Page.RegisterStartupScript("AlertDelete", strScript);
    }
    // Reprocess for the Selected Individuals in the particular Level for a pamrticular Period
    protected void btn_IndividualReprocess_Click(object sender, EventArgs e)
    {
        lblMessage.Text = string.Empty;
        int count = 0;
        // Check whether Payroll Details are already Processed or not by passing MonthClocsureId
        count = objMonthClosure.CheckMonthClosureProcessFlag(MonthCloseID);
        // If count is 0 i.e., Data is not Processed
        if (count == 0)
        {
            base.Message(rm.GetString("Msg_CannotReProcessClickProcessButtontotheprocesstheData", ci));
            return;
        }
        else
        {
        }
    }
    protected void btn_View_Click(object sender, EventArgs e)
    {
        if (grv_MonthClosure.Visible == false)
        {
            grv_MonthClosure.Visible = true;
        }
        lblMessage.Text = string.Empty;
        BindingMonthClosureGrid(MonthCloseID, Convert.ToInt32(lbl_LevelId.Text), strStartDate, strEndDate, closedDate);
    }
    #endregion
    #region GridviewEvents
    protected void grv_MonthClosure_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grv_MonthClosure.PageIndex = e.NewPageIndex;
        BindingMonthClosureGrid(MonthCloseID, Convert.ToInt32(lbl_LevelId.Text), strStartDate, strEndDate, closedDate);
    }
    protected void grv_MonthClosure_RowEditing(object sender, GridViewEditEventArgs e)
    {
        BindingMonthClosureGrid(MonthCloseID, Convert.ToInt32(lbl_LevelId.Text), strStartDate, strEndDate, closedDate);
    }
    protected void grv_MonthClosure_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        BindingMonthClosureGrid(MonthCloseID, Convert.ToInt32(lbl_LevelId.Text), strStartDate, strEndDate, closedDate);
    }
    protected void grv_MonthClosure_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    }
    #endregion

    protected void btnExport_Click(object sender, EventArgs e)
    {
        LinkButton btn = (LinkButton)sender;
        ASPxGridViewExporter1.GridViewID = "grv_MonthClosure";
        ASPxGridViewExporter1.FileName = "Month Closure " + lbl_Month.Text + " " + lbl_Year.Text;
        ASPxGridViewExporter1.Landscape = true;
        ASPxGridViewExporter1.LeftMargin = 30;
        ASPxGridViewExporter1.RightMargin = 30;
        ASPxGridViewExporter1.MaxColumnWidth = 200;
        ASPxGridViewExporter1.PaperKind = System.Drawing.Printing.PaperKind.A4;
        ASPxGridViewExporter1.PageHeader.Center = "Month Closure " + lbl_Month.Text + " " + lbl_Year.Text;
        switch (btn.CommandName)
        {
            case "excel":
                ASPxGridViewExporter1.WriteXlsxToResponse();
                break;
            case "pdf":
                ASPxGridViewExporter1.WritePdfToResponse();
                break;
            default:
                break;
        }
    }
}
