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.IO;

public partial class Transactions_TA_UI_Transactions_ManualCompensationEntry_Add : Base.BasePage
{
    #region Variable Declaration
    cls_Common objCommon = new cls_Common();
    EmployeeEventData objEmployeeEventData = new EmployeeEventData();
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    LeaveApplicationEventData objLeaveApplication = new LeaveApplicationEventData();
    Email_Triggering ObjEmailTrigger = new Email_Triggering();
    OTEventData objOT = new OTEventData();
    cls_Common objClassCommon = new cls_Common();
    DataSet ds_Checkuser = new DataSet();
    DataSet dsEmployeeDetails = new DataSet();
    DataSet dsCompensation = new DataSet();
    string gstrDateFormat = string.Empty;
    DateTime dtCurrentDate, dtApplicationDate, dtFromDate, dtExpiryDate;
    string strFromDateTime, strApplicationDate, strApplyDate;
    bool blnCheckEmail;
    DateTime gdtmBackDate;
    ResourceManager rm;
    CultureInfo ci;
    int intIndividualUser = 0;
    int intEmployeeId;
    string strEmpFirstName, strEmpLastName;
    string strEmailIdSanctioningAuthority, strEmailIdReportingTo, strEmployeeCodeId, strEmployeeName, strlevelName, strEmailID, TimeFormat = string.Empty;
    //DateTime gdtmBackDate;
    #endregion
    #region Page Load Event
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            objClassCommon.menu("OverTime", "254");
        }
        UserRights();
        string strSourceLanguage;
        strSourceLanguage = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(strSourceLanguage, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        LoadStrings(ci);

        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_EntertheEmployeeID", ci) + "','" + rm.GetString("Alert_SelectDutyDate", ci) + "','" + rm.GetString("Alert_WorkedHoursShouldnotbeempty", ci) + "','" + rm.GetString("Alert_WorkedHoursShouldnotbe0hrs", ci) + "','" + rm.GetString("Validator_ManualTimeEntry_Reason", ci) + "','" + rm.GetString("Alert_Are_you_sure_to_Save", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);

        dtCurrentDate = Convert.ToDateTime(System.DateTime.Today.Date.ToShortDateString());
        //lblLeaveApplicationDateData.Text = dtCurrentDate.ToString(Session["MDateFormat"].ToString());
        hdnDateFormat.Value = Convert.ToString(Session["IDateFormat"]);
        DataSet dsEmployeeGroup = new DataSet();
        intIndividualUser = objCheckUser.CheckIndividualUser(Convert.ToString(Session["UserGroupName"]));
        Session["intIndividualUser"] = intIndividualUser;
        hdnEmployeeId.Value = "0";
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || intIndividualUser == 0)
        {
            divEmployees.Visible = false;
            divAdmin.Visible = true;
            lblManCount.Text = "3";
        }
        else
        {
            divEmployees.Visible = true;
            divAdmin.Visible = false;
            hdnEmployeeId.Value = Convert.ToString(Session["EmpAutoId"]);
            lblManCount.Text = "2";
            GetEmployeeName();
        }


        if (!IsPostBack)
        {
            if (Convert.ToString(TimeFormat) == "HH:mm")
            {
                lblLeaveApplicationDateData.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");

            }
            else
            {
                lblLeaveApplicationDateData.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
            }
        }

    }
    #endregion
    #region User Defined Function
    public void CompareCurrentdate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtFromDate.Text, "D");
            DateTime dtFromDate = DateTime.Parse(strFromDateTime);
            TimeSpan diff;
            if (Convert.ToString(Session["HasSpecialRights"]) == "True" || Convert.ToString(Session["UserGroupName"]) == "IndividualUsers")
            {
                diff = dtFromDate.Subtract(gdtmBackDate);
            }
            else
            {
                DateTime dtCurrentDate = DateTime.Now;
                diff = dtFromDate.Subtract(dtCurrentDate);
            }
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
            {
                e.IsValid = false;
            }
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin")
            {
                e.IsValid = true;
            }
            if (e.IsValid == false)
            {
                
                string strScript = "<script language='javascript' type='text/javascript'>";
                strScript += "alert('"+ rm.GetString("Alert_Pastentriesarenotallowed", ci) + "');";
                strScript += " </script>";
                this.RegisterStartupScript("setScript", strScript);
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    private void LoadStrings(CultureInfo ci)
    {
        lblEmployeeIDLabel.Text = rm.GetString("email_EmployeeId", ci);
        lblEmployeeIDLabel1.Text = rm.GetString("email_EmployeeId", ci);
        lblEmployeeNameLabel.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeNameLabel1.Text = rm.GetString("email_EmployeeName", ci);
        lblLeaveApplicationDate.Text = rm.GetString("LeaveApplication_LeaveApplicationDate", ci);
        lblFromDate.Text = rm.GetString("lbl_DutyDate", ci);
        lbl_InTime.Text = rm.GetString("ManualTimeEntry_In_Time", ci);
        lbl_outTime.Text = rm.GetString("ManualTimeEntry_Out_Time", ci);
        lbl_DayWorked.Text = rm.GetString("lbl_Dayworked", ci);
        lbl_WorkedHrs.Text = rm.GetString("lbl_ExtraWorkedHrs", ci);
        btnAdd.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Save", ci);
        btnCancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        lblReason.Text= rm.GetString("email_Reason", ci);
        lblHeaderLeaveApplication.Text= rm.GetString("Transaction_CompensationEntry", ci);
    }
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtFromDate.Text, "D");
            DateTime dtFromDate = DateTime.Parse(strFromDateTime);
        }
        catch (Exception ex)
        {
            Response.Write(ex.ToString());
        }
    }
    #endregion
    #region Button Events
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            if (hdnLeavePolicyStatus.Value == "LeavePolicyNotAssign")
            {
                txt_Name.Text = Convert.ToString(hdnEmployeeName.Value);
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_LeavePolicynotallocatedforthisemployee", ci) + "');";
                strScript = strScript + "EmpName('CompOff');";
                strScript = strScript + "EmpNameForCompensationEntry('date', '" + hdnDateFormat.Value + "');";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                Page.RegisterStartupScript("Alertalreadyapplied", strScript);
                return;
            }
            //Proc_TA_GetShiftSettingsByComIdForCompOff
            if (hdnDayCompStatus.Value == "Not Reached")
            {
                txt_Name.Text = Convert.ToString(hdnEmployeeName.Value);
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_Definedhalfdaycompoffhoursnotreached", ci) + "');";
                strScript = strScript + "EmpName('CompOff');";
                strScript = strScript + "EmpNameForCompensationEntry('date', '" + hdnDateFormat.Value + "');";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                Page.RegisterStartupScript("Alertalreadyapplied", strScript);
                return;
            }
            
            
            int isRequestCompoff = 0;
            isRequestCompoff = objOT.GetShiftSettingsByComIdForCompOff(Convert.ToInt32(hdfTopLevelID.Value));
            if (isRequestCompoff == 1)
            {
                gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
                strApplicationDate = objClassCommon.DateConvertion(gstrDateFormat, txtFromDate.Text);
                strApplyDate = objClassCommon.DateConvertion(gstrDateFormat, lblLeaveApplicationDateData.Text);
                dsCompensation = objOT.InsertCompoff(Convert.ToInt32(hdfProcess_Rec_ID.Value), Convert.ToInt32(hdfEmployee_Id.Value), strApplyDate, strApplicationDate, Convert.ToString(hdfTotalWorkedHrs.Value), Convert.ToInt32(hdfExtraMins.Value), Convert.ToString(hdfOverTimeStatus.Value), Convert.ToInt32(hdfTopLevelID.Value), Convert.ToString(hdfDayWorked.Value), Convert.ToString(hdfInPunchTime.Value), Convert.ToString(hdfoutPunchTime.Value), Convert.ToString(txtReason.Text), 0, "I");
                if (dsCompensation.Tables[0].Rows[0][0].ToString() == "1")
                {
                    
                    dsEmployeeDetails = objLeaveApplication.GetEmployeeDetails(Convert.ToInt32(hdfEmployee_Id.Value));
                    if (dsEmployeeDetails.Tables.Count > 0)
                    {
                        if (dsEmployeeDetails.Tables[0].Rows.Count > 0)
                        {
                            if (dsEmployeeDetails.Tables[0].Rows[0]["ReportingToEmailID"] != DBNull.Value)
                            {
                                strEmailIdReportingTo = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["ReportingToEmailID"]);
                            }
                            if (dsEmployeeDetails.Tables[0].Rows[0]["ApprovalAuthorityEmailID"] != DBNull.Value)
                            {
                                strEmailIdSanctioningAuthority = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["ApprovalAuthorityEmailID"]);
                            }
                            strEmpFirstName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
                            strEmpLastName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
                            strEmployeeCodeId = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["Employee_Code_Id"]);
                            strEmployeeName = strEmpFirstName + " " + strEmpLastName;
                            strlevelName = Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["levelName"]);
                            strEmailID= Convert.ToString(dsEmployeeDetails.Tables[0].Rows[0]["EmailId"]);
                            blnCheckEmail = ObjEmailTrigger.SendMailCompOff(strEmailID, strEmailIdReportingTo, strEmailIdSanctioningAuthority, strEmployeeCodeId, strEmployeeName, Convert.ToString(lblLeaveApplicationDateData.Text), Convert.ToString(txtFromDate.Text), Convert.ToString(hdfInPunchTime.Value), Convert.ToString(hdfoutPunchTime.Value), Convert.ToString(hdfDayWorked.Value), Convert.ToString(hdfTotalWorkedHrs.Value), Convert.ToString(txtReason.Text), Convert.ToString(hdfOverTimeStatus.Value), strlevelName, "Add");
                        }
                    }
                    if (blnCheckEmail == true)
                    {
                        string strScript = "";
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_COffCreditApplicationSavedSuccessfully", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_ManualCompensationEntry.aspx');";
                        strScript = strScript + "</script>";
                        //Dispaly alert messsage.
                        Page.RegisterStartupScript("AlertPAdd65507866", strScript);
                    }
                    else
                    {
                        string strScript = "";
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_COffCreditApplicationSavedSuccessfullyEmailNot", ci) + "');";
                        strScript = strScript + "location.replace('TA_UI_Transactions_ManualCompensationEntry.aspx');";
                        strScript = strScript + "</script>";
                        //Dispaly alert messsage.
                        Page.RegisterStartupScript("AlertPAdd65507866", strScript);
                    }

                }
                else if (dsCompensation.Tables[0].Rows[0][0].ToString() == "0")
                {
                    txt_Name.Text = Convert.ToString(hdnEmployeeName.Value);
                    string strScript = "";
                    strScript = strScript + "<script language='javascript'>";
                    strScript = strScript + "alert('" + rm.GetString("Alert_CompensationEntryisalreadyapplied", ci) + "');";
                    strScript = strScript + "EmpName('CompOff');";
                    strScript = strScript + "EmpNameForCompensationEntry('date', '" + hdnDateFormat.Value + "');";
                    strScript = strScript + "</script>";
                    //Dispaly alert messsage.
                    Page.RegisterStartupScript("Alertalreadyapplied", strScript);
                    return;
                }
            }
            else
            {
                string strScript = "";
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_CompensationEntryRequestisnotallowed", ci) + "');";
                strScript = strScript + "EmpName('CompOff');";
                strScript = strScript + "EmpNameForCompensationEntry('date', '" + hdnDateFormat.Value + "');";
                strScript = strScript + "</script>";
                //Dispaly alert messsage.
                Page.RegisterStartupScript("AlertRequestisnot", strScript);
                return;
            }
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Transactions/TA_UI_Transactions_ManualCompensationEntry.aspx");
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(254, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    #endregion
    #region Employee Name.
    public void GetEmployeeName()
    {
        if (Session["user"] == null || Session["user"].ToString() == "")
        {
            Response.Redirect("../Index.aspx");
        }
        else
        {
            lblEmployeeIdData.Text = Convert.ToString(Session["EmployeeCodeId"]);
            intEmployeeId = Convert.ToInt32(Session["EmpAutoId"]);
            DataSet ds_EmployeeDetails = new DataSet();
            ds_EmployeeDetails = objEmployeeEventData.Select_EmployeeDetailsNewbyId(intEmployeeId);
            if (ds_EmployeeDetails.Tables[0].Rows.Count > 0)
            {
                strEmpFirstName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_FirstName"]);
                strEmpLastName = Convert.ToString(ds_EmployeeDetails.Tables[0].Rows[0]["Employee_LastName"]);
                lblEmployeeNameData.Text = strEmpFirstName + " " + strEmpLastName;
            }
        }
    }
    #endregion

 /****************************************************************************************************************************
* Project Name    : TimeCheck                  Started Date  : 27-Jan-2024
* Module          : Manual COMP OFF            Last Modified : 
* Programmer      : Hariharan.J
* Modified by     : 
*****************************************************************************************************************************/
    protected void txt_EmployeeId_TextChanged(object sender, EventArgs e)
    {
        #region UTC Time Save
        //String EmployeeID = Convert.ToString(Session["EmpAutoID"]);
        String EmployeeID = Convert.ToString(txt_EmployeeId.Text);
        org_levelsEventData getUtcEmployeeCheck = new org_levelsEventData();
        DataSet ds_UTC = new DataSet();
        ds_UTC = getUtcEmployeeCheck.GetUTCTimeZoneEmployeeCheck(EmployeeID);
        int Counts = ds_UTC.Tables[0].Rows.Count;
        //String UTC = Convert.ToString(Session["TimezoneId"]);
        //TimeZoneName,TimeZoneDesc,HoursToBeAdded,MinToBeAdded TimezoneId
        if (Counts != 0)
        {
            Session["TimezoneId"] = ds_UTC.Tables[0].Rows[0]["TimezoneId"].ToString();
            Session["TimeZoneName"] = ds_UTC.Tables[0].Rows[0]["TimeZoneName"].ToString();
            Session["TimeZoneDesc"] = ds_UTC.Tables[0].Rows[0]["TimeZoneValue"].ToString();
            Session["HoursToBeAdded"] = ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"].ToString();
            Session["MinToBeAdded"] = ds_UTC.Tables[0].Rows[0]["MinToBeAdded"].ToString();

            DateTime ConvertUTCTime = new DateTime();
            int hours = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["HoursToBeAdded"]);
            int Minutes = Convert.ToInt32(ds_UTC.Tables[0].Rows[0]["MinToBeAdded"]);
            ConvertUTCTime = objCommon.TimezoneGetDateTime(hours, Minutes);

            ViewState["CountryGetDateTime"] = ConvertUTCTime;


            if (Convert.ToString(TimeFormat) == "HH:mm")
            {
                lblLeaveApplicationDateData.Text = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm");

            }
            else
            {
                lblLeaveApplicationDateData.Text = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " hh:mm tt");
            }

            Session["CurrentCountryDatetime"] = ConvertUTCTime.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm:ss tt");

            string d = Session["CurrentCountryDatetime"].ToString();
            DateTime parsedDateTime;

            if (DateTime.TryParseExact(d, "dd/MM/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDateTime))
            {
                string formattedDate = parsedDateTime.ToString(Convert.ToString(Session["MDateFormat"]));
                string formattedUtcTime = parsedDateTime.ToString("hh:mm tt", CultureInfo.InvariantCulture);
                Session["CurrentCountryDatetimes"] = parsedDateTime;
                String A = Session["CurrentCountryDatetimes"].ToString();
              
            }


        }
        else
        {
            lblLeaveApplicationDateData.Text = DateTime.Now.ToString(Convert.ToString(Session["MDateFormat"]) + " HH:mm tt");
        }


        #endregion 
        //onblur="EmpName('CompOff');"
        Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "EmpName('CompOff');", true);


    }
}
