using System;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Globalization;
using System.Threading;
using System.Resources;
using System.IO;
/****************************************************************************************************************************
* Project Name    : TimeCheck                    Started Date  : 12-Aug-2007
* Module          : Leave Application            Last Modified : 14-Aug-2007
* Programmer      : Prabakaran.P
* Current Storage : \\Angler56\Projects\Inprogress\SCREEN1206\code\Time_AttendanceApp
* BackUp          :
****************************************************************************************************************************/
public partial class Transactions_TA_UI_Transactions_LeaveApplication : Base.BasePage
{
    #region "Variable Declaration"
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    LeaveApplicationEventData objLeaveHolidays = new LeaveApplicationEventData();
    cls_Common objClassCommon = new cls_Common();
    DataSet dsLeaveHolidays = new DataSet();
    DataSet ds_Year = new DataSet();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    DataSet dsEmailIdOfSanctionAuthority = new DataSet();
    DataSet ds_EmailIdOfReportingTo = new DataSet();
    DataSet ds_EmployeeDetails = new DataSet();
    int StartYear, EndYear; string source_Language;
    int iLeaveApplication_Id, iEmployeeID, YearSettingID;
    string strReason = string.Empty, strEmailIdReportingTo, gstrDateFormat, gstrTimeFormat, strlevelName, strStatusType;
    Boolean blnCheckEmail;
    DataSet dsEmployeeGroup = new DataSet();
    int payrollConfig = 0;
    #endregion
    #region Page Load Events
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        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"]);
        if (!Page.IsPostBack)
        {
            grv_LeaveApplication.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
            base.CheckPages(0);
            objClassCommon.menu("LeaveTransaction", "22");
            UserRights();
            LoadStrings(ci);
            btn_Add.Focus();
            Session["parentLevelId"] = "0";
            string strSetAlert = "";
            strSetAlert = strSetAlert + "<script language='javascript'>";
            strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
            strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_FillDetails", ci) + "','" + rm.GetString("Alert_FillFromToDate", 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);
            ds_Year = objClassCommon.GetYearsetting();
            if (ds_Year.Tables[0].Rows.Count <= 0)
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Msg_DefineYearSettinginOrganizationSettings", ci) + "');location.replace('../Organization Settings/Organization_YearSetting.aspx')";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertLeavePolicyYear", strScript);
            }
            else
            {
                StartYear = Convert.ToInt32(ds_Year.Tables[0].Rows[0]["StartYear"]);
                EndYear = Convert.ToInt32(ds_Year.Tables[0].Rows[0]["EndYear"]);
                ViewState["YearSettings_Id"] = Convert.ToString(ds_Year.Tables[0].Rows[0]["YearSettings_Id"]);
                ds_Year.Dispose();
            }
            BindLeaveApplication();
            Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
            Hidden2.Value = Convert.ToString(Session["ITimeFormat"]);
            BindControlsBasedOnLicense();

        }
        if (Convert.ToString(ViewState["GroupName"]) == "Normal")
        {
            trSwipeCardNo.Visible = false;
            trEmployeeDetails.Visible = false;
        }
        if (ViewState["vs_payrollConfig"] != null)
        {
            payrollConfig = (int)ViewState["vs_payrollConfig"];
        }
        else
        {
            payrollConfig = objClassCommon.CheckPageExistsInLicense(185);
        }
        if (payrollConfig == 1)
        {
            grv_LeaveApplication.Columns[10].Visible = false;
            grv_LeaveApplication.Columns[11].Visible = true;
            grv_LeaveApplication.Columns[12].Visible = false;
        }

    }
    /// <summary>
    /// Bind Controls based on license
    /// </summary>
    private void BindControlsBasedOnLicense()
    {
        #region Eastman
        if (Convert.ToString(Session["packageID"]) != "")
            if (Convert.ToString(Session["packageID"]) == "155") /*EastMan*/
            {
                if (Convert.ToString(Session["IndividualUsers"]) != "True")
                {
                    iframePopup.Attributes.Add("height", "600");
                }
            }
            else if (Convert.ToInt32(Session["packageID"]) >= 164) /*TimecheckV2.9_Enterprice*/
            {
                // for individual user it not be loaded. import option.
                if (Convert.ToString(Session["IndividualUsers"]) == "True")
                {
                    btnImport.Style.Add("display", "none");
                }
            }
        #endregion
    }
    private void BindLeaveApplication()
    {
        dsEmployeeGroup = objLeaveApplicationEventData.GetEmployeeGroupName(Convert.ToInt32(Session["EmpAutoId"]));
        if (dsEmployeeGroup.Tables[0].Rows.Count > 0)
        {
            if (Convert.ToString(dsEmployeeGroup.Tables[0].Rows[0]["GroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            {
                grv_LeaveApplication.DataSourceID = "";
                grv_LeaveApplication.DataSourceID = (payrollConfig == 1) ? ObjectDataSource4.ID : ObjectDataSource2.ID;
                ViewState["GroupName"] = "SuperAdmin";
                btnImport.Style.Add("display", "");
            }
            else
            {
                grv_LeaveApplication.DataSourceID = (payrollConfig == 1) ? ObjectDataSource3.ID : ObjectDataSource1.ID;
                grv_LeaveApplication.Columns[2].Visible = false;
                grv_LeaveApplication.Columns[3].Visible = false;
                grv_LeaveApplication.Columns[4].Visible = false;
                ViewState["GroupName"] = "Normal";
                btnImport.Style.Add("display", "none");
            }
        }
        else
        {
            grv_LeaveApplication.DataSourceID = (payrollConfig == 1) ? ObjectDataSource3.ID : ObjectDataSource1.ID;
            grv_LeaveApplication.Columns[2].Visible = false;
            grv_LeaveApplication.Columns[3].Visible = false;
            grv_LeaveApplication.Columns[4].Visible = false;
            ViewState["GroupName"] = "Normal";
            btnImport.Style.Add("display", "none");
        }
    }
    #endregion
    #region ButtonEvents
    protected void btn_Add_Click(object sender, EventArgs e)
    {
        /*Below parameter is used for Angler 1 ! 0*/
        if (payrollConfig == 1)
        {
            Response.Redirect("TA_UI_Transactions_MultipleLeaveApplicationAdd.aspx");
        }
        else
        {
            Response.Redirect("TA_UI_Transactions_LeaveApplicationAdd.aspx");
        }
    }
    protected void btn_Clear_Click(object sender, EventArgs e)
    {
        grid_RestoreDefault();
        lbl_Error.Text = string.Empty;
    }
    protected void btn_Search_Click(object sender, EventArgs e)
    {
        FillGrid_Search();
    }
    #endregion
    #region UserDefinedFunctions
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Transactions_LeaveApplication", ci);
        lbl_EmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lbl_EmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblTimePeriod.Text = rm.GetString("ShiftExchange_DateRange", ci);
        lblLeaveStartDate.Text = rm.GetString("email_FromDate", ci);
        lblLeaveEndDate.Text = rm.GetString("email_ToDate", ci);
        lblTimePeriod.Text = rm.GetString("ShiftExchange_DateRange", ci);
        btn_Search.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Search", ci);
        btn_Clear.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Clear", ci);
        btn_Add.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Add", ci);
        grv_LeaveApplication.Columns[1].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        grv_LeaveApplication.Columns[2].Caption = rm.GetString("email_EmployeeId", ci);
        grv_LeaveApplication.Columns[3].Caption = rm.GetString("email_EmployeeName", ci);
        grv_LeaveApplication.Columns[4].Caption = rm.GetString("LevelDetails_LevelName", ci);
        grv_LeaveApplication.Columns[5].Caption = rm.GetString("Report_Duration", ci);
        grv_LeaveApplication.Columns[6].Caption = rm.GetString("Type_Of_Leave", ci);
        grv_LeaveApplication.Columns[7].Caption = rm.GetString("email_Status", ci);
        grv_LeaveApplication.Columns[8].Caption = rm.GetString("email_Reason", ci);
        grv_LeaveApplication.Columns[9].Caption = rm.GetString("email_Remarks", ci);
        lblEmpSwipe.Text = rm.GetString("TerminalDataType_Card_No", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
        lblDataView.Text = rm.GetString("lblDataView", ci);
        btnImport.Text = rm.GetString("btnImport", ci);
    }
    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(22, Convert.ToInt32(Session["userGroup_Id"]), "");
        if (ds_Checkuser.Tables[0].Rows.Count > 0)
        {
            if (ds_Checkuser.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["addPrv"]) == 1)
            {
                this.btn_Add.Visible = true;
                btnImport.Visible = true;
            }
            else
            {
                this.btn_Add.Visible = false;
                btnImport.Visible = false;
            }
            if (ds_Checkuser.Tables[0].Rows[0]["viewPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 1)
            {
                if (payrollConfig == 1)
                {
                    this.grv_LeaveApplication.Columns[12].Visible = true;
                    this.grv_LeaveApplication.Columns[11].Visible = false;
                }
                else
                {
                    this.grv_LeaveApplication.Columns[12].Visible = false;
                    this.grv_LeaveApplication.Columns[11].Visible = true;
                }
            }
            else
            {
                if (payrollConfig == 1)
                {
                    this.grv_LeaveApplication.Columns[12].Visible = false;
                    this.grv_LeaveApplication.Columns[11].Visible = false;
                }
                else
                {
                    this.grv_LeaveApplication.Columns[12].Visible = false;
                    this.grv_LeaveApplication.Columns[11].Visible = false;
                }
            }
            if (ds_Checkuser.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["deletePrv"]) == 1)
            {
                this.grv_LeaveApplication.Columns[13].Visible = true;
            }
            else
            {
                this.grv_LeaveApplication.Columns[13].Visible = false;
            }
            if (ds_Checkuser.Tables[0].Rows[0]["addPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["addPrv"]) == 0 &&
                ds_Checkuser.Tables[0].Rows[0]["deletePrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["deletePrv"]) == 0 &&
                ds_Checkuser.Tables[0].Rows[0]["viewPrv"] != DBNull.Value && Convert.ToInt32(ds_Checkuser.Tables[0].Rows[0]["viewPrv"]) == 0)
            {
                Response.Redirect("TransactionLandingPage.aspx");
            }
        }
        else
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            lnktbnexcel.Visible = true;
            lnkbtnpdf.Visible = true;
        }
    }
    private void grid_RestoreDefault()
    {
        txt_EmpName.Text = string.Empty;
        txtEmployeeId.Text = string.Empty;
        txtLeaveStartDate.Text = string.Empty;
        txtLeaveEndDate.Text = string.Empty;
        txtSwipeCard.Text = string.Empty;
        grv_LeaveApplication.PageIndex = 0;
        if (payrollConfig == 1)
        {
            if (Convert.ToString(ViewState["GroupName"]) == "SuperAdmin")
            {
                grv_LeaveApplication.DataSourceID = ObjectDataSource4.ID;
            }
            else
            {
                grv_LeaveApplication.DataSourceID = ObjectDataSource3.ID;
            }
        }
        else
        {
            if (Convert.ToString(ViewState["GroupName"]) == "SuperAdmin")
            {
                grv_LeaveApplication.DataSourceID = ObjectDataSource2.ID;
            }
            else
            {
                grv_LeaveApplication.DataSourceID = ObjectDataSource1.ID;
            }
        }
    }
    private void FillGrid_Search()
    {
        string empName = txt_EmpName.Text.Trim();
        txt_EmpName.Text = empName;
        string empId = txtEmployeeId.Text.Trim();
        txtEmployeeId.Text = empId;
        string strLeaveStartDate;
        string strLeaveEndDate;
        bool boolErrorStatus = true;
        string gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        strLeaveStartDate = objClassCommon.DateConvertion(gstrDateFormat, Convert.ToString(txtLeaveStartDate.Text));
        strLeaveEndDate = objClassCommon.DateConvertion(gstrDateFormat, Convert.ToString(txtLeaveEndDate.Text));
        string strSwipeCard = "";
        strSwipeCard = Convert.ToString(txtSwipeCard.Text).Trim().Replace("'", "''");
        if (strLeaveStartDate == string.Empty && strLeaveEndDate == string.Empty)
        {
            boolErrorStatus = false;
        }
        else if (strLeaveStartDate != string.Empty && strLeaveEndDate != string.Empty)
        {
            if (Convert.ToDateTime(strLeaveEndDate).Date < Convert.ToDateTime(strLeaveStartDate).Date)
            {
                base.Message(rm.GetString("Alert_FromDateLessThanToDate"));
                boolErrorStatus = true;
                grv_LeaveApplication.DataSourceID = "";
                return;
            }
            else
            {
                boolErrorStatus = false;
            }
        }
        if (boolErrorStatus == true)
        {
            grid_RestoreDefault();
        }
        else
        {
            lbl_Error.Text = string.Empty;
            grv_LeaveApplication.PageIndex = 0;
            if (payrollConfig == 1)
            {
                if (Convert.ToString(ViewState["GroupName"]) == "SuperAdmin")
                {
                    grv_LeaveApplication.DataSourceID = ObjectDataSource4.ID;
                }
                else
                {
                    grv_LeaveApplication.DataSourceID = ObjectDataSource3.ID;
                }
            }
            else
            {
                if (Convert.ToString(ViewState["GroupName"]) == "SuperAdmin")
                {
                    grv_LeaveApplication.DataSourceID = ObjectDataSource2.ID;
                }
                else
                {
                    grv_LeaveApplication.DataSourceID = ObjectDataSource1.ID;
                }
            }
        }
    }
    #endregion
    #region GridveiwEvents
    protected void grv_LeaveApplication_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridViewTableRowEventArgs e)
    {
        base.Page_Load(sender, e);
        if (e.RowType == DevExpress.Web.GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            string appdate = Convert.ToString(e.GetValue("Leave_ApplicationDate"));
            Label lbl_Status = (Label)grv_LeaveApplication.FindRowCellTemplateControl(e.VisibleIndex, null, "lbl_Status");
            if (lbl_Status != null)
            {
                switch (lbl_Status.Text)
                {
                    case "Approved":
                        lbl_Status.Text = rm.GetString("btn_Approved", ci);
                        break;
                    case "Forwarded":
                        lbl_Status.Text = rm.GetString("btn_Forwarded", ci);
                        break;
                    case "Pending":
                        lbl_Status.Text = rm.GetString("btn_Pending", ci);
                        break;
                    case "Rejected":
                        lbl_Status.Text = rm.GetString("btn_Reject", ci);
                        break;
                    default:
                        break;
                }
            }
            Label lbl_LeaveType = (Label)grv_LeaveApplication.FindRowCellTemplateControl(e.VisibleIndex, null, "lbl_LeaveType");
            if (lbl_LeaveType != null)
            {
                switch (lbl_LeaveType.Text)
                {
                    case "Restricted Holiday":
                        lbl_LeaveType.Text = rm.GetString("Holiday_RestrictedHoliday", ci);
                        break;
                    case "Comp Off":
                        lbl_LeaveType.Text = rm.GetString("Caption_CompOff", ci);
                        break;
                    case "ESI":
                        lbl_LeaveType.Text = rm.GetString("Caption_ESI", ci);
                        break;
                    default:
                        if (lbl_LeaveType.Text.Contains("LOP"))
                        {
                            lbl_LeaveType.Text = lbl_LeaveType.Text.Replace("LOP", rm.GetString("lbl_LOP", ci));
                        }
                        else if (lbl_LeaveType.Text.Contains("Leave"))
                        {
                            lbl_LeaveType.Text = lbl_LeaveType.Text.Replace("Leave", rm.GetString("LeaveApplication_Leave", ci));
                        }
                        break;
                }
            }
        }
    }
    #endregion
    protected void btn_delete_Click_1(object sender, EventArgs e)
    {
        LinkButton btn = sender as LinkButton;
        iLeaveApplication_Id = Convert.ToInt32(btn.CommandName);
        ViewDetails();
        ViewState["EmpID"] = btn.ValidationGroup.ToString();
        ViewState["EmpName"] = btn.CommandArgument;
        string strLeaveStatus = string.Empty;
        int approvalSettingsPageExists = 0;
        switch (payrollConfig)
        {
            case 1:
                approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(110);
                break;
            default:
                approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(228);
                break;
        }
        if (approvalSettingsPageExists == 1)
        {
            //Get Compnay Id of the Employeee
            int intCompanyId = base.GetCompanyId(Convert.ToInt32(ViewState["iEmployeeID"]));
            //Get Approval Settings Based on Company Id
            DataSet dsApprovalSettings = new DataSet();
            ShiftEvenData objShift = new ShiftEvenData();
            dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
            if (dsApprovalSettings != null)
            {
                if (dsApprovalSettings.Tables.Count > 0)
                {
                    if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0]["LeaveSanction"]) == false)
                        {
                            strLeaveStatus = "ApprovalNotRequired";
                        }
                    }
                    else
                    {
                        base.Message(rm.GetString("Msg_ApprovalSettings", ci));
                        return;
                    }
                }
            }
        }
        else
        {
            strLeaveStatus = "ApprovalNotRequired";
        }
        if (Convert.ToString(ViewState["StatusOfApplication"]) == "Rejected")
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            {
                switch (payrollConfig)
                {
                    case 1:
                        objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
                        //Update Year Closure
                        DeleteAlertMessage();
                        break;
                    default:
                        if (Convert.ToString(Session["IndividualUsers"]) == "True")
                        {
                            Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('Rejected Leave Application Cannot be Deleted');</script>");
                        }
                        else
                        {
                            objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
                            DeleteAlertMessage();
                        }
                        break;
                }
                RemoveUploadedFiles(iLeaveApplication_Id);
            }
            else
            {
                Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('Rejected Leave Application Cannot be Deleted');</script>");
            }
        }
        else if (Convert.ToString(ViewState["StatusOfApplication"]) == "Pending" || strLeaveStatus == "ApprovalNotRequired")
        {
            //Check Borrow Leave Exists after normal leaves
            int intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), Convert.ToInt32(ViewState["LeaveTypeId"]), Convert.ToInt32(ViewState["iEmployeeID"]));
            if (intBorrowCount > 0)
            {
                base.Message(rm.GetString("Msg_BorrowLeavesareavailabletodelete", ci));
                return;
            }
            //Delete Leave Application
            objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
            RemoveUploadedFiles(iLeaveApplication_Id);
            //Update Year Closure
            YearClosureUpdate(strLeaveStatus);
            //Added Newly by Manikandan.RR on 10-06-2015 11.38 AM
            MailToReportingTo();
            DeleteAlertMessage();
        }
        else
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            {
                if (payrollConfig == 1)
                {
                    //Check Borrow Leave Exists after normal leaves
                    int intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), Convert.ToInt32(ViewState["LeaveTypeId"]), Convert.ToInt32(ViewState["iEmployeeID"]));
                    if (intBorrowCount > 0)
                    {
                        base.Message(rm.GetString("Msg_BorrowLeavesareavailabletodelete", ci));
                        return;
                    }
                    //Delete Leave Application
                    objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
                    //Update Year Closure
                    YearClosureUpdate(strLeaveStatus);
                    MailToReportingTo();
                    DeleteAlertMessage();
                }
                else
                {
                    if (Convert.ToString(Session["IndividualUsers"]) == "True")
                    {
                        Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('" + rm.GetString("Alert_Cannotdeletethisrecordd", ci) + "');</script>");
                    }
                    else
                    {
                        //Check Borrow Leave Exists after normal leaves
                        int intBorrowCount = objLeaveApplicationEventData.CheckBorrowLeaveExists(ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), Convert.ToInt32(ViewState["LeaveTypeId"]), Convert.ToInt32(ViewState["iEmployeeID"]));
                        if (intBorrowCount > 0)
                        {
                            base.Message(rm.GetString("Msg_BorrowLeavesareavailabletodelete", ci));
                            return;
                        }
                        //Delete Leave Application
                        objLeaveApplicationEventData.Delete_LeaveApplication(iLeaveApplication_Id, Convert.ToInt32(Session["EmpAutoId"]));
                        //Update Year Closure
                        YearClosureUpdate(strLeaveStatus);
                        MailToReportingTo();
                        DeleteAlertMessage();
                    }
                }
                RemoveUploadedFiles(iLeaveApplication_Id);
            }
            else
            {
                Page.RegisterStartupScript("statusalert", "<script language='javascript'>alert('" + rm.GetString("Alert_Cannotdeletethisrecordd", ci) + "');</script>");
            }
        }
    }
    private void DeleteAlertMessage()
    {
        string strScript = "";
        strScript = strScript + "<script language='javascript'>";
        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveApplicationDeleted", ci) + "');";
        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveApplication.aspx');";
        strScript = strScript + "</script>";
        //Dispaly alert messsage.
        Page.RegisterStartupScript("AlertLDel65507866", strScript);
        return;
    }
    public void ViewDetails()
    {
        DataSet ds_LeaveApplication = new DataSet();
        ds_LeaveApplication = objLeaveApplicationEventData.SelectLeaveApplication(iLeaveApplication_Id);
        if (ds_LeaveApplication.Tables.Count > 0)
        {
            if (ds_LeaveApplication.Tables[0].Rows.Count > 0)
            {
                iEmployeeID = Convert.ToInt32(ds_LeaveApplication.Tables[0].Rows[0]["Employee_Id"]);
                YearSettingID = Convert.ToInt32(ds_LeaveApplication.Tables[0].Rows[0]["YearSettings_Id"]);
                ViewState["iEmployeeID"] = iEmployeeID.ToString();
                ViewState["StatusOfApplication"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Status"]);
                ViewState["lblType"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Type"]);
                ViewState["LeaveTypeId"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["LeaveType_Id"]);
                ViewState["LeaveFromDate"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_FromDate"]);
                ViewState["LeaveToDate"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_ToDate"]);
                ViewState["IsBorrow"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["IsBorrow"]);
                ViewState["NumberOfDays"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["NumberOfDays"]);
                ViewState["Application_Date"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_ApplicationDate"]);
                ViewState["Leave_Reason"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Reason"]);
                ViewState["Leave_Type"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["LeaveType"]);
                ViewState["From_session"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_SessionFrom"]);
                ViewState["To_session"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["Leave_SessionTo"]);
                ViewState["isWFH"] = Convert.ToString(ds_LeaveApplication.Tables[0].Rows[0]["isWFH"]);
            }
        }
    }
    public void YearClosureUpdate(string strLeaveStatus)
    {
        if (strLeaveStatus == "ApprovalNotRequired")
        {
            int Employee_Id = Convert.ToInt32(ViewState["iEmployeeID"]);
            string strTypeOfLeave = ViewState["lblType"].ToString();
            if (strTypeOfLeave == "Leave")
            {
                double NumberOfDays = Convert.ToDouble(ViewState["NumberOfDays"]);
                int LeaveTypeId = Convert.ToInt32(ViewState["LeaveTypeId"]);
                if (Convert.ToBoolean(ViewState["IsBorrow"]) == false)
                {
                    objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "R", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                }
                else
                {
                    objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "RB", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                }
            }
            // Update Processed Data Flag for Re-Processing
            objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, ViewState["LeaveFromDate"].ToString(), ViewState["LeaveToDate"].ToString(), 0);
        }
    }
    private void MailToReportingTo()
    {
        string strEmployeeEmailId = string.Empty;
        string strEmailIdSanctioningAuthority = string.Empty;
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        gstrTimeFormat = Session["MTimeFormat"].ToString();
        strStatusType = "deleted";
        ds_EmployeeDetails = objLeaveApplicationEventData.GetEmployeeDetails(Convert.ToInt32(ViewState["iEmployeeID"]));
        if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
        {
            strlevelName = ds_EmployeeDetails.Tables[0].Rows[0]["levelName"].ToString();
            strEmployeeEmailId = ds_EmployeeDetails.Tables[0].Rows[0]["emailId"].ToString();
            ViewState["EmpID"] = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"]);
            ViewState["EmpName"] = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]) + " " + Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
            strlevelName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["levelName"]);
        }
        ds_EmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Convert.ToInt32(ViewState["iEmployeeID"]));
        dsEmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Convert.ToInt32(ViewState["iEmployeeID"]));
        strEmailIdSanctioningAuthority = string.Empty;
        if (dsEmailIdOfSanctionAuthority != null)
        {
            if (dsEmailIdOfSanctionAuthority.Tables.Count > 0)
            {
                if (dsEmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                {
                    if (dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                    {
                        if (dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
                        {
                            strEmailIdSanctioningAuthority = dsEmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                        }
                    }
                }
            }
        }
        if (ds_EmailIdOfReportingTo.Tables[0].Rows.Count > 0)
        {
            if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
            {
                if (ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                {
                    strEmailIdReportingTo = ds_EmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                    if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                    {
                        SendMail(strEmployeeEmailId, strEmailIdReportingTo, strEmailIdSanctioningAuthority, Convert.ToDouble(ViewState["NumberOfDays"]), Convert.ToString(ViewState["LeaveFromDate"]), Convert.ToString(ViewState["LeaveToDate"]), Convert.ToString(ViewState["Application_Date"]), Convert.ToString(ViewState["EmpID"]), Convert.ToString(ViewState["EmpName"]), Convert.ToString(ViewState["Leave_Reason"]), strlevelName, Convert.ToString(ViewState["Leave_Type"]));
                    }
                }
            }
        }
    }
    private void SendMail(string strEmployeeEmailId, string ToMailId, string SanctionMailId, double NumberOfDaysApplied, string FromDate, string ToDate, string ApplicationDate, string EmployeeName, string Employee_Code_Id, string strReason, string strlevelName, string strLeaveType)
    {
        string strFromEmailId = string.Empty;
        MailMessage mailMessage = new MailMessage();
        string strMailStatus = "Deleted";
        try
        {
            string scriptText;
            DataTable dtTableScript = new DataTable();
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts("New Leave Application Form");
            if (dtTableScript.Rows.Count > 0)
            {
                switch (strLeaveType)
                {
                    case "Restricted Holiday":
                        strLeaveType = rm.GetString("Holiday_RestrictedHoliday", ci);
                        break;
                    case "Comp Off":
                        strLeaveType = rm.GetString("Caption_CompOff", ci);
                        break;
                    case "LOP":
                        strLeaveType = strLeaveType.Replace("LOP", rm.GetString("lbl_LOP", ci));
                        break;
                    case "ESI":
                        strLeaveType = rm.GetString("Caption_ESI", ci);
                        break;
                    default:
                        if (strLeaveType.Contains("Leave"))
                            strLeaveType = strLeaveType.Replace("Leave", rm.GetString("LeaveApplication_Leave", ci));
                        break;
                }
                scriptText = Convert.ToString(dtTableScript.Rows[0]["ScriptText"]);
                // As per elite partner requisition, mail should be trigger from admin id, whatever we configured in setting page.
                //25-Dec-2019 02:06 PM
                //if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                //{
                //    mailMessage.From = new MailAddress(Convert.ToString(Session["loginEmailId"]));
                //    strFromEmailId = Convert.ToString(Session["loginEmailId"]);
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                strFromEmailId = Convert.ToString(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                if (ToMailId != string.Empty)
                {
                    mailMessage.To.Add(new MailAddress(ToMailId));
                }
                if (strEmployeeEmailId != string.Empty)
                {
                    mailMessage.CC.Add(new MailAddress(strEmployeeEmailId));
                }
                if (Convert.ToString(ViewState["isWFH"]) == "1")
                {
                    mailMessage.Subject = rm.GetString("email_WorkFromHomeApplicationForm", ci) + " - " + (DateTime.Parse(ApplicationDate)).ToString(Session["MDateFormat"].ToString()) + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strMailStatus;
                    mailMessage.Body = scriptText.Replace("<<lblleaveapplicationform>>", rm.GetString("email_WFHApplicationForm", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblapplicationdate>>", rm.GetString("email_WFHApplicationDate", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavetype>>", rm.GetString("lbl_WFHtype", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavedate>>", rm.GetString("email_WFHDate", ci));
                }
                else
                {
                    mailMessage.Subject = rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + (DateTime.Parse(ApplicationDate)).ToString(Session["MDateFormat"].ToString()) + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strMailStatus;
                    mailMessage.Body = scriptText.Replace("<<lblleaveapplicationform>>", rm.GetString("email_LeaveApplicationForm", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblapplicationdate>>", rm.GetString("email_LeaveApplicationDate", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavetype>>", rm.GetString("lbl_leavetype", ci));
                    mailMessage.Body = mailMessage.Body.Replace("<<lblleavedate>>", rm.GetString("email_LeaveDate", ci));
                }
                mailMessage.Body = mailMessage.Body.Replace("<<ltr_rtl>>", rm.GetString("Direction", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeeid>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<employeeid>>", Employee_Code_Id);
                mailMessage.Body = mailMessage.Body.Replace("<<employeename>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblemployeename>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<applicationdate>>", (DateTime.Parse(ApplicationDate)).ToString(Session["MDateFormat"].ToString()));
                mailMessage.Body = mailMessage.Body.Replace("<<leavetype>>", strLeaveType);
                mailMessage.Body = mailMessage.Body.Replace("<<numberdaysapplied>>", Convert.ToString(NumberOfDaysApplied));
                mailMessage.Body = mailMessage.Body.Replace("<<lblnumberdaysapplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<fromdate>>", (DateTime.Parse(FromDate)).ToString(Session["MDateFormat"].ToString()));
                mailMessage.Body = mailMessage.Body.Replace("<<lblfromdate>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<todate>>", (DateTime.Parse(ToDate)).ToString(Session["MDateFormat"].ToString()));
                mailMessage.Body = mailMessage.Body.Replace("<<lbltodate>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblsession>>", rm.GetString("email_Session", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<fromsession>>", Convert.ToString(ViewState["From_session"]));
                mailMessage.Body = mailMessage.Body.Replace("<<lblfromsession>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<tosession>>", Convert.ToString(ViewState["To_session"]));
                mailMessage.Body = mailMessage.Body.Replace("<<lbltosession>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<reason>>", strReason);
                mailMessage.Body = mailMessage.Body.Replace("<<lblreason>>", rm.GetString("email_Reason", ci));
                string strReplaceText = "<a href=<<LinkData>>><font face=\"Arial\" size=\"2\">Click here for approval</font></a>";
                mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                blnCheckEmail = false;
                objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(iLeaveApplication_Id, strFromEmailId, ToMailId, strEmployeeEmailId, rm.GetString("email_LeaveApplicationForm", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + strMailStatus, Convert.ToString(mailMessage.Body), "", "LeaveApplication");
            }
        }
        catch
        {
            blnCheckEmail = false;
            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(iLeaveApplication_Id, strFromEmailId, ToMailId, strEmployeeEmailId, rm.GetString("email_LeaveApplicationForm", ci) + " - " + ApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + strlevelName + " - " + strMailStatus, Convert.ToString(mailMessage.Body), "", "LeaveApplication");
        }
    }
    protected void btnImport_Click(object sender, EventArgs e)
    {
        Response.Redirect("TA_UI_Transactions_LeaveImport.aspx");
    }
    protected void lnktbnexcel_Click(object sender, EventArgs e)
    {
        LinkButton lnkbtn = (LinkButton)sender;  //Called From  Grid Report Icon click / both excel and pdf
        DisableControls();
        ASPxGridViewExporter1.Landscape = true;
        ASPxGridViewExporter1.LeftMargin = 10;
        ASPxGridViewExporter1.RightMargin = 10;
        ASPxGridViewExporter1.ExportedRowType = DevExpress.Web.GridViewExportedRowType.All;
        ASPxGridViewExporter1.MaxColumnWidth = 400;
        string saveAsFileName = string.Format("ListofLeaveApplications - {0:d}", DateTime.Now).Replace("/", "-").Replace(" ", "");
        ASPxGridViewExporter1.FileName = saveAsFileName;
        ASPxGridViewExporter1.PaperKind = System.Drawing.Printing.PaperKind.A3;
        switch (lnkbtn.CommandName)
        {
            case "excel":
                ASPxGridViewExporter1.WriteXlsxToResponse();
                break;
            case "pdf":
                ASPxGridViewExporter1.WritePdfToResponse();
                break;
            case "csv":
                ASPxGridViewExporter1.WriteCsvToResponse();
                break;
        }
    }
    private void DisableControls()
    {
        grv_LeaveApplication.Columns[10].Visible = false;
        grv_LeaveApplication.Columns[11].Visible = false;
        //GridView1.Columns[15].Visible = false;
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        BindLeaveApplication();
    }
    protected void btnDownload_Click(object sender, EventArgs e)
    {
        ImageButton btn = sender as ImageButton;
        int intEmpid = Convert.ToInt32(btn.CommandArgument);
        Random rnd = new Random();
        Download_MedicalCertificate(intEmpid);
    }
    private bool Download_MedicalCertificate(int LeaveApplication_ID)
    {
        string GetType = "SelectMedicalCertificate";
        bool fileflage = false;
        int LeaveApplication_Id = LeaveApplication_ID;
        DataSet dsFileDetails = objLeaveApplicationEventData.EditLeaveApplication_FileUpload(LeaveApplication_Id, GetType);
        if (dsFileDetails.Tables[0].Rows.Count > 0)
        {
            string GetPath = dsFileDetails.Tables[0].Rows[0]["FilePath"].ToString();
            string filename = Path.GetFileName(GetPath);
            string FilePath = Server.MapPath("~/Transactions/LeaveApplicationUploadFiles/" + filename);
            FileInfo fileInfo = new FileInfo(FilePath);
            if (fileInfo.Exists)
            {
                Response.Clear();
                Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
                Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                Response.ContentType = "application/octet-stream";
                Response.Flush();
                Response.TransmitFile(fileInfo.FullName);
                Response.End();
                fileflage = true;
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rm.GetString("Alert_MedicalCertificateNotAvailable", ci) + "');", true);
                fileflage = false;
            }
        }
        return fileflage;
    }
    private bool RemoveUploadedFiles(int LeaveApplication_ID)
    {
        string GetType = "SelectMedicalCertificate";
        bool fileflage = false;
        int LeaveApplication_Id = LeaveApplication_ID;
        DataSet dsFileDetails = objLeaveApplicationEventData.EditLeaveApplication_FileUpload(LeaveApplication_Id, GetType);
        if (dsFileDetails.Tables[0].Rows.Count > 0)
        {
            string GetPath = dsFileDetails.Tables[0].Rows[0]["FilePath"].ToString();
            string filename = Path.GetFileName(GetPath);
            string FilePath = Server.MapPath("~/Transactions/LeaveApplicationUploadFiles/" + filename);
            FileInfo fileInfo = new FileInfo(FilePath);
            if (fileInfo.Exists)
            {
                File.Delete(FilePath);
                //ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rm.GetString("MsgDeleteMedicalCertificate", ci) + "');", true);
                fileflage = true;
            }
            else
            {
                fileflage = false;
            }
        }
        else
        {
            fileflage = false;
        }
        return fileflage;
    }
}