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.Data.SqlClient;
using System.Globalization;
using System.Threading;
using System.Reflection;
using System.Resources;
public partial class Transactions_TA_UI_Transactions_ManualTimeEntrySanction : Base.BasePage
{
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    LeaveApplicationEventData objLeaveApplicationEventData = new LeaveApplicationEventData();
    cls_Common objClassCommon = new cls_Common();
    ManualEntryEventData objManualEntryEventData = new ManualEntryEventData();
    YearSettingsEventData objYearSettingsEventData = new YearSettingsEventData();
    EmployeeEventData objEmployee = new EmployeeEventData();
    DataSet dsEmployeeGroup = new DataSet();
    DataSet ds_Checkuser = new DataSet();
    string strScript = string.Empty;
    string strStatus = string.Empty;
    int intCompanyId;
    string startDate;
    int vmonthValue;
    string strFromDateTime, strToDateTime;
    string endDate, gstrDateFormat, LevelId, Status, From_Date, To_Date, StartMonth, EndMonth, StartYear, EndYear;
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        if (!Page.IsPostBack)
        {
            base.CheckPages(0);
            objClassCommon.menu("ManualTransaction", "98");
        }
        CultureInfo ci;
        string source_Language;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        LoadStrings(ci);
        string strSetAlert = "";
        strSetAlert = strSetAlert + "<script language='javascript'>";
        strSetAlert = strSetAlert + "SetAlertMessages('" + rm.GetString("Alert_SelectStatus", ci) + "','" + rm.GetString("Alert_EnterDate", ci) + "','" + rm.GetString("Alert_EnterToDate", ci) + "','" + rm.GetString("Msg_GrearterThanFrmDate", ci) + "');";
        strSetAlert = strSetAlert + "MaxLengthh('" + rm.GetString("Alert_MaximumLengthis", ci) + "');";
        strSetAlert = strSetAlert + "SetAlertCheckDate('" + rm.GetString("Alert_Validmonthdatefourdigit", ci) + "','" + rm.GetString("Alert_Validdatemonthfourdigit", ci) + "','" + rm.GetString("Alert_Invalidyearentry", ci) + "','" + rm.GetString("Alert_Invalidmonthentry", ci) + "','" + rm.GetString("Alert_Invaliddateentry", ci) + "','" + rm.GetString("Alert_IncorrectdateformatDDMONYYYY", ci) + "','" + rm.GetString("Alert_Entertime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "','" + rm.GetString("Alert_Invalidtimeformat1", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMM", ci) + "','" + rm.GetString("Alert_ValiddatemonthMMDDYYHHMMTT", ci) + "','" + rm.GetString("Alert_PleaseentervalidDateandTime", ci) + "','" + rm.GetString("Alert_Invalidvalueforhours", ci) + "','" + rm.GetString("Alert_Invalidvalueforminites", ci) + "');";
        strSetAlert = strSetAlert + "</script>";
        Page.RegisterStartupScript("SetAlertMessages", strSetAlert);
        UserRights();
        Hidden1.Value = Convert.ToString(Session["IDateFormat"]);
        if (!IsPostBack)
        {
            if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
            {
            }
            else
            {
                DataSet ds_RecordsCountLeaveReportingTo = new DataSet();
                ds_RecordsCountLeaveReportingTo = objLeaveApplicationEventData.GetRecordsCountLeaveReportingTo(Convert.ToInt32(Session["EmpAutoId"]));
                DataSet dsRecordsCount = new DataSet();
                dsRecordsCount = objLeaveApplicationEventData.GetRecordsCountLeaveSanction(Convert.ToInt32(Session["EmpAutoId"]));
                if ((Convert.ToInt32(ds_RecordsCountLeaveReportingTo.Tables[0].Rows[0]["RecordsCount"]) > 0) && (Convert.ToInt32(dsRecordsCount.Tables[0].Rows[0]["RecordsCount"]) > 0))
                {
                }
                else if (Convert.ToInt32(ds_RecordsCountLeaveReportingTo.Tables[0].Rows[0]["RecordsCount"]) > 0)
                {
                    ddlStatus.Items[1].Enabled = false;
                    ddlStatus.Items[3].Enabled = false;
                }
                else if (Convert.ToInt32(dsRecordsCount.Tables[0].Rows[0]["RecordsCount"]) > 0)
                {
                    ddlStatus.Items[1].Enabled = false;
                    ddlStatus.Items[4].Enabled = false;
                }
            }
            BindingEmployeeCategoryandType();
        }
    }
    /// <summary>
    /// Compare FromDate and ToDate
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void CompareDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtFromDate.Text, "D");
            strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtToDate.Text, "D");
            DateTime dtToDate = DateTime.Parse(strToDateTime);
            DateTime dtFromDate = DateTime.Parse(strFromDateTime);
            TimeSpan diff = dtToDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
        }
    }
    public int getParentCompany(int iEmployeeLevelID)
    {
        org_levelsEventData getOrg = new org_levelsEventData();
        getOrg.GetOrgParentLevels_FromID(iEmployeeLevelID);
        DataSet ds_getOrg = new DataSet();
        ds_getOrg = getOrg.GetOrgParentLevels();
        int iCompanyID = 0;
        if (ds_getOrg != null)
        {
            if (ds_getOrg.Tables[0].Rows.Count > 0)
            {
                iCompanyID = Convert.ToInt32(ds_getOrg.Tables[0].Rows[0]["LevelID"].ToString());
            }
        }
        return iCompanyID;
    }
    public string GetApprovalStatus(int intCompanyId, string strModule)
    {
        int approvalSettingsPageExists = 0;
        //Checking grade module is available or not and changed the id value from 110 to 228
        approvalSettingsPageExists = objClassCommon.CheckPageExistsInLicense(228);
        string strStatus = string.Empty;
        if (approvalSettingsPageExists == 1)
        {
            DataSet dsApprovalSettings = new DataSet();
            ShiftEvenData objShift = new ShiftEvenData();
            dsApprovalSettings = objShift.SelectApprovalSettings(intCompanyId);
            if (dsApprovalSettings != null)
            {
                if (dsApprovalSettings.Tables.Count > 0)
                {
                    if (dsApprovalSettings.Tables[0].Rows.Count > 0)
                    {
                        if (Convert.ToBoolean(dsApprovalSettings.Tables[0].Rows[0][strModule]) == false)
                        {
                            strStatus = "ApprovalNotRequired";
                        }
                        else
                        {
                            strStatus = "ApprovalRequired";
                        }
                    }
                    else
                    {
                        strStatus = "NotDefined";
                    }
                }
            }
        }
        else
        {
            strStatus = "ApprovalRequired";
        }
        return strStatus;
    }
    /// <summary>
    /// Compare From Date with Current Date
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    /// 
    public void ValidateFromDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strFromDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtFromDate.Text, "D");
            DateTime dtCurrentDate = DateTime.Now;
            DateTime dtFromDate = DateTime.Parse(strFromDateTime);
            TimeSpan diff = dtCurrentDate.Subtract(dtFromDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
        }
    }
    /// <summary>
    /// Compare To Date with Current Date
    /// </summary>
    /// <param name="s"></param>
    /// <param name="e"></param>
    public void ValidateToDate(object s, ServerValidateEventArgs e)
    {
        try
        {
            gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
            strToDateTime = objClassCommon.DateTimeConvertion((gstrDateFormat), txtToDate.Text, "D");
            DateTime dtCurrentDate = DateTime.Now;
            DateTime dtToDate = DateTime.Parse(strToDateTime);
            TimeSpan diff = dtCurrentDate.Subtract(dtToDate);
            int day = diff.Days;
            if (day >= 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
        catch
        {
        }
    }
    protected void btn_View_Click(object sender, EventArgs e)
    {
        string strModule = string.Empty;
        strModule = "ManualEntry";
        strScript = "";
        strScript = strScript + "<script language='javascript'>";
        if (Session["parentLevelId"] == null || Convert.ToInt32(Session["parentLevelId"]) == 0)
        {
            strStatus = rm.GetString("Alert_SelectCompany", ci);
            strScript = strScript + "alert('" + strStatus + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertManualApproval", strScript);
            return;
        }
        intCompanyId = getParentCompany(Convert.ToInt32(Session["parentLevelId"]));
        strStatus = GetApprovalStatus(intCompanyId, strModule);
        if (strStatus == "ApprovalNotRequired")
        {
            strStatus = rm.GetString("Alert_ApprovalNotRequiredforthiscompany", ci);
            strScript = strScript + "alert('" + strStatus + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertManualApproval", strScript);
            return;
        }
        else if (strStatus == "ApprovalRequired")
        {
        }
        else if (strStatus == "NotDefined")
        {
            strStatus = rm.GetString("Alert_ApprovalSettingsnotdefinedforthiscompany", ci);
            strScript = strScript + "alert('" + strStatus + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertManualApproval", strScript);
            return;
        }
        gstrDateFormat = Convert.ToString(Session["MDateFormat"]);
        DataSet dsYearSetting = new DataSet();
        dsYearSetting = objYearSettingsEventData.GetActiveYearSettings();
        if (dsYearSetting.Tables[0].Rows.Count <= 0)
        {
            return;
        }
        else
        {
            StartMonth = dsYearSetting.Tables[0].Rows[0]["StartMonth"].ToString();
            StartYear = dsYearSetting.Tables[0].Rows[0]["StartYear"].ToString();
            vmonthValue = MonthValue(StartMonth);
            startDate = vmonthValue.ToString() + "/1/" + StartYear;
            EndMonth = dsYearSetting.Tables[0].Rows[0]["EndMonth"].ToString();
            EndYear = dsYearSetting.Tables[0].Rows[0]["EndYear"].ToString();
            vmonthValue = MonthValue(EndMonth);
            endDate = vmonthValue.ToString() + "/31/" + EndYear;
        }
        int intcount = 0;
        string strFromDate, strToDate;
        if (txtFromDate.Text == "")
        {
            strFromDate = startDate;
            strToDate = endDate;
        }
        else
        {
            strFromDate = objClassCommon.DateConvertion(gstrDateFormat, txtFromDate.Text);
            strToDate = objClassCommon.DateConvertion(gstrDateFormat, txtToDate.Text);
        }
        int ParentID = Convert.ToInt32(Session["parentLevelId"]);
        intcount = BindManualEntrySanctionDetails(Convert.ToString(ParentID), ddlStatus.SelectedValue, txtEmployeeId.Text, txtEmployeeName.Text, ddlEmpCatagory.SelectedValue, ddlEmpType.SelectedValue, strFromDate, strToDate, txtSwipeCard.Text);
        if (intcount == 0)
        {
            strStatus = rm.GetString("Alert_Thereisnorecord", ci);
            strScript = strScript + "alert('" + strStatus + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("AlertManualApproval", strScript);
            return;
        }
        else
        {
            Response.Redirect("PopUpManualTimeEntryApproval.aspx?EmpId=" + txtEmployeeId.Text + "&EmpName=" + txtEmployeeName.Text + "&EmpCategory=" + ddlEmpCatagory.SelectedValue + "&EmpType=" + ddlEmpType.SelectedValue + "&FromDate=" + txtFromDate.Text + "&ToDate=" + txtToDate.Text + "&Status=" + ddlStatus.SelectedValue + "&SwipeCard=" + txtSwipeCard.Text + "");
            //strScript = strScript + "window.open('PopUpManualTimeEntryApproval.aspx?LevelID=" + ParentID + "&EmpId=" + txtEmployeeId.Text + "&EmpName=" + txtEmployeeName.Text + "&EmpCategory=" + ddlEmpCatagory.SelectedValue + "&EmpType=" + ddlEmpType.SelectedValue + "&FromDate=" + txtFromDate.Text + "&ToDate=" + txtToDate.Text + "&Status=" + ddlStatus.SelectedValue + "&SwipeCard=" + txtSwipeCard.Text + "','TimeCheck-ManualTimeEntry','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=900, height=600');";
            //strScript = strScript + "</script>";
            //Page.RegisterStartupScript("AlertManualApproval", strScript);
        }

    }

    public int BindManualEntrySanctionDetails(string LevelID, string Status, string EmployeeID, string EmployeeName, string EmployeeCategory, string EmployeeType, string From_Date, string To_Date, string strSwipeCard)
    {
        int intCount = 0;
        DataTable dtManualEntrySanctionView = new DataTable();
        if (Convert.ToString(Session["UserGroupName"]) == "SuperAdmin" || Convert.ToString(Session["HasSpecialRights"]) == "True")
        {
            dtManualEntrySanctionView = objManualEntryEventData.GetManualEntrySanctionDetailsForSuperAdmin(Convert.ToInt32(Session["EmpAutoId"]), LevelID, Status, EmployeeID, EmployeeName, Convert.ToInt32(EmployeeCategory), Convert.ToInt32(EmployeeType), From_Date, To_Date, strSwipeCard, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]));
            intCount = dtManualEntrySanctionView.Rows.Count;
        }
        else
        {
            dtManualEntrySanctionView = objManualEntryEventData.GetManualEntrySanctionDetails(Convert.ToInt32(Session["EmpAutoId"]), LevelID, Status, EmployeeID, EmployeeName, Convert.ToInt32(EmployeeCategory), Convert.ToInt32(EmployeeType), Convert.ToDateTime(From_Date), Convert.ToDateTime(To_Date), strSwipeCard, Convert.ToString(Session["UserGroupName"]), Convert.ToInt16(Session["parentLevelId"]));
            intCount = dtManualEntrySanctionView.Rows.Count;
        }
        return intCount;
    }
    private void LoadStrings(CultureInfo ci)
    {
        lbl_Header.Text = rm.GetString("UserGroups_ManualTimeEntrySanction", ci);
        lblEmployeeName.Text = rm.GetString("email_EmployeeName", ci);
        lblEmployeeId.Text = rm.GetString("email_EmployeeId", ci);
        lblEmpCategory.Text = rm.GetString("Master_Category", ci);
        lblEmpType.Text = rm.GetString("Master_Type", ci);
        lbl_From.Text = rm.GetString("email_FromDate", ci);
        lbl_Status.Text = rm.GetString("email_Status", ci);
        lbl_To.Text = rm.GetString("email_ToDate", ci);
        cus_ComDate.ErrorMessage = rm.GetString("Msg_GrearterThanFrmDate", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        btn_View.Text = "&nbsp;" + rm.GetString("btn_View", ci);
        lblEmpSwipe.Text = rm.GetString("TerminalDataType_Card_No", ci);
        ddlStatus.Items[0].Text = rm.GetString("ExportData_All", ci);
        ddlStatus.Items[1].Text = rm.GetString("btn_Approved", ci);
        ddlStatus.Items[2].Text = rm.GetString("btn_Forwarded", ci);
        ddlStatus.Items[3].Text = rm.GetString("btn_Pending", ci);
        ddlStatus.Items[4].Text = rm.GetString("btn_Reject", ci);
        lblFilter.Text = rm.GetString("lblFilter", ci);
        //cus_FromDate.ErrorMessage = rm.GetString("Alert_SelectvalidFromDate", ci);
        //cus_ToDate.ErrorMessage = rm.GetString("Alert_SelectvalidToDate", ci);
        cus_ComDate.ErrorMessage = rm.GetString("Custom_TodateShouldbegreaterthanFromdate", ci);
        ddlEmpCatagory.Items[0].Text = rm.GetString("Select", ci);
        ddlEmpType.Items[0].Text = rm.GetString("Select", ci);
    }
    #region "EmployeeCategoryandType
    /// <summary>
    /// Bindings the type of the employee category and Type.
    /// </summary>
    private void BindingEmployeeCategoryandType()
    {
        DataSet dsCategory = new DataSet();
        try
        {
            dsCategory = objEmployee.SelectCategoryDetailsEmployee("");
            if (dsCategory != null)
            {
                if (dsCategory.Tables[0].Rows.Count > 0)
                {
                    ddlEmpCatagory.DataSource = dsCategory;
                    ddlEmpCatagory.DataTextField = "CategoryName";
                    ddlEmpCatagory.DataValueField = "CategoryId";
                    ddlEmpCatagory.DataBind();
                }
                dsCategory.Dispose();
                foreach (ListItem item in ddlEmpCatagory.Items)
                {
                    item.Attributes.Add("title", item.Text);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        DataSet dsType = new DataSet();
        try
        {
            dsType = objEmployee.SelectTypeDetailsEmployee("");
            if (dsType != null)
            {
                if (dsType.Tables[0].Rows.Count > 0)
                {
                    ddlEmpType.DataSource = dsType;
                    ddlEmpType.DataTextField = "TypeName";
                    ddlEmpType.DataValueField = "TypeId";
                    ddlEmpType.DataBind();
                }
                dsType.Dispose();
                foreach (ListItem item in ddlEmpType.Items)
                {
                    item.Attributes.Add("title", item.Text);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    #endregion
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(98, Convert.ToInt32(Session["userGroup_Id"]), "viewPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    protected void btn_Back_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Transactions/TA_UI_Transactions_ManualTimeEntryList.aspx");
    }
    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;
    }
}
