using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;
using System.Globalization;
using System.Threading;
using System.Net.Mail;
using System.Net;
using DevExpress.Web;
using System.IO;
/*
* Modified By      :   Manjula.P
* Modified On      :   28-Sep-2013
* Descriptinos     :   To resolve the bug from mantis : 	0019022
* */
public partial class Transactions_TA_UI_Transactions_LeaveSanctionViewForBulkApproval : Base.BasePage
{
    #region Variable Declaration
    string source_Language;
    ResourceManager rm;
    SMSNotification objsms = new SMSNotification();
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    YearSettingsEventData objYearSettingsEventData = new YearSettingsEventData();
    cls_Common objcls_Common = new cls_Common();
    Rpt_Common rptcommon = new Rpt_Common();
    DataTable dtLeaveTransactionView = new DataTable();
    DataSet dsYearSetting = new DataSet();
    int vmonthValue;
    string startDate;
    bool checkRecordExists;
    string endDate, gstrDateFormat, LevelId, Status, From_Date, To_Date, StartMonth, EndMonth, StartYear, EndYear;
    string strSwipeCardNo = string.Empty;
    string strEmployeeName = string.Empty;
    string strEmployeeCodeId = string.Empty;
    PermissionEventData objPermissionEventData = new PermissionEventData();
    DataTable dtSanctionView = new DataTable();
    DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
    DataSet dsEmailIdOfReportingTo = new DataSet();
    DataSet dsRecordsCount = new DataSet();
    int intCount;
    int LeaveApplication_Id, Employee_Id, LeaveTypeId;
    string Remarks, strEmailIdSanctionAuthority, strEmailIdReportingTo, EmployeeName, EmployeeEamilId, strLeaveApplicationDate, strNoOfDays, Leave_FromDate, Leave_ToDate;
    double NumberOfDays;
    bool checkEmail = true, blnCheckSMS = true;
    string NotSendedEmployeeCodeId = "";
    DataSet ds_ReportingToSanctionAuthorityList = new DataSet();
    string Employee_Code_Id = string.Empty;
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        gdLeaveSanctionView.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        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);
        UserRights();
        if (Session["levelId"] == string.Empty || Session["levelId"] == null)
        {
            if (Request.QueryString["LevelId"] != null)
            {
                LevelId = Convert.ToString(Request.QueryString["LevelId"]);
                LevelId = rptcommon.getNodes(Convert.ToInt16(LevelId), Convert.ToString(Session["LevelRights"]));
            }
            else
            {
                LevelId = "";
            }
            Session["levelId"] = LevelId;
        }
        else
        {
            LevelId = Convert.ToString(Session["levelId"]);
        }
        if (Session["LeaveSanctionStatus"] == string.Empty || Session["LeaveSanctionStatus"] == null)
        {
            if (Request.QueryString["Status"] != null)
            {
                Status = Convert.ToString(Request.QueryString["Status"]);
            }
            else
            {
                Status = "";
            }
            Session["LeaveSanctionStatus"] = Status;
        }
        else
        {
            Status = Convert.ToString(Session["LeaveSanctionStatus"]);
        }
        if (Session["strSwipeCardNo"] == string.Empty || Session["strSwipeCardNo"] == null)
        {
            if (Request.QueryString["strSwipeCardNo"] != null)
            {
                strSwipeCardNo = Convert.ToString(Request.QueryString["strSwipeCardNo"]);
            }
            else
            {
                strSwipeCardNo = "";
            }
            Session["strSwipeCardNo"] = strSwipeCardNo;
        }
        else
        {
            strSwipeCardNo = Convert.ToString(Session["strSwipeCardNo"]);
        }
        if (Session["strEmployeeName"] == string.Empty || Session["strEmployeeName"] == null)
        {
            if (Request.QueryString["strEmployeeName"] != null)
            {
                strEmployeeName = Convert.ToString(Request.QueryString["strEmployeeName"]);
            }
            else
            {
                strEmployeeName = "";
            }
            Session["strEmployeeName"] = strEmployeeName;
        }
        else
        {
            strEmployeeName = Convert.ToString(Session["strEmployeeName"]);
        }
        if (Session["strEmployeeCodeId"] == string.Empty || Session["strEmployeeCodeId"] == null)
        {
            if (Request.QueryString["strEmployeeName"] != null)
            {
                strEmployeeCodeId = Convert.ToString(Request.QueryString["strEmployeeCodeId"]);
            }
            else
            {
                strEmployeeCodeId = "";
            }
            Session["strEmployeeCodeId"] = strEmployeeCodeId;
        }
        else
        {
            strEmployeeCodeId = Convert.ToString(Session["strEmployeeCodeId"]);
        }
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        if (Session["LeaveFrom_Date"] == null || Session["LeaveFrom_Date"] == string.Empty)
        {
            if (Request.QueryString["From_Date"] != null)
            {
                From_Date = Convert.ToString(Request.QueryString["From_Date"]);
            }
            else
            {
                From_Date = "";
            }
            Session["LeaveFrom_Date"] = From_Date;
        }
        else
        {
            From_Date = Convert.ToString(Session["LeaveFrom_Date"]);
        }
        if (Session["LeaveTo_Date"] == null || Session["LeaveTo_Date"] == string.Empty)
        {
            if (Request.QueryString["To_Date"] != null)
            {
                To_Date = Convert.ToString(Request.QueryString["To_Date"]);
            }
            else
            {
                To_Date = "";
            }
            Session["LeaveTo_Date"] = To_Date;
        }
        else
        {
            To_Date = Convert.ToString(Session["LeaveTo_Date"]);
        }
        if (From_Date != "")
        {
            From_Date = objcls_Common.DateConvertion(gstrDateFormat, From_Date);
        }
        if (To_Date != "")
        {
            To_Date = objcls_Common.DateConvertion(gstrDateFormat, To_Date);
        }
        dsYearSetting = objYearSettingsEventData.GetActiveYearSettings();
        if (dsYearSetting.Tables[0].Rows.Count <= 0)
        {
            return;
        }
        else
        {
            StartMonth = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["StartMonth"]);
            StartYear = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["StartYear"]);
            vmonthValue = MonthValue(StartMonth);
            startDate = Convert.ToString(vmonthValue) + "/1/" + StartYear;
            EndMonth = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["EndMonth"]);
            EndYear = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["EndYear"]);
            vmonthValue = MonthValue(EndMonth);
            endDate = Convert.ToString(vmonthValue) + "/31/" + EndYear;
        }
        if (LevelId == "0")
        {
            LevelId = null;
        }
        if (Status == "-Select Status-")
        {
            Status = null;
        }
        else if (Status == "All")
        {
            Status = "All";
        }
        if (From_Date == "")
        {
            From_Date = startDate;
        }
        if (To_Date == "")
        {
            To_Date = endDate;
        }
        bindLeaveSanctionDetails();
        if (!IsPostBack)
        {
            Session["LeaveChecked"] = null;
        }
    }
    #endregion
    #region userDefined function
    public void SortGrid(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)ViewState["DataLeaveSanction"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gdLeaveSanctionView.DataSource = dvSearch;
        gdLeaveSanctionView.DataBind();
    }
    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("Menu_Transactions_LeaveSanction", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        gdLeaveSanctionView.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        gdLeaveSanctionView.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        gdLeaveSanctionView.Columns[3].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        gdLeaveSanctionView.Columns[4].Caption = rm.GetString("Report_Duration", ci);
        gdLeaveSanctionView.Columns[5].Caption = rm.GetString("Type_Of_Leave", ci);
        gdLeaveSanctionView.Columns[6].Caption = rm.GetString("email_Status", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
    }
    public int MonthValue(string monthName)
    {
        if (monthName == "January")
            return 1;
        else if (monthName == "February")
            return 2;
        else if (monthName == "March")
            return 3;
        else if (monthName == "April")
            return 4;
        else if (monthName == "May")
            return 5;
        else if (monthName == "June")
            return 6;
        else if (monthName == "July")
            return 7;
        else if (monthName == "August")
            return 8;
        else if (monthName == "September")
            return 9;
        else if (monthName == "October")
            return 10;
        else if (monthName == "November")
            return 11;
        else if (monthName == "December")
            return 12;
        else
            return 0;
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(24, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    public void bindLeaveSanctionDetails()
    {
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            dtLeaveTransactionView = objLeaveApplicationEventData.GetLeaveSanctionDetailsForSuperAdmin(Convert.ToInt32(Session["EmpAutoID"]), LevelId, Convert.ToString(Session["LeaveSanctionStatus"]), From_Date, To_Date, strSwipeCardNo, strEmployeeName, strEmployeeCodeId, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(LevelId), 0, 0);
            gdLeaveSanctionView.DataSource = dtLeaveTransactionView;
            ViewState["DataLeaveSanction"] = dtLeaveTransactionView;
            Session["TotalLeaveApplication_Id"] = dtLeaveTransactionView.Rows.Count;
            gdLeaveSanctionView.DataBind();
            if (dtLeaveTransactionView.Rows.Count == 0)
            {
                checkRecordExists = false;
            }
        }
        else
        {
            dtLeaveTransactionView = objLeaveApplicationEventData.GetLeaveSanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), LevelId, Convert.ToString(Session["LeaveSanctionStatus"]), Convert.ToDateTime(From_Date), Convert.ToDateTime(To_Date), strSwipeCardNo, strEmployeeName, strEmployeeCodeId, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(LevelId), 0, 0);
            gdLeaveSanctionView.DataSource = dtLeaveTransactionView;
            ViewState["DataLeaveSanction"] = dtLeaveTransactionView;
            Session["TotalLeaveApplication_Id"] = dtLeaveTransactionView.Rows.Count;
            gdLeaveSanctionView.DataBind();
            if (dtLeaveTransactionView.Rows.Count == 0)
            {
                checkRecordExists = false;
            }
        }
    }
    public void clearAllSession()
    {
        Session["levelId"] = string.Empty;
        Session["LeaveSanctionStatus"] = string.Empty;
        Session["strSwipeCardNo"] = string.Empty;
        Session["strEmployeeName"] = string.Empty;
        Session["strEmployeeCodeId"] = string.Empty;
        Session["LeaveFrom_Date "] = null;
        Session["LeaveTo_Date"] = null;
    }
    private void SanctionViewDetails()
    {
        ViewState["Employee_code_Id"] = Convert.ToString(dtSanctionView.Rows[0]["Employee_code_Id"]);
        ViewState["StatusOnLoad"] = Convert.ToString(dtSanctionView.Rows[0]["Status"]);
        ViewState["StatusBorrow"] = Convert.ToString(dtSanctionView.Rows[0]["IsBorrow"]);
    }
    private void SanctionViewDetails(int LeaveApplication_Id)
    {
        dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
        ViewState["Employee_code_Id"] = Convert.ToString(dtSanctionView.Rows[0]["Employee_code_Id"]);
        ViewState["StatusOnLoad"] = Convert.ToString(dtSanctionView.Rows[0]["Status"]);
        ViewState["StatusBorrow"] = Convert.ToString(dtSanctionView.Rows[0]["IsBorrow"]);
        ViewState["LeaveType"] = Convert.ToString(dtSanctionView.Rows[0]["LeaveType"]);
    }
    private void SendMailToApplicant(int LevelID, int LeaveApplication_Id, string EmployeeEamilId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string EmployeeName, string Status, string Remarks, string LeaveApplicationDate, string NoOfDays, string strLeaveType, string FromDate, string Todate, string FromSession, string ToSession)
    {
        MailMessage mailMessage = new MailMessage();
        string scriptText;
        DataTable dtTableScript = new DataTable();
        string strFromEmailId = string.Empty;
        try
        {
            string ScriptType = "Leave Application Sanction By Reporting to Person";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            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"]);
                string Employee_Code_Id = Convert.ToString(ViewState["Employee_code_Id"]);
                //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 (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                {
                    //if (strEmailIdSanctionAuthority != strEmailIdReportingTo)
                    //{
                    if (Status == "Forwarded")
                    {
                        if (EmployeeEamilId != string.Empty)
                        {
                            mailMessage.To.Add(new MailAddress(strEmailIdSanctionAuthority));
                        }
                        if (strEmailIdReportingTo != string.Empty)
                        {
                            mailMessage.CC.Add(new MailAddress(EmployeeEamilId));
                        }
                    }
                    else
                    {
                        if (EmployeeEamilId != string.Empty)
                        {
                            mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                        }
                        if (strEmailIdReportingTo != string.Empty)
                        {
                            mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                        }
                    }
                }
                else
                {
                    if (EmployeeEamilId != string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                    }
                }
                mailMessage.Subject = rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + LeaveApplicationDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + Status;
                mailMessage.Body = scriptText.Replace("<<lblLeaveApplicationForm>>", rm.GetString("email_LeaveApplicationForm", 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("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", EmployeeName);
                mailMessage.Body = mailMessage.Body.Replace("<<lblApplicationDate>>", rm.GetString("email_LeaveApplicationDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ApplicationDate>>", LeaveApplicationDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveType>>", rm.GetString("lbl_leavetype", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<LeaveType>>", strLeaveType);
                mailMessage.Body = mailMessage.Body.Replace("<<lblLeaveDate>>", rm.GetString("email_LeaveDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromDate>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromDate>>", FromDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToDate>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToDate>>", Todate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblSession>>", rm.GetString("email_Session", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromSession>>", FromSession);
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromSession>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToSession>>", ToSession);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToSession>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblNumberDaysApplied>>", rm.GetString("email_NumberOfDaysApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<NumberDaysApplied>>", NoOfDays);
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", "Reason");
                mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", Remarks);
                if (Status == "Forwarded")
                {
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?LeaveApplication_Id=" + Convert.ToString(LeaveApplication_Id) + "&LevelId=" + LevelID + "&Status=" + Status + "&ApprovalType=Leave");
                }
                else
                {
                    string strReplaceText = "<font face=\"Arial\" size=\"2\"><a href=\"<<LinkData>>\">Click here for approval</a></font>";
                    mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                }
                objcls_Common.SendMail(mailMessage);
            }
            else
            {
                checkEmail = false;
                objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(LeaveApplication_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + Convert.ToDateTime(FromDate).ToShortDateString() + " - " + Convert.ToDateTime(Todate).ToShortDateString() + " | " + Status, Convert.ToString(mailMessage.Body), "", "LeaveSanction");
            }
        }
        catch
        {
            checkEmail = false;
            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(LeaveApplication_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourLeaveApplicationFor", ci) + " - " + Convert.ToDateTime(FromDate).ToShortDateString() + " - " + Convert.ToDateTime(Todate).ToShortDateString() + " | " + Status, Convert.ToString(mailMessage.Body), "", "LeaveSanction");
        }
    }
    private string[] commaStringToArray(string strComma)
    {
        string[] strArray;
        strArray = strComma.Split(new char[] { ',' });
        string[] intArray = new string[strArray.Length];
        for (int i = 0; i < strArray.Length; i++)
            intArray[i] = Convert.ToString(strArray[i]);
        return intArray;
    }
    #endregion
    #region ButtonEvents
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hdnSelectRow.Value != string.Empty && hdnSelectRow.Value != null)
        {
            #region SaveLeaveDetails
            string[] test;
            test = commaStringToArray(hdnSelectRow.Value);
            DataTable dsCheckedItem;
            dsCheckedItem = (DataTable)Session["LeaveChecked"];
            for (int i = 0; i < test.Length; i++)
            {
                LeaveApplication_Id = Convert.ToInt32(test[i]);
                dtSanctionView = objLeaveApplicationEventData.GetLeaveApplicationByLeaveApplicationId(LeaveApplication_Id);
                SanctionViewDetails(LeaveApplication_Id);
                EmployeeName = Convert.ToString(dtSanctionView.Rows[0]["Employee_FirstName"]);
                Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
                Employee_Code_Id = Convert.ToString(dtSanctionView.Rows[0]["Employee_Code_Id"]);
                EmployeeEamilId = Convert.ToString(dtSanctionView.Rows[0]["EmailId"]);
                strLeaveApplicationDate = (DateTime.Parse(Convert.ToString(dtSanctionView.Rows[0]["Leave_ApplicationDate"]))).ToString(Convert.ToString(Session["MDateFormat"]));
                strNoOfDays = Convert.ToString(dtSanctionView.Rows[0]["NumberOfDays"]);
                Leave_FromDate = Convert.ToString(dtSanctionView.Rows[0]["Leave_FromDate"]);
                Leave_ToDate = Convert.ToString(dtSanctionView.Rows[0]["Leave_ToDate"]);
                ViewState["LevelName"] = Convert.ToString(dtSanctionView.Rows[0]["LevelName"]);
                Status = Convert.ToString(dtSanctionView.Rows[0]["Status"]);
                string strTypeOfLeave = Convert.ToString(dtSanctionView.Rows[0]["Type"]);
                int YearSettingID = Convert.ToInt16(dtSanctionView.Rows[0]["YearSettings_Id"]);
                ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.SelectReportingToSanctionAuthority(LeaveApplication_Id);
                if (Convert.ToString(Session["UserGroupName"]) != "SuperAdmin" && Convert.ToString(Session["HasSpecialRights"]) != "True")
                {
                    if (ds_ReportingToSanctionAuthorityList.Tables.Count > 0)
                    {
                        if (ds_ReportingToSanctionAuthorityList.Tables[0].Rows.Count > 0)
                        {
                            if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]) && Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                            {
                                Status = "Approved";
                            }
                            else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                            {
                                Status = "Forwarded";
                            }
                            else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                            {
                                Status = "Approved";
                            }
                        }
                    }
                }
                else
                {
                    if (Status == "Forwarded")
                    {
                        if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                        {
                        }
                        Status = "Approved";
                    }
                    if (Status == "Pending")
                    {
                        Status = "Forwarded";
                    }
                }
                NumberOfDays = Convert.ToDouble(dtSanctionView.Rows[0]["NumberOfDays"]);
                LeaveTypeId = Convert.ToInt32(dtSanctionView.Rows[0]["LeaveType_id"]);
                bool boolChkLeave = true;
                int intLeaveCount = 0;
                #region SavingLeaveApplication
                try
                {
                    if (strTypeOfLeave == "Leave")
                    {
                        if (Convert.ToString(ViewState["StatusBorrow"]) == "False")
                        {
                            if (Status == "Approved")
                            {
                                objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "A", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                            }
                        }
                        if (Convert.ToString(ViewState["StatusBorrow"]) == "True")
                        {
                            DataSet dsRemainingNoOfleaves = new DataSet();
                            double dblCurrLeave = 0.0;
                            if (Convert.ToString(ViewState["StatusOnLoad"]) != Status)
                            {
                                if (Status == "Approved")
                                {
                                    intLeaveCount = objLeaveApplicationEventData.CheckLeaveExistsBeforeBorrow(Leave_FromDate, Leave_ToDate, LeaveTypeId, Employee_Id);
                                    if (intLeaveCount > 0)
                                    {
                                        boolChkLeave = false;
                                        base.Message(rm.GetString("Msg_Alreadycurrentyearleaveapplicationsareavailabletoapprovereject", ci));
                                        return;
                                    }
                                    else
                                    {
                                        dsRemainingNoOfleaves = objLeaveApplicationEventData.GetRemainingNumberOfLeaves(Employee_Id, LeaveTypeId);
                                        dsRemainingNoOfleaves.Tables[0].TableName = "Details";
                                        if (dsRemainingNoOfleaves.Tables.Count > 0)
                                        {
                                            if (dsRemainingNoOfleaves.Tables[0].Rows.Count > 0)
                                            {
                                                dblCurrLeave = Convert.ToDouble(dsRemainingNoOfleaves.Tables["Details"].Rows[0]["RemainingNoOfLeaves"]);
                                            }
                                        }
                                        if (dblCurrLeave > 0)
                                        {
                                            boolChkLeave = false;
                                            base.Message(rm.GetString("Msg_Currentyearquotaavailableforthisleavetype", ci));
                                            return;
                                        }
                                        objLeaveApplicationEventData.UpdateYearClosureByLeaveSanction(NumberOfDays, LeaveTypeId, Employee_Id, "AB", Convert.ToInt32(Session["EmpAutoId"]), YearSettingID);
                                    }
                                }
                            }
                        }
                    }
                    if (boolChkLeave == true)
                    {
                        objLeaveApplicationEventData.UpdateLeaveApplicationSanction(LeaveApplication_Id, Status, Convert.ToInt32(Session["EmpAutoId"]), "Ok", Convert.ToInt32(Session["EmpAutoId"]));
                    }
                    objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, Leave_FromDate, Leave_ToDate, 0);
                    if (EmployeeEamilId != string.Empty)
                    {
                    }
                    ds_EmailIdOfSanctionAuthority = objPermissionEventData.SelectMailIdOfSanctionAuthority(Employee_Id);
                    if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows.Count > 0)
                    {
                        if (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                        {
                            if (Convert.ToString(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]) != string.Empty)
                            {
                                strEmailIdSanctionAuthority = Convert.ToString(ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"]);
                            }
                        }
                    }
                    dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                    if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                    {
                        if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                        {
                            if (Convert.ToString(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]) != string.Empty)
                            {
                                strEmailIdReportingTo = Convert.ToString(dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"]);
                            }
                        }
                    }
                    if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                    {
                        SendMailToApplicant(Convert.ToInt32(Session["LevelId"]), LeaveApplication_Id, EmployeeEamilId, strEmailIdReportingTo, strEmailIdSanctionAuthority, EmployeeName, Status, "Ok", strLeaveApplicationDate, strNoOfDays, Convert.ToString(ViewState["LeaveType"]), Convert.ToString(dtSanctionView.Rows[0]["Leave_FromDate"]), Convert.ToString(dtSanctionView.Rows[0]["Leave_ToDate"]), Convert.ToString(dtSanctionView.Rows[0]["Leave_SessionFrom"]), Convert.ToString(dtSanctionView.Rows[0]["Leave_SessionTo"]));
                    }
                    #region SMSNotification
                    try
                    {
                        DataSet dsGateway = new DataSet();
                        DataSet dsStatus = new DataSet();
                        bool isSmsEnabled = false;
                        string destinationKey = string.Empty;
                        string MessageKey = string.Empty;
                        string ServiceUrl = string.Empty;
                        string mobileNo = string.Empty;
                        string strTemplateName = string.Empty;
                        string EmployeecodeId = string.Empty;
                        bool isApplyAndReceiverSame = false;
                        if (Status == "Pending")
                            strTemplateName = "Leave Application - Apply";
                        else if (Status == "Forwarded")
                            strTemplateName = "Leave Application - Forward";
                        else if (Status == "Approved")
                            strTemplateName = "Leave Application - Approved";
                        else if (Status == "Approved")
                            strTemplateName = "Leave Application - Approved";
                        else if (Status == "Rejected")
                            strTemplateName = "Leave Application - Rejected";
                        dsStatus = objsms.GetTemplateStauts(strTemplateName);
                        if (dsStatus.Tables.Count > 0)
                        {
                            if (dsStatus.Tables[0].Rows.Count > 0 && Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["Status"]) != false)
                            {
                                dsGateway = objsms.SelectGatewayDetails();
                                if (dsGateway.Tables.Count > 0)
                                {
                                    if (dsGateway.Tables[0].Rows.Count > 0)
                                    {
                                        ServiceUrl = Convert.ToString(dsGateway.Tables[0].Rows[0]["ServiceUrl"]);
                                        destinationKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["DestinationKey"]);
                                        MessageKey = Convert.ToString(dsGateway.Tables[0].Rows[0]["MessageKey"]);
                                        isSmsEnabled = Convert.ToBoolean(dsStatus.Tables[0].Rows[0]["ToEmployee"]);
                                        if (dtSanctionView.Rows.Count > 0)
                                        {
                                            if (dtSanctionView.Rows.Count > 0)
                                            {
                                                mobileNo = Convert.ToString(dtSanctionView.Rows[0]["Mobile_Number"]);
                                                EmployeecodeId = Convert.ToString(dtSanctionView.Rows[0]["Employee_code_id"]);
                                            }
                                        }
                                        DataSet dsReceivers = new DataSet();
                                        dsReceivers = objsms.GetReceiversDetails(strTemplateName, EmployeecodeId, EmployeeName, Leave_FromDate + " To " + Leave_FromDate, strTypeOfLeave, Convert.ToString(strNoOfDays));
                                        if (dsReceivers.Tables.Count > 0)
                                        {
                                            if (dsReceivers.Tables[1].Rows.Count > 0)
                                            {
                                                foreach (DataRow dr in dsReceivers.Tables[1].Rows)
                                                {
                                                    if (Convert.ToString(dr["Mobile_Number"]) != "")
                                                    {
                                                        blnCheckSMS = objsms.SendSMSNotifications
                                                        (
                                                            ServiceUrl,
                                                            destinationKey,
                                                            MessageKey,
                                                            Convert.ToString(dr["Receivers"]),
                                                            Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                            Convert.ToString(dr["Mobile_Number"]),
                                                            EmployeecodeId,
                                                            strTemplateName,
                                                            Convert.ToString(dr["SwipeCardNo"])
                                                        );
                                                        if (isSmsEnabled)
                                                        {
                                                            if (Convert.ToString(dr["SwipeCardNo"]) == EmployeecodeId)
                                                            {
                                                                isApplyAndReceiverSame = true;
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        objsms.InsertLogDetails(strTemplateName, Convert.ToString(dr["SwipeCardNo"]), EmployeecodeId, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                objsms.InsertLogDetails(strTemplateName, "", EmployeecodeId, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Receivers are not having the configured usergroup");
                                            }
                                            if (isSmsEnabled)
                                            {
                                                if (mobileNo != string.Empty && isApplyAndReceiverSame != true)
                                                {
                                                    blnCheckSMS = objsms.SendSMSNotifications
                                                                    (
                                                                        ServiceUrl,
                                                                        destinationKey,
                                                                        MessageKey,
                                                                        "",
                                                                        Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]),
                                                                        Convert.ToString(mobileNo),
                                                                        EmployeecodeId,
                                                                         strTemplateName,
                                                                    Convert.ToString(EmployeecodeId)

                                                                    );

                                                }
                                                else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                                {
                                                    objsms.InsertLogDetails(strTemplateName, Convert.ToString(EmployeecodeId), EmployeecodeId, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                    #endregion
                    if (checkEmail == true && blnCheckSMS == true)
                    {
                        string strScript = string.Empty;
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_LeaveSanctionApplicationSaved", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_LeaveSanction.aspx');";
                        strScript = strScript + "</script>";
                        Page.RegisterStartupScript("AlertPAdd9975466", strScript);
                    }
                    else
                    {
                        if (NotSendedEmployeeCodeId == "")
                        {
                            NotSendedEmployeeCodeId = Convert.ToString(Employee_Code_Id);
                        }
                        else
                        {
                            string[] ExistEmployeeCode = NotSendedEmployeeCodeId.Split(',');
                            if (ExistEmployeeCode.Length > 0)
                            {
                                int pos = Array.IndexOf(ExistEmployeeCode, Employee_Code_Id);
                                if (pos <= -1)
                                {
                                    NotSendedEmployeeCodeId = NotSendedEmployeeCodeId + ',' + Convert.ToString(Employee_Code_Id);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                #endregion
            }
            if (NotSendedEmployeeCodeId != null)
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_LeaveSanctionApplicationSavedEmailnotsent_Bulk", ci) + NotSendedEmployeeCodeId + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertPAdd3674", strScript);
            }
            else
            {
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("PleaseSelectAnyOneLeaveApplication", ci) + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertPAdd3674", strScript);
            }
            if (test.Length == gdLeaveSanctionView.VisibleRowCount)
            {
                Session["LeaveChecked"] = null;
                bindLeaveSanctionDetails();
            }
            else
            {
                bindLeaveSanctionDetails();
                Session["LeaveChecked"] = null;
            }
            #endregion
        }
        else
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("PleaseSelectAnyOneLeaveApplication", ci) + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertPAdd996266", strScript);
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        clearAllSession();
        if (Convert.ToString(Session["isDashBoard"]) != "Yes")
        {
            Response.Redirect("TA_UI_Transactions_LeaveSanction.aspx");
        }
        else
        {
            if (Convert.ToString(Session["packageID"]) != "")
            {
                if (Convert.ToInt32(Session["packageID"]) == 168)  //Samsung
                    Response.Redirect("../Dashboard_Samsung.aspx");
            }
            Response.Redirect("../DashBoard.aspx");
        }
    }
    #endregion
    #region Gridview
    protected void gdLeaveSanctionView_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrderLeaveSanction"]);
                SortGrid(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void gdLeaveSanctionView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lbl = (Label)e.Row.Cells[1].FindControl("Label1");
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Convert.ToString(Session["MDateFormat"]));
            lbl.Text = date1;
            Label lbldur = (Label)e.Row.Cells[1].FindControl("Label3");
            string[] duration = lbldur.Text.Split(" - ".ToCharArray());
            string datedur = (Convert.ToDateTime(duration[0])).ToString(Convert.ToString(Session["MDateFormat"]));
            string datedur1 = (Convert.ToDateTime(duration[3])).ToString(Convert.ToString(Session["MDateFormat"]));
            lbldur.Text = datedur + " - " + datedur1;
            Label lblStatus = (Label)e.Row.Cells[1].FindControl("Label2");
            if (lblStatus.Text == "Approved")
            {
                lblStatus.Text = rm.GetString("btn_Approved", ci);
            }
            else if (lblStatus.Text == "Forwarded")
            {
                lblStatus.Text = rm.GetString("btn_Forwarded", ci);
            }
            else if (lblStatus.Text == "Pending")
            {
                lblStatus.Text = rm.GetString("btn_Pending", ci);
            }
            else if (lblStatus.Text == "Rejected")
            {
                lblStatus.Text = rm.GetString("btn_Reject", ci);
            }
        }
    }
    protected void gdLeaveSanctionView_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrderLeaveSanction"]) == string.Empty)
        {
            Session["SortOrderLeaveSanction"] = "Asc";
        }
        else if (Convert.ToString(Session["SortOrderLeaveSanction"]) == "Asc")
        {
            Session["SortOrderLeaveSanction"] = "Desc";
        }
        else
        {
            Session["SortOrderLeaveSanction"] = "Asc";
        }
        SortGrid(e.SortExpression, Convert.ToString(Session["SortOrderLeaveSanction"]));
    }
    #endregion
    protected void gdLeaveSanctionView_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
    {
        if (e.RowType == GridViewRowType.Data)
        {
            source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
            rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
            ci = Thread.CurrentThread.CurrentCulture;
            Label lbl = (Label)gdLeaveSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "Label1");
            string date1 = (Convert.ToDateTime(lbl.Text)).ToString(Convert.ToString(Session["MDateFormat"]));
            e.Row.Cells[3].Text = date1;
            string lbldur = Convert.ToString(e.GetValue("Duration"));
            string[] duration = lbldur.Split(" - ".ToCharArray());
            string datedur = (Convert.ToDateTime(duration[0])).ToString(Convert.ToString(Session["MDateFormat"]));
            string datedur1 = (Convert.ToDateTime(duration[3])).ToString(Convert.ToString(Session["MDateFormat"]));
            lbldur = datedur + " - " + datedur1;
            e.Row.Cells[4].Text = lbldur;
            Label lblStatus = (Label)gdLeaveSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "Label2");
            if (lblStatus.Text == "Approved")
            {
                lblStatus.Text = rm.GetString("btn_Approved", ci);
            }
            else if (lblStatus.Text == "Forwarded")
            {
                lblStatus.Text = rm.GetString("btn_Forwarded", ci);
            }
            else if (lblStatus.Text == "Pending")
            {
                lblStatus.Text = rm.GetString("btn_Pending", ci);
            }
            else if (lblStatus.Text == "Rejected")
            {
                lblStatus.Text = rm.GetString("btn_Reject", ci);
            }
        }
    }
}