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     :   Commented and added for passing ParentId insetead of levelid Mantis : 0019145
* */
public partial class Transactions_TA_UI_Transactions_PermissionBulkSanction : Base.BasePage
{
    #region Variable Declaration
    ResourceManager rm;
    SMSNotification objsms = new SMSNotification();
    bool blnCheckSMS = true;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    LeaveEventData objLeave = new LeaveEventData();
    PermissionEventData objPermissionEventData = new PermissionEventData();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    YearSettingsEventData objYearSettingsEventData = new YearSettingsEventData();
    cls_Common objcls_Common = new cls_Common();
    Rpt_Common rptcommon = new Rpt_Common();
    DataTable dtPermissionSanctionView = new DataTable();
    DataSet dsYearSetting = new DataSet();
    DataTable dtSanctionView = new DataTable();
    int vmonthValue;
    string startDate;
    string endDate, gstrDateFormat, LevelId = "", NewStatus, Status, StartMonth, EndMonth, StartYear, EndYear, From_Date, To_Date;
    string strSwipeCardNo = string.Empty;
    string strEmployeeName = string.Empty;
    string strEmployeeCodeId = string.Empty;
    string SelectedShift = string.Empty;
    bool checkEmail = true;
    string LastName = ""; string lblPermissionDate; string lblPermissionFromTime; string lblPermissionToTime;
    cls_Common objClassCommon = new cls_Common();
    DataSet ds_EmailIdOfSanctionAuthority = new DataSet();
    DataSet dsEmailIdOfReportingTo = new DataSet();
    DataSet dsRecordsCount = new DataSet();
    int Permission_Id, Employee_Id;
    string Remarks, EmployeeEamilId, strEmailIdSanctionAuthority, EmployeeName, Employee_Code_Id, strlevelName, gstrTimeFormat;
    string NotSendedEmployeeCodeId = "";
    string source_Language;
    string[] chkBoxIDs;
    DataSet ds_ReportingToSanctionAuthorityList = new DataSet();
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        gdPermissionSanctionView.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);
        string Level = "";
        UserRights();
        if (!IsPostBack)
        {
            objcls_Common.menu("PermissionTransaction", "248");
        }
        if (Convert.ToString(Session["LevelId"]) == string.Empty)
        {
            LevelId = Request.QueryString["LevelId"].ToString();
            Level = rptcommon.getNodes(Convert.ToInt16(LevelId), Convert.ToString(Session["LevelRights"]));
            LevelId = rptcommon.getNodes(Convert.ToInt16(LevelId), Convert.ToString(Session["LevelRights"]));
            Session["Level"] = Level;
            Session["LevelId"] = LevelId;
        }
        else
        {
            Level = Convert.ToString(Session["Level"]);
            LevelId = Convert.ToString(Session["LevelId"]);
        }
        if (Convert.ToString(Session["PermissionSanctionStatus"]) == string.Empty)
        {
            Status = Convert.ToString(Request.QueryString["Status"]);
            Session["PermissionSanctionStatus"] = Status;
        }
        else
        {
            Status = Convert.ToString(Session["PermissionSanctionStatus"]);
        }
        if (Convert.ToString(Session["strSwipeCardNo"]) == string.Empty)
        {
            if (Request.QueryString["strSwipeCardNo"] != null)
            {
                strSwipeCardNo = Convert.ToString(Request.QueryString["strSwipeCardNo"]);
            }
            else
            {
                strSwipeCardNo = "";
            }
            Session["strSwipeCardNo"] = strSwipeCardNo;
        }
        else
        {
            strSwipeCardNo = Convert.ToString(Session["strSwipeCardNo"]);
        }
        if (Convert.ToString(Session["strEmployeeName"]) == string.Empty)
        {
            if (Request.QueryString["strEmployeeName"] != null)
            {
                strEmployeeName = Convert.ToString(Request.QueryString["strEmployeeName"]);
            }
            else
            {
                strEmployeeName = "";
            }
            Session["strEmployeeName"] = strEmployeeName;
        }
        else
        {
            strEmployeeName = Convert.ToString(Session["strEmployeeName"]);
        }
        if (Convert.ToString(Session["strEmployeeCodeId"]) == string.Empty)
        {
            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 (Convert.ToString(Session["PermissionFrom_Date"]) == null || Convert.ToString(Session["PermissionFrom_Date"]) == "")
        {
            if (Request.QueryString["From_Date"] != null)
            {
                From_Date = Convert.ToString(Request.QueryString["From_Date"]);
            }
            else
            {
                From_Date = "";
            }
            Session["PermissionFrom_Date"] = From_Date;
        }
        else
        {
            From_Date = Convert.ToString(Session["PermissionFrom_Date"]);
        }
        if (Convert.ToString(Session["PermissionTo_Date"]) == null || Convert.ToString(Session["PermissionTo_Date"]) == "")
        {
            if (Request.QueryString["To_Date"] != null)
            {
                To_Date = Convert.ToString(Request.QueryString["To_Date"]);
            }
            else
            {
                To_Date = "";
            }
            Session["PermissionTo_Date"] = To_Date;
        }
        else
        {
            To_Date = Convert.ToString(Session["PermissionTo_Date"]);
        }
        if (Request.QueryString["Shift"] != null)
        {
            SelectedShift = Convert.ToString(Request.QueryString["Shift"]);
        }
        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 = vmonthValue.ToString() + "/1/" + StartYear;
            EndMonth = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["EndMonth"]);
            EndYear = Convert.ToString(dsYearSetting.Tables[0].Rows[0]["EndYear"]);
            vmonthValue = MonthValue(EndMonth);
            endDate = vmonthValue.ToString() + "/31/" + EndYear;
        }
        if (Convert.ToString(Session["isDashBoard"]) != "Yes")
        {
            if (LevelId == "0")
            {
                LevelId = null;
            }
        }
        if (Status == "-Select Status-")
        {
            Status = null;
        }
        else if (Status == "All")
        {
            Status = null;
        }
        if (From_Date == "")
        {
            From_Date = startDate;
        }
        if (To_Date == "")
        {
            To_Date = endDate;
        }
        if (!IsPostBack)
        {
            Session["PermissionChecked"] = null;
        }
        bindpermissionsanctiondetails();
    }
    #endregion
    #region  Gridview
    protected void gdPermissionSanctionView_PageIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if ((ViewState["SortExpression"]) != null)
            {
                string SortColumn = Convert.ToString(ViewState["SortExpression"]);
                string SortOrder = Convert.ToString(Session["SortOrder"]);
                SortGrid(SortColumn, SortOrder);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void gdPermissionSanctionView_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["SortExpression"] = e.SortExpression;
        if (Convert.ToString(Session["SortOrder"]) == string.Empty)
        {
            Session["SortOrder"] = "Asc";
        }
        else if (Convert.ToString(Session["SortOrder"]) == "Asc")
        {
            Session["SortOrder"] = "Desc";
        }
        else
        {
            Session["SortOrder"] = "Asc";
        }
        SortGrid(e.SortExpression, Convert.ToString(Session["SortOrder"]));
    }
    protected void gdPermissionSanctionView_HtmlRowCreated(object sender, DevExpress.Web.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;
            string Label1 = (string)e.GetValue("Permission_AppliedDate");
            string Lbl_FromTime = e.GetValue("Permission_FromTime").ToString();
            string Lbl_EndTime = e.GetValue("Permission_ToTime").ToString();
            string TEndTime;
            TEndTime = DateTime.Parse(Lbl_EndTime).ToString(Session["MTimeFormat"].ToString());
            string TFromTime;
            TFromTime = DateTime.Parse(Lbl_FromTime).ToString(Session["MDateFormat"].ToString()) + "&nbsp;" + DateTime.Parse(Lbl_FromTime).ToString(Session["MTimeFormat"].ToString());
            e.Row.Cells[4].Text = TFromTime + " To " + TEndTime;
            Label lblStatus = (Label)gdPermissionSanctionView.FindRowCellTemplateControl(e.VisibleIndex, null, "lblPermissionStatus");
            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);
            }
        }
    }
    #endregion
    #region UserDefinedFunction
    /// <summary>
    /// Clear all session Values
    /// </summary>
    public void clearAllSession()
    {
        Session["LevelId"] = string.Empty;
        Session["PermissionSanctionStatus"] = string.Empty;
        Session["strSwipeCardNo"] = string.Empty;
        Session["strEmployeeName"] = string.Empty;
        Session["strEmployeeCodeId"] = string.Empty;
        Session["PermissionFrom_Date"] = string.Empty;
        Session["PermissionTo_Date"] = string.Empty;
    }
    // Getting Information from resource file and display it in label
    private void LoadStrings(CultureInfo ci)
    {
        lbl_HeaderPermissionSanction.Text = rm.GetString("Transaction_PermissionSanction_PermissionSanction", ci);
        btnBack.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        gdPermissionSanctionView.Columns[1].Caption = rm.GetString("email_EmployeeId", ci);
        gdPermissionSanctionView.Columns[2].Caption = rm.GetString("email_EmployeeName", ci);
        gdPermissionSanctionView.Columns[3].Caption = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        gdPermissionSanctionView.Columns[4].Caption = rm.GetString("Report_Duration", ci);
        gdPermissionSanctionView.Columns[5].Caption = rm.GetString("email_Status", ci);
        btnSave.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
    }
    public void SortGrid(string SortColumn, string SortOrder)
    {
        DataTable dtSrch = new DataTable();
        DataView dvSearch = new DataView();
        dtSrch = (DataTable)ViewState["DataPermissionSanction"];
        dvSearch.Table = dtSrch;
        dvSearch.Sort = SortColumn + " " + SortOrder;
        gdPermissionSanctionView.DataSource = dvSearch;
        gdPermissionSanctionView.DataBind();
    }
    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()
    {
        //approval page id -- 248
        ds_Checkuser = objCheckUser.checkRights(248, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    public void bindpermissionsanctiondetails()
    {
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            dtPermissionSanctionView = objPermissionEventData.GetPermissionSanctionDetailsForSuperAdmin(Convert.ToInt32(Session["EmpAutoID"]), LevelId, Status, From_Date, To_Date, strSwipeCardNo, strEmployeeName, strEmployeeCodeId, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]), 0, 0);
            gdPermissionSanctionView.DataSource = dtPermissionSanctionView;
            ViewState["DataPermissionSanction"] = dtPermissionSanctionView;
            Session["TotalPermissionID"] = dtPermissionSanctionView.Rows.Count;
            gdPermissionSanctionView.DataBind();
        }
        else
        {
            dtPermissionSanctionView = objPermissionEventData.GetPermissionSanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), LevelId, Status, Convert.ToString(From_Date), Convert.ToString(To_Date), strSwipeCardNo, strEmployeeName, strEmployeeCodeId, Convert.ToString(Session["UserGroupName"]), Convert.ToInt32(Session["parentLevelId"]), 0, 0);
            gdPermissionSanctionView.DataSource = dtPermissionSanctionView;
            ViewState["DataPermissionSanction"] = dtPermissionSanctionView;
            Session["TotalPermissionID"] = dtPermissionSanctionView.Rows.Count;
            gdPermissionSanctionView.DataBind();
        }
    }
    public string CalculateNumberOfHoursApplied(string startTime, string EndTime)
    {
        TimeSpan tsDiff = new TimeSpan();
        DateTime dtmIn = DateTime.Parse(startTime);
        DateTime dtmOut = DateTime.Parse(EndTime);
        tsDiff = dtmOut.Subtract(dtmIn);
        string s = tsDiff.ToString();
        int sReturn = s.LastIndexOf(':');
        string RemainHours = s.Remove(sReturn);
        return (RemainHours);
    }
    private void SendMailToApplicant(string EmployeeEamilId, string strEmailIdReportingTo, string strEmailIdSanctionAuthority, string Status, string Remarks, string EmployeeCodeId, string TotalHours, string levelName, string employeename)
    {
        MailMessage mailMessage = new MailMessage();
        string scriptText;
        DataTable dtTableScript = new DataTable();
        string strFromEmailId = string.Empty;
        try
        {
            string ScriptType = "Permission Application Sanction By Reporting to Person";
            dtTableScript = objLeaveApplicationEventData.GetEmailScripts(ScriptType);
            if (dtTableScript.Rows.Count > 0)
            {
                scriptText = dtTableScript.Rows[0]["ScriptText"].ToString();
                //if (Session["loginEmailId"] != null && Convert.ToString(Session["loginEmailId"]) != string.Empty)
                //{
                //    mailMessage.From = new MailAddress(Session["loginEmailId"].ToString());
                //    strFromEmailId = Convert.ToString(Session["loginEmailId"]);
                //}
                //else
                //{
                mailMessage.From = new MailAddress(ConfigurationManager.AppSettings.Get("FromId"));
                strFromEmailId = Convert.ToString(ConfigurationManager.AppSettings.Get("FromId"));
                //}
                if (Status == "Forwarded")
                {
                    if (strEmailIdSanctionAuthority != string.Empty)
                    {
                        mailMessage.To.Add(new MailAddress(strEmailIdSanctionAuthority));
                    }
                    if (EmployeeEamilId != string.Empty)
                    {
                        mailMessage.CC.Add(new MailAddress(EmployeeEamilId));
                    }
                }
                if (Session["loginEmailId"] != null && Session["loginEmailId"].ToString() != string.Empty)
                {
                    if (strEmailIdSanctionAuthority != strEmailIdReportingTo)
                    {
                        if (Status != "Forwarded")
                        {
                            if (Session["loginEmailId"].ToString() == strEmailIdSanctionAuthority)
                            {
                                if (EmployeeEamilId != string.Empty)
                                {
                                    mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                                }
                                if (strEmailIdReportingTo != string.Empty)
                                {
                                    mailMessage.CC.Add(new MailAddress(strEmailIdReportingTo));
                                }
                            }
                            if (Session["loginEmailId"].ToString() == strEmailIdReportingTo)
                            {
                                if (EmployeeEamilId != string.Empty)
                                {
                                    mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                                }
                            }
                        }
                    }
                    else
                    {
                        if (Status != "Forwarded")
                        {
                            if (EmployeeEamilId != string.Empty)
                            {
                                mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                            }
                        }
                    }
                }
                else
                {
                    if (Status != "Forwarded")
                    {
                        if (EmployeeEamilId != string.Empty)
                        {
                            mailMessage.To.Add(new MailAddress(EmployeeEamilId));
                        }
                    }
                }
                if (Status == "Approved")
                {
                    Status = rm.GetString("btn_Approved", ci);
                }
                else if (Status == "Forwarded")
                {
                    Status = rm.GetString("btn_Forwarded", ci);
                }
                else if (Status == "Pending")
                {
                    Status = rm.GetString("btn_Pending", ci);
                }
                else if (Status == "Rejected")
                {
                    Status = rm.GetString("btn_Reject", ci);
                }
                mailMessage.Subject = rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Employee_Code_Id + " - " + EmployeeName + " | " + levelName + " - " + Status;
                mailMessage.Body = scriptText.Replace("<<lblPermissionSanction>>", rm.GetString("email_PermissionForm", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeId>>", rm.GetString("email_EmployeeId", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeId>>", EmployeeCodeId);
                mailMessage.Body = mailMessage.Body.Replace("<<lblEmployeeName>>", rm.GetString("email_EmployeeName", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<EmployeeName>>", employeename);
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermissionDate>>", rm.GetString("Permission_PermissionDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<PermissionDate>>", lblPermissionDate);
                mailMessage.Body = mailMessage.Body.Replace("<<lblNumberOfHoursApplied>>", rm.GetString("email_NumberOfHoursApplied", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<NumberOfHoursApplied>>", TotalHours);
                mailMessage.Body = mailMessage.Body.Replace("<<lblPermission>>", rm.GetString("Dash_Permission", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<lblFromTime>>", rm.GetString("email_FromDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<FromTime>>", lblPermissionFromTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblToTime>>", rm.GetString("email_ToDate", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<ToTime>>", lblPermissionToTime);
                mailMessage.Body = mailMessage.Body.Replace("<<lblStatus>>", rm.GetString("email_Status", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Status>>", Status);
                mailMessage.Body = mailMessage.Body.Replace("<<lblReason>>", rm.GetString("email_Reason", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Reason>>", Remarks);
                mailMessage.Body = mailMessage.Body.Replace("<<lblRemarks>>", rm.GetString("email_Remarks", ci));
                mailMessage.Body = mailMessage.Body.Replace("<<Remarks>>", "Ok");
                if (Status == "Forwarded" || Status == "Pending")
                {
                    mailMessage.Body = mailMessage.Body.Replace("<<LinkData>>", Convert.ToString(Session["HostServerURL"]) + "?Permission_Id=" + Convert.ToString(Permission_Id) + "&LevelId=" + Session["LevelId"] + "&Status=" + Status + "&ApprovalType=Permission");
                }
                else
                {
                    string strReplaceText = "<a href=<<LinkData>>><font face=\"Arial\" size=\"2\">Click here for approval</font>";
                    mailMessage.Body = mailMessage.Body.Replace(strReplaceText, string.Empty);
                }
                objClassCommon.SendMail(mailMessage);
            }
            else
            {
                objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(Permission_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Status, mailMessage.Body.ToString(), "", "PermissionSanction");
                checkEmail = false;
            }
        }
        catch
        {
            objLeaveApplicationEventData.InsertLeaveApplicationDetailsInEmailTrigger(Permission_Id, strFromEmailId, EmployeeEamilId, strEmailIdReportingTo, rm.GetString("email_YourPermissionApplicationFor", ci) + " - " + lblPermissionDate + " | " + Status, mailMessage.Body.ToString(), "", "PermissionSanction");
            checkEmail = false;
        }
    }
        private void SanctionViewDetails(int PermissionID)
    {
        Permission_Id = Convert.ToInt32(PermissionID);
        dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
        if (dtSanctionView.Rows[0]["Employee_LastName"] != DBNull.Value)
        {
            LastName = dtSanctionView.Rows[0]["Employee_LastName"].ToString();
        }
        EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
        lblPermissionDate = (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"])).ToString(Session["MDateFormat"].ToString());
        string[] PerTime = dtSanctionView.Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
        string timePart1 = PerTime[1].ToString() + " " + PerTime[2].ToString();
        lblPermissionFromTime = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
        string[] PerTime1 = dtSanctionView.Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
        string timePart2 = PerTime1[1].ToString() + " " + PerTime1[2].ToString();
        lblPermissionToTime = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
    }
    #endregion
    #region ButtonEvents
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (hdnSelectRow.Value != string.Empty)
        {
            DataTable dsCheckedItem;
            dsCheckedItem = (DataTable)Session["PermissionChecked"];
            chkBoxIDs = objLeave.commaStringToArray(hdnSelectRow.Value);
            for (int i = 0; i < chkBoxIDs.Length; i++)
            {
                Permission_Id = Convert.ToInt32(chkBoxIDs[i]);
                dtSanctionView = objPermissionEventData.GetPermissionByPermissionId(Permission_Id);
                if (dtSanctionView.Rows.Count > 0)
                {
                    if (dtSanctionView.Rows[0]["EmailId"] != DBNull.Value)
                    {
                        EmployeeEamilId = dtSanctionView.Rows[0]["EmailId"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_Id"] != DBNull.Value)
                    {
                        Employee_Id = Convert.ToInt32(dtSanctionView.Rows[0]["Employee_Id"]);
                    }
                    if (dtSanctionView.Rows[0]["Employee_Code_Id"] != DBNull.Value)
                    {
                        Employee_Code_Id = dtSanctionView.Rows[0]["Employee_Code_Id"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["Employee_FirstName"] != DBNull.Value)
                    {
                        EmployeeName = dtSanctionView.Rows[0]["Employee_FirstName"].ToString();
                    }
                    if (dtSanctionView.Rows[0]["name"] != DBNull.Value)
                    {
                        strlevelName = dtSanctionView.Rows[0]["name"].ToString();
                    }
                    gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                    gstrTimeFormat = Session["MTimeFormat"].ToString();
                    string strFromDateTime = string.Empty;
                    string strToDateTime = string.Empty;
                    string[] PerTime = dtSanctionView.Rows[0]["Permission_FromTime"].ToString().Split(" ".ToCharArray());
                    string timePart1 = PerTime[0].ToString() + " " + PerTime[1].ToString();
                    lblPermissionFromTime = (Convert.ToDateTime(PerTime[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart1).ToString(Session["MTimeFormat"].ToString());
                    string[] PerTime1 = dtSanctionView.Rows[0]["Permission_ToTime"].ToString().Split(" ".ToCharArray());
                    string timePart2 = PerTime1[0].ToString() + " " + PerTime1[1].ToString();
                    lblPermissionToTime = (Convert.ToDateTime(PerTime1[0])).ToString(Session["MDateFormat"].ToString()) + " " + DateTime.Parse(timePart2).ToString(Session["MTimeFormat"].ToString());
                    lblPermissionDate = (Convert.ToDateTime(dtSanctionView.Rows[0]["Permission_Date"])).ToString(Session["MDateFormat"].ToString());
                    NewStatus = dtSanctionView.Rows[0]["Permission_Status"].ToString();
                    strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionFromTime, "B");
                    strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat + " " + gstrTimeFormat), lblPermissionToTime, "B");
                    string dNumberOfHoursApplied = string.Empty;
                    dNumberOfHoursApplied = CalculateNumberOfHoursApplied(strFromDateTime, strToDateTime);
                    ds_ReportingToSanctionAuthorityList = objLeaveApplicationEventData.SelectReportingToSanctionAuthorityForPermission(Permission_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"]))
                                {
                                    NewStatus = "Approved";
                                }
                                else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Reporting_To"]))
                                {
                                    NewStatus = "Forwarded";
                                }
                                else if (Convert.ToString(Session["EmpAutoId"]) == Convert.ToString(ds_ReportingToSanctionAuthorityList.Tables[0].Rows[0]["Leave_Sanc_Authority"]))
                                {
                                    NewStatus = "Approved";
                                }
                            }
                        }
                    }
                    else
                    {
                        if (NewStatus == "Forwarded")
                        {
                            NewStatus = "Approved";
                        }
                        if (NewStatus == "Pending")
                        {
                            NewStatus = "Forwarded";
                        }
                    }
                    Remarks = "";
                    try
                    {
                        objPermissionEventData.UpdatePermissionSanction(Permission_Id, NewStatus, Remarks, Convert.ToInt32(Session["EmpAutoId"]));
                        cls_Common objclscommon = new cls_Common();
                        string strPermissionDate = objclscommon.DateConvertion(gstrDateFormat, lblPermissionDate);
                        objLeaveApplicationEventData.UpdateProcessedDataFlag(Employee_Id, strPermissionDate, strPermissionDate, 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 (ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString() != "")
                                {
                                    strEmailIdSanctionAuthority = ds_EmailIdOfSanctionAuthority.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                        }
                        dsEmailIdOfReportingTo = objPermissionEventData.SelectMailIdOfReportingTo(Employee_Id);
                        string strEmailIdReportingTo = string.Empty;
                        if (dsEmailIdOfReportingTo.Tables[0].Rows.Count > 0)
                        {
                            if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"] != DBNull.Value)
                            {
                                if (dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString() != string.Empty)
                                {
                                    strEmailIdReportingTo = dsEmailIdOfReportingTo.Tables[0].Rows[0]["EmailId"].ToString();
                                }
                            }
                        }
                        if (Convert.ToInt32(ConfigurationManager.AppSettings.Get("isRequiredEmail")) == 1)
                        {
                            SendMailToApplicant(EmployeeEamilId, strEmailIdReportingTo, strEmailIdSanctionAuthority, NewStatus, Remarks, Employee_Code_Id, dNumberOfHoursApplied, strlevelName, EmployeeName);
                        }
                        #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;
                            bool isApplyAndReceiverSame = false;
                            if (Status == "Pending")
                                strTemplateName = "Permission Application - Apply";
                            else if (Status == "Forwarded")
                                strTemplateName = "Permission Application - Forward";
                            else if (Status == "Approved")
                                strTemplateName = "Permission Application - Approved";
                            else if (Status == "Rejected")
                                strTemplateName = "Permission 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"]);
                                                    EmployeeName = Convert.ToString(dtSanctionView.Rows[0]["Employee_FirstName"]);
                                                }
                                            }
                                            DataSet dsReceivers = new DataSet();
                                            dsReceivers = objsms.GetReceiversDetails(strTemplateName, Employee_Code_Id, EmployeeName, strFromDateTime + " To " + strToDateTime, "", Convert.ToString(dNumberOfHoursApplied));
                                            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"]),
                                                                Employee_Code_Id,
                                                                strTemplateName,
                                                                Convert.ToString(dr["SwipeCardNo"])
                                                            );
                                                            if (isSmsEnabled)
                                                            {
                                                                if (Convert.ToString(dr["SwipeCardNo"]) == Employee_Code_Id)
                                                                {
                                                                    isApplyAndReceiverSame = true;
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            objsms.InsertLogDetails(strTemplateName, Convert.ToString(dr["SwipeCardNo"]), Employee_Code_Id, false, Convert.ToString(dsReceivers.Tables[0].Rows[0]["Message"]), "Mobile Number is not configured in employee master");
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    objsms.InsertLogDetails(strTemplateName, "", Employee_Code_Id, 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),
                                                                            Employee_Code_Id,
                                                                             strTemplateName,
                                                                        Convert.ToString(Employee_Code_Id)
                                                                        );
                                                    }
                                                    else if (mobileNo == string.Empty && isApplyAndReceiverSame != true)
                                                    {
                                                        objsms.InsertLogDetails(strTemplateName, Convert.ToString(Employee_Code_Id), Employee_Code_Id, 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)
                        {
                            hdnSelectRow.Value = "";
                            string strScript = string.Empty;
                            strScript = strScript + "<script language='javascript'>";
                            strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsaved", ci) + "');";
                            strScript = strScript + "location.replace('TA_UI_Transactions_PermissionSanction.aspx');";
                            strScript = strScript + "</script>";
                            Page.RegisterStartupScript("AlertPsaved36774", strScript);
                        }
                        else
                        {
                            if (NotSendedEmployeeCodeId == "")
                            {
                                NotSendedEmployeeCodeId = 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 + ',' + Employee_Code_Id;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            if (NotSendedEmployeeCodeId != null)
            {
                hdnSelectRow.Value = "";
                string strScript = string.Empty;
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_PermissionApplicationsavedEmailnotsent_Bulk", ci) + NotSendedEmployeeCodeId + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("AlertPAdd3674", strScript);
            }
            bindpermissionsanctiondetails();
        }
        else
        {
            string strScript = string.Empty;
            strScript = strScript + "<script language='javascript'>";
            strScript = strScript + "alert('" + rm.GetString("Alert_SelectAnyOneApplication", ci) + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertPAdd3674", strScript);
        }
    }
    public void GetEmptyText(object sender, EventArgs e)
    {
        Label lblNoRecords = (Label)sender;
        lblNoRecords.Text = rm.GetString("Alert_Norecordsfound", ci);
    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        clearAllSession();
        if (Convert.ToString(Session["isDashBoard"]) != "Yes")
        {
            Response.Redirect("TA_UI_Transactions_PermissionSanction.aspx");
        }
        else
        {
            string From_Datenew = "";
            if (Request.QueryString["From_Date"] != null)
            {
                From_Datenew = objcls_Common.DateConvertion(gstrDateFormat, Request.QueryString["From_Date"]);
            }
            Response.Redirect("../DashBoard.aspx?LevelId=" + Request.QueryString["LevelId"] + "&From_Date=" + From_Datenew + "&Shift=" + SelectedShift);
        }
    }
    #endregion
}
