using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.IO;
public partial class Transactions_TA_UI_Transactions_ManualEntryImport : Base.BasePage
{
    #region VariableDeclaration
    ResourceManager rm;
    CultureInfo ci;
    Cls_CheckUser objCheckUser = new Cls_CheckUser();
    DataSet ds_Checkuser = new DataSet();
    EntranceEventData objEntrance = new EntranceEventData();
    HiddenField hdn_InTerminal = new HiddenField();
    HiddenField hdn_OutTerminal = new HiddenField();
    HiddenField hdn_InPunchType = new HiddenField();
    HiddenField hdn_OutPunchType = new HiddenField();
    ImportData ObjImportData = new ImportData();
    string gstrDateFormat = "dd-MMM-yyyy", strScript = "";
    cls_Common objCommon = new cls_Common();
    char chrImportDelimiter = ',';
    FileStream aFile;
    ManualEntryEventData objManualEntry = new ManualEntryEventData();
    PunchTypesEventdata objPunchTypes = new PunchTypesEventdata();
    ShiftAllocationEvendata objShiftAllocation = new ShiftAllocationEvendata();
    EmployeeEventData objEmployee = new EmployeeEventData();
    ShiftExchangeEventData objShiftExchange = new ShiftExchangeEventData();
    ShiftEvenData objShift = new ShiftEvenData();
    DataSet ds = new DataSet();
    TextBox txt_InDate = new TextBox();
    TextBox txt_OutDate = new TextBox();
    TextBox txt_EmployeeId = new TextBox();
    TextBox txt_ShiftIn = new TextBox();
    TextBox txt_ShiftOut = new TextBox();
    TextBox txt_Reason = new TextBox();
    DropDownList ddlInPunchTypes = new DropDownList();
    DropDownList ddlOutPunchTypes = new DropDownList();
    Label lbl_EntryDate = new Label();
    string gstrEmployeeIds = string.Empty, gstrUserGroupName = string.Empty, strStartDate, strEndDate, strStartTime, strEndTime, RowNumber;
    string strEmployeeIds = string.Empty, onDuty = string.Empty, strIn = string.Empty, strOut = string.Empty, TimeFormat = string.Empty;
    string gstrDOJValidation = string.Empty, gstrPermissionValidation = string.Empty, gstrShiftValidation = string.Empty;
    string strIsINPunchPresent = "N", strRowValue = "";
    int count, gintUserId, gintInsertCount = 0, manualEntryExists = 0, approvalSettingsPageExists = 0, intShiftId = 0, gintAlreadyInsertCount = 0;
    DateTime dtmIn = new DateTime();
    DateTime dtmOut = new DateTime();
    #endregion
    #region PageLoad
    protected override void Page_Load(object sender, EventArgs e)
    {
        base.Page_Load(sender, e);
        string source_Language = string.Empty;
        source_Language = Convert.ToString(Session["Session_ActiveLanguage"]);
        rm = new ResourceManager(source_Language, System.Reflection.Assembly.Load("App_GlobalResources"));
        ci = Thread.CurrentThread.CurrentCulture;
        if (!IsPostBack)
        {
            base.CheckPages(220);
            LoadStrings(ci);
            UserRights();
            objCommon.menu("ManualTransaction", "220");
            gvImportMaster.Styles.CssFilePath = Convert.ToString(Session["GridCSS"]);
        }

        site.SiteMapProvider = Convert.ToString(Session["SiteMapProvider"]);
        gintUserId = Int32.Parse(Session["EmpAutoID"].ToString());
        gstrUserGroupName = Convert.ToString(Session["UserGroupName"]);
        lbl_EntryDate.Text = DateTime.Now.ToString("dd-MMM-yyyy" + " HH:mm:ss tt");
        manualEntryExists = objCommon.CheckPageExistsInLicense(98);
        //Checking grade module is available or not and changed the id value from 110 to 228
        approvalSettingsPageExists = objCommon.CheckPageExistsInLicense(228);
    }
    #endregion
    #region Button Events
    protected void btnTemplate_Click(object sender, EventArgs e)
    {
        try
        {
            string strPath = Server.MapPath("Uploads/TC_ManualEntry_Import.xls");
            if (File.Exists(strPath))
            {
                byte[] data = System.IO.File.ReadAllBytes(strPath);
                Response.Clear();
                Response.AddHeader("Content-Type", "application/Excel");
                Response.AddHeader("Content-Disposition", "attachment;filename=TC_ManualEntry_Import.csv");
                Response.BinaryWrite(data);
                Response.End();
            }
            else
            {
                Message("Template file is not available in the source file");
                return;
            }
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }
    protected void btn_Upload_Click(object sender, EventArgs e)
    {
        try
        {
            if (fp_ManualEntryImport.HasFile)
            {
                string filename = fp_ManualEntryImport.FileName.Substring(fp_ManualEntryImport.FileName.LastIndexOf("\\") + 1);
                string fileType = System.IO.Path.GetExtension(filename);
                if (fileType == ".xls" || fileType == ".csv")
                {
                    string strFilePath = Server.MapPath("Uploads");
                    FileInfo fileInfo = new System.IO.FileInfo(strFilePath + "\\" + fp_ManualEntryImport.FileName);
                    fp_ManualEntryImport.SaveAs(strFilePath + "\\" + fp_ManualEntryImport.FileName);
                    if (fp_ManualEntryImport.PostedFile.ContentLength == fileInfo.Length)
                    {
                        int val = 0;
                        if (fileType == ".csv")
                        {
                            val = ManualEntryImportCSV(fileInfo);
                        }
                        if (val == 1)
                        {
                            if (gintInsertCount > 0 && gintAlreadyInsertCount == 0)
                            {
                                strScript = strScript + "<script language='javascript'>";
                                strScript = strScript + "alert('" + rm.GetString("Alert_FileUploadedandDataareimportedSucessfully", ci) + "');";
                                strScript = strScript + "location.replace('TA_UI_Transactions_ManualTimeEntry.aspx');";
                                strScript = strScript + "</script>";
                                Page.RegisterStartupScript("Alert", strScript);
                                if (aFile != null) aFile.Dispose();
                            }
                            else if (gintInsertCount > 0 && gintAlreadyInsertCount > 0)
                            {
                                string Message = rm.GetString("Alert_FileUploadedandDataareimportedSucessfully", ci) + "Except For Si.No - " + strRowValue + " " + rm.GetString("Msg_ManualEntryAddedAlready", ci);
                                strScript = strScript + "<script language='javascript'>";
                                strScript = strScript + "alert('" + Message + "');";
                                strScript = strScript + "location.replace('TA_UI_Transactions_ManualTimeEntry.aspx');";
                                strScript = strScript + "</script>";
                                Page.RegisterStartupScript("Alert", strScript);
                                if (aFile != null) aFile.Dispose();
                            }
                            else if (gintInsertCount == 0 && gintAlreadyInsertCount > 0)
                            {
                                string Message = " For Si.No - " + strRowValue + " " + rm.GetString("Msg_ManualEntryAddedAlready", ci);
                                strScript = strScript + "<script language='javascript'>";
                                strScript = strScript + "alert('" + rm.GetString("Alert_FileUploadedandDataareimportedSucessfully", ci) + "');";
                                strScript = strScript + "</script>";
                                Page.RegisterStartupScript("Alert", strScript);
                                if (aFile != null) aFile.Dispose();
                            }
                        }
                    }
                    else
                    {
                        strScript = strScript + "<script language='javascript'>";
                        strScript = strScript + "alert('" + rm.GetString("Alert_ErrorinImportingEmployee", ci) + "');";
                        strScript = strScript + "</script>";
                        Page.RegisterStartupScript("Alert", strScript);
                        if (aFile != null) aFile.Dispose();
                    }
                }
                else
                {
                    strScript = strScript + "<script language='javascript'>";
                    strScript = strScript + "alert('" + rm.GetString("Alert_TheUploadedfileisnotExcelfile", ci) + "');";
                    strScript = strScript + "</script>";
                    Page.RegisterStartupScript("Alert", strScript);
                    if (aFile != null) aFile.Dispose();
                }
            }
            else
            {
                strScript = strScript + "<script language='javascript'>";
                strScript = strScript + "alert('" + rm.GetString("Alert_Youhavenotspecifiedafile", ci) + "');";
                strScript = strScript + "</script>";
                Page.RegisterStartupScript("Alert", strScript);
            }
        }
        catch (Exception Ex)
        {
            string strErr = Convert.ToString(Ex.Message);
            strScript = strScript + "<script language='javascript' type='text/javascript'>";
            strScript = strScript + "alert('" + strErr.Replace("\r", "").Replace("\n", "") + "');";
            strScript = strScript + "</script>";
            Page.RegisterStartupScript("Alert", strScript);
            aFile.Dispose();
        }
        finally
        {
            try
            {
                if (fp_ManualEntryImport.HasFile)
                {
                    string StrFilePath = Convert.ToString(Server.MapPath("Uploads")) + "\\" + fp_ManualEntryImport.FileName;
                    System.IO.File.Delete(StrFilePath);
                }
            }
            catch (Exception Ex)
            {
            }
            if (aFile != null)
                aFile.Dispose();
        }
    }
    protected void btn_Cancel_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect("TA_UI_Transactions_ManualTimeEntryList.aspx");
        }
        catch (Exception Ex)
        {
            throw Ex;
        }
    }
    #endregion
    #region User Defined Functions
    private void LoadStrings(CultureInfo ci)
    {
        lbl_ImportEmployeeHeader.Text = rm.GetString("Transaction_ManualTimeEntryImport", ci);
        btn_Upload.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Upload", ci);
        lbl_ImportFilePath.Text = rm.GetString("SelectFileImport", ci);
        btnTemplate.Text = "&nbsp;&nbsp;" + rm.GetString("strDownloadTemplate", ci);
        btn_Cancel.Text = "&nbsp;&nbsp;" + rm.GetString("btn_Back", ci);
        lbl_IndicatesMandatoryFields.Text = rm.GetString("IndicatesMandatoryFields", ci);
        lblImportNote.Text = rm.GetString("lblChangepassImportant", ci);
        lblcon.Text = rm.GetString("ManualImport_Cont", ci);
    }
    public string Export(DataSet ds)
    {
        string columnnames = "", body = "", record = "";
        foreach (DataColumn col in ds.Tables[0].Columns)
        {
            columnnames = columnnames + " " + col.ColumnName + " " + ",";
        }
        columnnames = columnnames.Substring(0, columnnames.Length - 1);
        foreach (DataRow row in ds.Tables[0].Rows)
        {
            object[] arr = row.ItemArray;
            for (int i = 0; i <= arr.Length - 1; i++)
            {
                if (arr[i].ToString().IndexOf(",") > 0)
                {
                    record = record + " " + arr[i].ToString() + " " + ",";
                }
                else
                {
                    record = record + arr[i].ToString() + ",";
                }
            }
            body = body + record.Substring(0, record.Length - 1) + System.Environment.NewLine;
            record = "";
        }
        return (columnnames + System.Environment.NewLine + body);
    }
    public void FillEntranceDropDown()
    {
        string strEntranceId = string.Empty;
        DataSet ds_Entrance = new DataSet();
        ds_Entrance = objEntrance.SelectEntranceDetailsForManualTimeEntry();
        if (ds_Entrance.Tables[0].Rows.Count > 0)
        {
            strEntranceId = ds_Entrance.Tables[0].Rows[0]["Entrance_Id"].ToString();
            FillTerminals(strEntranceId);
        }
        ds_Entrance.Dispose();
    }
    public void FillTerminals(string strEntranceId)
    {
        DataSet dsInTerminals = new DataSet();
        dsInTerminals = objEntrance.SelectEntranceINOUTDetailsByIDview(Convert.ToInt32(strEntranceId), "In");
        dsInTerminals.Tables[0].TableName = "InTerminals";
        string strInTerminalId = string.Empty;
        if (dsInTerminals.Tables["InTerminals"].Rows.Count > 0)
        {
            strInTerminalId = dsInTerminals.Tables["InTerminals"].Rows[0]["Reader_Id"].ToString();
            FillInPunchTypes(strInTerminalId);
        }
        hdn_InTerminal.Value = strInTerminalId;
        dsInTerminals.Dispose();
        DataSet dsOutTerminals = new DataSet();
        dsOutTerminals = objEntrance.SelectEntranceINOUTDetailsByIDview(Convert.ToInt32(strEntranceId), "Out");
        dsOutTerminals.Tables[0].TableName = "OutTerminals";
        string strOutTerminalId = string.Empty;
        if (dsOutTerminals.Tables[0].Rows.Count > 0)
        {
            strOutTerminalId = dsOutTerminals.Tables["OutTerminals"].Rows[0]["Reader_Id"].ToString();
            FillOutPunchTypes(strOutTerminalId);
        }
        hdn_OutTerminal.Value = strOutTerminalId;
        dsOutTerminals.Dispose();
    }
    public string GetManualTimeEntryStatus(string inEmployeeCodeId)
    {
        DataSet dsReportingPersons = new DataSet();
        DataTable dtReportingPersons = new DataTable();
        string strManualTimeEntryStatus = string.Empty;
        Int64 intReportTo = 0, intLeave_Sanc_Authority = 0;
        dsReportingPersons = objEmployee.GetReportingToSanctionAuthorityByCodeID(inEmployeeCodeId);
        dtReportingPersons = dsReportingPersons.Tables[0];
        if (dtReportingPersons.Rows.Count > 0)
        {
            if (dtReportingPersons.Rows[0]["Reporting_To"] != DBNull.Value && dtReportingPersons.Rows[0]["Reporting_To"].ToString() != string.Empty)
            {
                intReportTo = Int64.Parse(dtReportingPersons.Rows[0]["Reporting_To"].ToString());
            }
            if (dtReportingPersons.Rows[0]["Leave_Sanc_Authority"] != DBNull.Value && dtReportingPersons.Rows[0]["Leave_Sanc_Authority"].ToString() != string.Empty)
            {
                intLeave_Sanc_Authority = Int64.Parse(dtReportingPersons.Rows[0]["Leave_Sanc_Authority"].ToString());
            }
        }
        if (intReportTo != 0 && intLeave_Sanc_Authority != 0 && intReportTo == intLeave_Sanc_Authority)
        {
            strManualTimeEntryStatus = "Forwarded";
        }
        else if (intReportTo == 0 && intLeave_Sanc_Authority != 0)
        {
            strManualTimeEntryStatus = "Forwarded";
        }
        else if (intReportTo != 0 && intLeave_Sanc_Authority == 0)
        {
            strManualTimeEntryStatus = "Forwarded";
        }
        else if (intReportTo == 0 && intLeave_Sanc_Authority == 0)
        {
            strManualTimeEntryStatus = "Forwarded";
        }
        else
        {
            strManualTimeEntryStatus = "Pending";
        }
        return (strManualTimeEntryStatus);
    }
    private void UserRights()
    {
        ds_Checkuser = objCheckUser.checkRights(220, Convert.ToInt32(Session["userGroup_Id"]), "addPrv");
        if (ds_Checkuser.Tables[0].Rows.Count == 0)
        {
            Response.Redirect("TransactionLandingPage.aspx");
        }
    }
    public void CheckInDate(object s, ServerValidateEventArgs e)
    {
        string strInDate = "";
        if (txt_InDate.Text != "")
        {
            gstrDateFormat = "dd-MMM-yyyy";
            strInDate = objCommon.DateConvertion(gstrDateFormat, txt_InDate.Text);
            DateTime dtCurrent = DateTime.Now;
            DateTime dtInDate = DateTime.Parse(strInDate);
            int Days = dtCurrent.CompareTo(dtInDate);
            if (Days > 0)
            {
                e.IsValid = true;
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Validator_ManualTimeEntry_InDate", ci) + "');", true);
                e.IsValid = false;
            }
        }
        else
        {
            e.IsValid = true;
        }
    }
    public void CheckOutDate(object s, ServerValidateEventArgs e)
    {
        string strOutDate = "";
        if (txt_OutDate.Text != "")
        {
            gstrDateFormat = "dd-MMM-yyyy";
            strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_OutDate.Text);
            DateTime dtCurrent = DateTime.Now;
            DateTime dtOutDate = DateTime.Parse(strOutDate);
            int Days = dtCurrent.CompareTo(dtOutDate);
            if (Days > 0)
            {
                e.IsValid = true;
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + rm.GetString("Validator_ManualTimeEntry_OutDate", ci) + "');", true);
                e.IsValid = false;
            }
        }
        else
        {
            e.IsValid = true;
        }
    }
    public void CheckTime(object s, ServerValidateEventArgs e)
    {
        if ((txt_ShiftIn.Text != "") && (txt_ShiftOut.Text != ""))
        {
            DateTime dtmInTime = DateTime.Parse(txt_ShiftIn.Text);
            DateTime dtmOutTime = DateTime.Parse(txt_ShiftOut.Text);
            int day = dtmOutTime.CompareTo(dtmInTime);
            if (day > 0)
                e.IsValid = true;
            else
                e.IsValid = false;
        }
    }
    private int ManualEntryImportCSV(FileInfo fileInfo)
    {
        FillEntranceDropDown();
        string strScript = string.Empty;
        string validationMsg = string.Empty;
        string strLine;
        string[] strArray;
        gstrDateFormat = "dd-MMM-yyyy";
        char[] charArray = new char[] { chrImportDelimiter = ',', ';' };
        DataSet ds = new DataSet();
        DataTable dt = ds.Tables.Add("TheData");
        aFile = new FileStream(fileInfo.FullName.ToString(), FileMode.Open);
        StreamReader sr = new StreamReader(aFile);
        strLine = sr.ReadLine();
        strArray = strLine.Split(charArray);
        int totalColumnCount = strArray.Length;
        string firstLevelColumnName = string.Empty;
        for (int x = 0; x <= strArray.GetUpperBound(0); x++)
        {
            dt.Columns.Add(strArray[x].Trim().Replace("\"", "").Replace("*", "").Replace(" ", "").Split('(')[0]);
        }
        strLine = sr.ReadLine();
        while (strLine != null)
        {
            strArray = strLine.Split(charArray);
            if (Session["MDateFormat"] != null)
                gstrDateFormat = "dd-MMM-yyyy";
            else
                gstrDateFormat = "dd/MM/yyyy";
            if (strArray.Length > totalColumnCount)
            {
                validationMsg = rm.GetString("Alert_Commashouldnotbeusedinanyofthedata", ci);
                strScript = "<script language='javascript' type='text/javascript'>alert('" + validationMsg + "');</script>";
                this.RegisterStartupScript("AlertErrorMsg", strScript);
                sr.Dispose();
                aFile.Dispose();
                return 0;
            }
            if (strArray.Length <= 1)
            {
                validationMsg = rm.GetString("ImportFiles_Separation", ci);
                strScript = "<script language='javascript' type='text/javascript'>alert('" + validationMsg + "');</script>";
                this.RegisterStartupScript("AlertErrorMsg", strScript);
                sr.Dispose();
                aFile.Dispose();
                return 0;
            }
            DataRow dr = dt.NewRow();
            for (int i = 0; i <= strArray.GetUpperBound(0); i++)
            {
                dr[i] = strArray[i].Trim().Replace("\"", "");
            }
            dt.Rows.Add(dr);
            strLine = sr.ReadLine();
        }
        sr.Dispose();
        aFile.Dispose();
        if (ds.Tables[0].Rows.Count == 0)
        {
            validationMsg = rm.GetString("Alert_ThereisnorecordintheImportfile", ci);
            strScript = "<script language='javascript' type='text/javascript'>alert('" + validationMsg + "');</script>";
            this.RegisterStartupScript("AlertErrorMsg", strScript);
            sr.Dispose();
            aFile.Dispose();
            return 0;
        }
        ds.Tables[0].DefaultView.RowFilter = "Employee_Id IS NULL OR Employee_Id = ''";
        if (ds.Tables[0].DefaultView.Count > 0)
        {
            validationMsg = rm.GetString("Alert_PleasefillEmployeeCodeforallemployees", ci);
        }
        ds.Tables[0].DefaultView.RowFilter = "Reason IS NULL OR Reason = ''";
        if (ds.Tables[0].DefaultView.Count > 0)
        {
            validationMsg = "Please fill Reason for all Manual Time Entries !";
        }
        if (validationMsg != string.Empty)
        {
            strScript = "<script language='javascript' type='text/javascript'>alert('" + validationMsg + "');</script>";
            this.RegisterStartupScript("AlertErrorMsg", strScript);
            sr.Dispose();
            aFile.Dispose();
            return 0;
        }
        DataTable dtErrorData = new DataTable();
        dtErrorData.Columns.Add("SlNO", typeof(Int64));
        dtErrorData.Columns.Add("ErrorMsg", typeof(string));
        DataRow dtErrorRow;
        string errorMessage = string.Empty;
        DateTime dtmFromDate = new DateTime();
        DateTime dtmToDate = new DateTime();
        DataSet ds_Year = new DataSet();
        ds_Year = objCommon.GetYearsetting();
        if (ds_Year != null)
        {
            if (ds_Year.Tables[0].Rows.Count > 0)
            {
                if (ds_Year.Tables[0].Rows[0]["FromDate"] != DBNull.Value)
                {
                    dtmFromDate = DateTime.Parse(ds_Year.Tables[0].Rows[0]["FromDate"].ToString());
                }
                if (ds_Year.Tables[0].Rows[0]["ToDate"] != DBNull.Value)
                {
                    dtmToDate = DateTime.Parse(ds_Year.Tables[0].Rows[0]["ToDate"].ToString());
                }
                ViewState["YearSettings_Id"] = ds_Year.Tables[0].Rows[0]["YearSettings_Id"].ToString();
            }
        }
        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            errorMessage = "";
            dtErrorRow = dtErrorData.NewRow();
            RowNumber = dr[0].ToString();
            txt_EmployeeId.Text = dr[1].ToString();
            txt_InDate.Text = Convert.ToString(dr[2]).Replace("'", "");
            txt_ShiftIn.Text = dr[3].ToString();
            hdn_InPunchType.Value = dr[4].ToString();
            txt_OutDate.Text = Convert.ToString(dr[5]).Replace("'", "");
            txt_ShiftOut.Text = dr[6].ToString();
            hdn_OutPunchType.Value = dr[7].ToString();
            txt_Reason.Text = dr[8].ToString();
            string EmployeeId = txt_EmployeeId.Text;
            if (EmployeeId == "")
            {
                errorMessage = errorMessage + rm.GetString("Msg_FillEmployee", ci);
            }
            if ((txt_InDate.Text == "") && (txt_ShiftIn.Text == "") && (txt_OutDate.Text == "") && (txt_ShiftOut.Text == ""))
            {
                errorMessage = rm.GetString("Msg_EitherInDateTime", ci) + "; ";
            }
            if ((txt_InDate.Text != "") && (txt_ShiftIn.Text == ""))
            {
                errorMessage = errorMessage + rm.GetString("Msg_InTimeEmpty", ci) + "; ";
            }
            if ((txt_InDate.Text == string.Empty) && (txt_ShiftIn.Text != string.Empty))
            {
                errorMessage = errorMessage + rm.GetString("Msg_InDate", ci) + "; ";
            }
            if ((txt_InDate.Text != "") && (txt_ShiftIn.Text != "") && (hdn_InPunchType.Value == "-Select-" || hdn_InPunchType.Value == ""))
            {
                errorMessage = errorMessage + "In Punch Type cannot be Empty" + "; ";
            }
            if ((txt_OutDate.Text != "") && (txt_ShiftOut.Text == ""))
            {
                errorMessage = errorMessage + rm.GetString("Msg_OutTimeEmpty", ci) + "; ";
            }
            if ((txt_OutDate.Text == "") && (txt_ShiftOut.Text != ""))
            {
                errorMessage = errorMessage + rm.GetString("Msg_OutDateEmpty", ci) + "; ";
            }
            if ((txt_OutDate.Text != "") && (txt_ShiftOut.Text != "") && (hdn_OutPunchType.Value == "-Select-" || hdn_OutPunchType.Value == ""))
            {
                errorMessage = errorMessage + "Out Punch Type cannot be Empty" + "; ";
            }
            string strInDate = "", strOutDate = "";
            try
            {
                strInDate = objCommon.DateConvertion(gstrDateFormat, txt_InDate.Text);
            }
            catch
            {
                errorMessage = errorMessage + "InDate - Invalid Date Format" + "; ";
            }
            try
            {
                strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_OutDate.Text);
            }
            catch (Exception Ex)
            {
                errorMessage = errorMessage + "OutDate  - Invalid Date Format" + "; ";
            }
            if (hdn_InPunchType.Value != null && hdn_InPunchType.Value != "")
            {
                if (ddlInPunchTypes.Items.FindByText(hdn_InPunchType.Value.ToString()) == null)
                {
                    errorMessage = errorMessage + "InPunch Type is Invalid " + "; ";
                }
            }
            if (hdn_OutPunchType.Value != null && hdn_OutPunchType.Value != "")
            {
                if (ddlOutPunchTypes.Items.FindByText(hdn_OutPunchType.Value.ToString()) == null)
                {
                    errorMessage = errorMessage + "OutPunch Type is Invalid" + "; ";
                }
            }
            DateTime dtmCurrentDateTime = DateTime.Parse(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString());
            if (strInDate != "")
            {
                if (txt_InDate.Text != string.Empty)
                {
                    DateTime dtmInDate = DateTime.Parse(strInDate);
                    if ((dtmFromDate <= dtmInDate) && (dtmInDate <= dtmToDate))
                    {
                    }
                    else
                    {
                        errorMessage = errorMessage + rm.GetString("Msg_ActiveYear", ci) + "; ";
                    }
                }

                if ((txt_InDate.Text != "") && (txt_ShiftIn.Text != ""))
                {
                    strIn = strInDate + " " + txt_ShiftIn.Text;
                    try
                    {
                        dtmIn = DateTime.Parse(strIn);
                    }
                    catch
                    {
                        errorMessage = errorMessage + "InTime - Invalid Time Format" + "; ";
                    }
                    if (dtmIn > dtmCurrentDateTime)
                    {
                        errorMessage = errorMessage + rm.GetString("Msg_InDategreater", ci) + "; ";
                    }
                }
            }
            if (strOutDate != "")
            {
                if (txt_OutDate.Text != "")
                {
                    DateTime dtmOutDate = DateTime.Parse(strOutDate);
                    if ((dtmFromDate <= dtmOutDate) && (dtmOutDate <= dtmToDate))
                    {
                    }
                    else
                    {
                        errorMessage = errorMessage + rm.GetString("Msg_OutdateSetting", ci) + "; ";
                    }
                }
                if ((txt_OutDate.Text != "") && (txt_ShiftOut.Text != ""))
                {
                    strOut = strOutDate + " " + txt_ShiftOut.Text;
                    try
                    {
                        dtmOut = DateTime.Parse(strOut);
                    }
                    catch
                    {
                        errorMessage = errorMessage + "OutTime - Invalid Time Format" + "; ";
                    }
                    if (dtmOut > dtmCurrentDateTime)
                    {
                        errorMessage = errorMessage + rm.GetString("Msg_OutDategreater", ci) + "; ";
                    }
                }
            }

            /* If all InDate, InTime, OutDate and OutTime are not NULL, then check whether difference between In DateTime and Out DateTime  
             should not exceed 24 Hours and also check whether In DateTime cannot be greater than Out DateTime   
             */
            if (dtmOut > dtmIn)
            {
                if ((txt_InDate.Text != "") && (txt_ShiftIn.Text != "") && (txt_OutDate.Text != "") && (txt_ShiftOut.Text != ""))
                {
                    TimeSpan tsDiff = dtmOut.Subtract(dtmIn);
                    double dTotalHrs = tsDiff.TotalHours;
                    if (dTotalHrs > 24)
                    {
                        errorMessage = errorMessage + rm.GetString("Msg_DiffBetInandOutTime", ci) + "; ";
                    }
                    else if (dTotalHrs < 0)
                    {
                        errorMessage = errorMessage + rm.GetString("Msg_InDatetimeGreater", ci) + "; ";
                    }
                }
            }
           
            DataSet dsEmpAutoId = new DataSet();
            dsEmpAutoId = objManualEntry.getEmployeeAutoIdForImport(txt_EmployeeId.Text);
            if (dsEmpAutoId.Tables[0].Rows.Count == 0)
            {
                errorMessage = errorMessage + "Unable to Upload.Employee ID - " + txt_EmployeeId.Text + " is not Active Status " + "; ";
            }
            else
            {
                int EmployeeAutoId = Convert.ToInt32(dsEmpAutoId.Tables[0].Rows[0]["Employee_Id"]);
            }
            string strDateOfJoining = string.Empty, strFlag = "Y";
            DataSet dsEmployeeDOJ = new DataSet();
            dsEmployeeDOJ = objEmployee.GetEmployeeDateOfJoining(txt_EmployeeId.Text, "", "", "S");
            if (dsEmployeeDOJ.Tables[0].Rows.Count > 0)
            {
                if (dsEmployeeDOJ.Tables[0].Rows[0]["DateOfJoining"] != DBNull.Value)
                {
                    strDateOfJoining = dsEmployeeDOJ.Tables[0].Rows[0]["DateOfJoining"].ToString();
                }
            }
            if (strDateOfJoining != string.Empty)
            {
                DateTime dtmDateOfJoining = DateTime.Parse(strDateOfJoining);
                if (strInDate != string.Empty)
                {
                    strIsINPunchPresent = "Y";
                    DateTime dtmInDate = DateTime.Parse(strInDate);
                    if (dtmInDate < dtmDateOfJoining)
                    {
                        errorMessage = errorMessage + rm.GetString("Msg_IndateGreaterThanEmpDOJ", ci) + "; ";
                    }
                    intShiftId = objShiftExchange.SelectShiftId(EmployeeId, dtmInDate.Year.ToString(), dtmInDate.Month.ToString(), dtmInDate.Day.ToString());
                    if (intShiftId == 0)
                    {
                        errorMessage = errorMessage + "For Si.No - " + RowNumber + " " + rm.GetString("Msg_ManualTimeEntry", ci) + "; ";
                    }
                }
                if (strOutDate != string.Empty)
                {
                    DateTime dtmOutDate = DateTime.Parse(strOutDate);
                    if (dtmOutDate < dtmDateOfJoining)
                    {
                        errorMessage = errorMessage + rm.GetString("Msg_OutdategreaterthanEmpDOJ", ci) + "; ";
                    }
                    if (strIsINPunchPresent == "N")
                    {
                        intShiftId = objShiftExchange.SelectShiftId(EmployeeId, dtmOutDate.Year.ToString(), dtmOutDate.Month.ToString(), dtmOutDate.Day.ToString());
                        if (intShiftId == 0)
                        {
                            errorMessage = errorMessage + "For Si.No - " + RowNumber + " " + rm.GetString("Msg_ManualTimeEntry", ci) + "; ";
                        }
                    }
                }
            }
            count = objManualEntry.CheckManualEntry(EmployeeId, strInDate, txt_ShiftIn.Text, strOutDate, txt_ShiftOut.Text);
            if (count == 1)
            {
                errorMessage = errorMessage + "For Si.No - " + RowNumber + " " + rm.GetString("Msg_ManualEntryAddedAlready", ci) + "; ";
            }
            if (errorMessage != "")
            {
                dtErrorRow["SlNO"] = RowNumber;
                dtErrorRow["ErrorMsg"] = errorMessage;
                dtErrorData.Rows.Add(dtErrorRow);
            }
        }
        if (dtErrorData.Rows.Count == 0)
        {
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                int intInReaderId = 0, intOutReaderId = 0, intRouteId = 0, intShiftId = 0;
                string strInDate = string.Empty, strOutDate = string.Empty, strManualTimeEntryStatus = string.Empty;
                RowNumber = dr[0].ToString();
                txt_EmployeeId.Text = dr[1].ToString();
                txt_InDate.Text = Convert.ToString(dr[2]).Replace("'", "");
                txt_ShiftIn.Text = dr[3].ToString();
                hdn_InPunchType.Value = dr[4].ToString();
                txt_OutDate.Text = Convert.ToString(dr[5]).Replace("'", "");
                txt_ShiftOut.Text = dr[6].ToString();
                hdn_OutPunchType.Value = dr[7].ToString();
                txt_Reason.Text = dr[8].ToString();
                string EmployeeId = txt_EmployeeId.Text;
                strInDate = objCommon.DateConvertion(gstrDateFormat, txt_InDate.Text);
                strOutDate = objCommon.DateConvertion(gstrDateFormat, txt_OutDate.Text);
                DataSet dsEmpAutoId = new DataSet();
                dsEmpAutoId = objManualEntry.getEmployeeAutoIdForImport(txt_EmployeeId.Text);
                int EmployeeAutoId = Convert.ToInt32(dsEmpAutoId.Tables[0].Rows[0]["Employee_Id"]);
                count = objManualEntry.CheckManualEntry(EmployeeId, strInDate, txt_ShiftIn.Text, strOutDate, txt_ShiftOut.Text);
                if (count == 0)
                {
                    string strInPunchType = hdn_InPunchType.Value;
                    string strOutPunchType = hdn_OutPunchType.Value;
                    if (hdn_InTerminal.Value != "")
                    {
                        intInReaderId = Convert.ToInt32(hdn_InTerminal.Value);
                    }
                    else
                    {
                        intInReaderId = 0;
                    }
                    if (hdn_OutTerminal.Value != "")
                    {
                        intOutReaderId = Convert.ToInt32(hdn_OutTerminal.Value);
                    }
                    else
                    {
                        intOutReaderId = 0;
                    }
                    string strEntryDate = objCommon.DateConvertion(gstrDateFormat, lbl_EntryDate.Text);
                    strManualTimeEntryStatus = GetManualTimeEntryStatus(EmployeeId);
                    if (txt_ShiftIn.Text != string.Empty)
                    {
                        txt_ShiftIn.Text = Convert.ToDateTime(txt_ShiftIn.Text).ToString("hh:mm:ss tt");
                    }
                    if (txt_ShiftOut.Text != string.Empty)
                    {
                        txt_ShiftOut.Text = Convert.ToDateTime(txt_ShiftOut.Text).ToString("hh:mm:ss tt");
                    }
                    if (manualEntryExists == 1)
                    {
                        if (approvalSettingsPageExists == 1)
                        {
                            int intCompanyId = base.GetCompanyId(EmployeeAutoId);
                            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]["ManualEntry"]) == false)
                                        {
                                            strManualTimeEntryStatus = "Approved";
                                        }
                                    }
                                    else
                                    {
                                        errorMessage = rm.GetString("Msg_ApprovalSettings", ci) + " for Si.No - " + RowNumber;
                                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", "alert('" + errorMessage + "');", true);
                                        return 0;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        strManualTimeEntryStatus = "Approved";
                    }
                    objManualEntry.InsertManualEntryImport(EmployeeId, DateTime.Parse(strEntryDate), strInDate, txt_ShiftIn.Text, strInPunchType, strOutDate, txt_ShiftOut.Text, strOutPunchType, intInReaderId, intOutReaderId, txt_Reason.Text.Trim().Replace("'", "''"), intRouteId, strManualTimeEntryStatus, DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss"), gintUserId, ViewState["YearSettings_Id"].ToString(), 0, 1);
                    gintInsertCount = gintInsertCount + 1;
                }
                else
                {
                    if (strRowValue == "")
                    {
                        strRowValue = RowNumber;
                    }
                    else
                    {
                        strRowValue = strRowValue + ',' + RowNumber;
                    }
                    gintAlreadyInsertCount = gintAlreadyInsertCount + 1;
                }
            }
        }
        else
        {
            btnDelete.Visible = true;
            Message("Found Some invalid data in Excel File, please correct it and then import");
            gvImportMaster.DataSource = dtErrorData;
            gvImportMaster.DataBind();
            gvImportMaster.Attributes.Add("display", "none");
            return 0;
        }
        return 1;
    }
    private void DisplayMessage(string Message)
    {
        string strScript = "<script language='javascript' type='text/javascript'>";
        strScript += "alert('" + Message + "');";
        strScript += " </script>";
        ScriptManager.RegisterStartupScript(this, this.GetType(), "Alert", strScript, false);
    }
    public void FillInPunchTypes(string strEntranceId)
    {
        DataSet dsInPunchTypes = new DataSet();
        dsInPunchTypes = objPunchTypes.Select_PunchTypeDetailsByTerminalId(Convert.ToInt32(strEntranceId), "I");
        if (dsInPunchTypes.Tables.Count > 0)
        {
            if (dsInPunchTypes.Tables[0].Rows.Count > 0)
            {
                ddlInPunchTypes.DataSource = dsInPunchTypes;
                ddlInPunchTypes.DataTextField = "PunchType";
                ddlInPunchTypes.DataValueField = "PunchType_Value";
                ddlInPunchTypes.DataBind();
            }
            dsInPunchTypes.Dispose();
        }
    }
    public void FillOutPunchTypes(string strEntranceId)
    {
        DataSet dsOutPunchTypes = new DataSet();
        dsOutPunchTypes = objPunchTypes.Select_PunchTypeDetailsByTerminalId(Convert.ToInt32(strEntranceId), "O");
        if (dsOutPunchTypes.Tables.Count > 0)
        {
            if (dsOutPunchTypes.Tables[0].Rows.Count > 0)
            {
                ddlOutPunchTypes.DataSource = dsOutPunchTypes;
                ddlOutPunchTypes.DataTextField = "PunchType";
                ddlOutPunchTypes.DataValueField = "PunchType_Value";
                ddlOutPunchTypes.DataBind();
            }
        }
        ddlOutPunchTypes.Dispose();
    }
    #endregion

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        gvImportMaster.DataSource = null;
        gvImportMaster.DataBind();
        btnDelete.Visible = false;
    }
}