using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ease.Core.Model;
using Ease.Core.Utility;
using HRM.BO;
using HRM.DA;
using HRM.Report.Attendence.AttendenceDataSet;
using Microsoft.Reporting.NETCore;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.Streaming.Values;
using Org.BouncyCastle.Ocsp;
using Org.BouncyCastle.Utilities.Collections;

namespace HRM.Report
{
    public class rptEcho
    {
        List<EmployeeBankAccount> _empBankAccs = null;
        List<ESBDefinition> _oGratuityParams = null;
        private DateTime _dSalaryMonth = DateTime.MinValue;
        private DateTime _dMonthEndDate = DateTime.MinValue;
        DateTime _fiscalyearStart;
        DateTime _SalaryMonth;
        string tempEmpID = string.Empty;
        private int TotalEmp = 0;
        int count = 1;
        public rptEcho()
        {

        }
        #region Payslip
        public byte[] ShowPaySlipEcho(int payrollTypeID, DateTime SalaryMonth, string sEmpID, bool isForESS)
        {
            DataSet oFDST = new DataSet();
            //_empBankAccs = new List<EmployeeBankAccount>();
            //_empBankAccs = new EmployeeBankAccountService().Get();
            //_oGratuityParams = new ESBDefinitionService().Get();
            Employee oEmployee = null;
            List<Employee> oEmps = new List<Employee>();
            oEmps = new EmployeeService().GetByEmpIDs(sEmpID, payrollTypeID);
            List<Designation> oDesigs = new DesignationService().Get(EnumStatus.Regardless, payrollTypeID);

            ReportProcessor reportProcessor = new ReportProcessor();
            DateTime salaryMonth = SalaryMonth.LastDateOfMonth();

            List<SalaryProcess> oSaProcess = new List<SalaryProcess>();
            oSaProcess = new SalaryProcessService().Get(salaryMonth, payrollTypeID);
            DataTable basicInfo = new HRM.Report.PayrollDataSet.PayrollDataSet.PayslipBasicInfoDataTable();
            if (isForESS)
            {
                foreach (SalaryProcess item in oSaProcess)
                {
                    if (!item.ShowInDesktops)
                    {
                        throw new Exception("Salary is not approved yet.");
                    }
                }
            }

            //bool bIsProcess = SalaryMonthly.IsSalaryProcessed(SessionManager.CurrentEmployee.ID, _SalaryMonth);

            DataSet oSalaryMonthlysGross = new SalaryMonthlyService().GetEmpPaySlipGrossForOthersNew(GlobalFunctions.LastDateOfMonth(salaryMonth), sEmpID);

            HRM.Report.PayrollDataSet.PayrollDataSet.PayslipDataTable PayslipData = new HRM.Report.PayrollDataSet.PayrollDataSet.PayslipDataTable();

            HRM.Report.PayrollDataSet.PayrollDataSet.LoanDataDataTable loanDT = new HRM.Report.PayrollDataSet.PayrollDataSet.LoanDataDataTable();
            //bool IsApproved = oSaProcess.GetBySMonth(GlobalFunctions.LastDateOfMonth(salaryMonth));

            _SalaryMonth = GlobalFunctions.LastDateOfMonth(salaryMonth);

            if (oSaProcess != null && oSaProcess.Count > 0 && oSalaryMonthlysGross.Tables[1].Rows.Count > 0)
            {
                if (oSaProcess[0].PaymentDate != DateTime.MinValue)
                {
                    _dMonthEndDate = Convert.ToDateTime(oSaProcess[0].PaymentDate);
                }
                else
                {
                    _dMonthEndDate = DateTime.MinValue;
                }
            }

            foreach (DataRow odRow in oSalaryMonthlysGross.Tables[1].Rows)
            {
                double dbl = Convert.ToDouble(odRow["CHANGEDAMOUNT"].ToString());
                if (dbl == 0)
                {
                    continue;
                }
                DataRow oRow = this.GetItem(PayslipData, Convert.ToString(odRow["EMPLOYEENO"]), (EnumSalaryGroup)Convert.ToInt32(odRow["ITEMGROUP"]), (EnumSalaryItemCode)Convert.ToInt32(odRow["ItemCode"]), Convert.ToInt32(odRow["ItemID"]));
                if (oRow == null)
                {
                    oRow = PayslipData.NewRow();
                    oRow = this.GrossMerge(oRow, odRow);
                    PayslipData.Rows.Add(oRow);
                }
                if (Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.Gross)
                {
                    oRow["Earning"] = odRow["CHANGEDAMOUNT"];
                }

                else if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.Arrear))
                {
                    double dArrear = Convert.ToDouble(odRow["CHANGEDAMOUNT"].ToString());
                    oRow["Arrear"] = dArrear;
                }
                else if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.UnauthLeave))
                {
                    oRow["unAuthLeave"] = odRow["CHANGEDAMOUNT"];
                }
            }

            int nCount = 0;
            DataSet oSalaryMonthlysDeduct = new SalaryMonthlyService().GetEmpPaySlipDeductForOthers(GlobalFunctions.LastDateOfMonth(salaryMonth), sEmpID);

            string employeeNo = "";
            DataRow[] odros = null;
            if (oSalaryMonthlysDeduct.Tables[0].Rows.Count > 0)
            {
                employeeNo = oSalaryMonthlysDeduct.Tables[0].Rows[0]["EMPLOYEENO"].ToString();
                odros = PayslipData.Select(" EmployeeNo='" + oSalaryMonthlysDeduct.Tables[0].Rows[0]["EMPLOYEENO"].ToString() + "'");
            }

            double dGratuityAmount = 0;
            double dPFAmount = 0;
            string sTEmpEmpNo = "";
            double nCurrPFAmount = 0;
            foreach (DataRow odRow in oSalaryMonthlysDeduct.Tables[0].Rows)
            {
                double dbl = Convert.ToDouble(odRow["CHANGEDAMOUNT"].ToString());
                if (dbl == 0)
                {
                    continue;
                }

                DataRow oRow = null;
                if (employeeNo != odRow["EMPLOYEENO"].ToString())
                {
                    odros = PayslipData.Select(" EmployeeNo='" + odRow["EMPLOYEENO"].ToString() + "'");
                    nCount = 0;
                }

                if (odros.Length <= nCount)
                {
                    oRow = PayslipData.NewRow();
                    oRow = this.GrossMerge(oRow, odRow);
                    PayslipData.Rows.Add(oRow);
                }
                else oRow = odros[nCount];

                oRow["DeducDescription"] = odRow["Description"];
                if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.Deductions))
                    oRow["DeducAmount"] = odRow["CHANGEDAMOUNT"];

                oRow["DeducDescription"] = odRow["Description"];

                //oEmployee = oEmps.Find(delegate(Employee oEmpItem) { return oEmpItem.EmployeeNo == odRow["EMPLOYEENO"].ToString().Trim(); });

                if (sTEmpEmpNo == "" || sTEmpEmpNo != odRow["EMPLOYEENO"].ToString())
                {
                    nCurrPFAmount = 0;
                    dPFAmount = 0;
                    oEmployee = oEmps.Find(delegate (Employee oEmpItem) { return oEmpItem.EmployeeNo == odRow["EMPLOYEENO"].ToString().Trim(); });

                    DataRow[] odrosPF = oSalaryMonthlysDeduct.Tables[0].Select(" ItemCode='" + (int)EnumSalaryItemCode.PF_Contribution + "' AND EMPLOYEENO='" + odRow["EMPLOYEENO"].ToString() + "'");
                    if (odrosPF.Length > 0)
                    {
                        DataRow oRowPF = odrosPF[0];
                        nCurrPFAmount = Convert.ToDouble(oRowPF["CHANGEDAMOUNT"]);
                    }

                    if (oEmployee != null)
                    {
                        //if (_oGratuityParams.Count > 0 && _oGratuityParams != null)
                        //{
                        //    dGratuityAmount = GetGratuityAmount(_oGratuityParams, oEmployee, salaryMonth);
                        //}
                        //else
                        //{
                        //    dGratuityAmount = 0;
                        //}
                        dPFAmount = GetPFAmount(oEmployee, salaryMonth);
                    }
                }

                oRow["Gratuity"] = dGratuityAmount;
                double nServiceLength = 0;
                if (oEmployee != null)
                    nServiceLength = ServiceYears(GlobalFunctions.LastDateOfMonth(salaryMonth), oEmployee);

                if (nServiceLength > 5)
                {
                    //oRow["PF"] = dPFAmount + nCurrPFAmount * 2;
                    oRow["PF"] = dPFAmount + nCurrPFAmount;
                }
                else
                {
                    oRow["PF"] = dPFAmount + nCurrPFAmount;
                }

                nCount = nCount + 1;
                employeeNo = odRow["EMPLOYEENO"].ToString();
                sTEmpEmpNo = odRow["EMPLOYEENO"].ToString();
            }

            nCount = 0;
            DataSet oSalaryMonthlysIncomeTax = new SalaryMonthlyService().GetEmpPaySlipIncomeTaxAmountForOthers(GlobalFunctions.LastDateOfMonth(salaryMonth), sEmpID);

            string employeeNo1 = "";
            DataRow[] odros1 = null;
            if (oSalaryMonthlysIncomeTax.Tables[0].Rows.Count > 0)
            {
                employeeNo1 = oSalaryMonthlysIncomeTax.Tables[0].Rows[0]["EMPLOYEENO"].ToString();
                odros1 = PayslipData.Select(" EmployeeNo='" + oSalaryMonthlysIncomeTax.Tables[0].Rows[0]["EMPLOYEENO"].ToString() + "'");
            }

            foreach (DataRow odRow in oSalaryMonthlysIncomeTax.Tables[0].Rows)
            {
                DataRow oRow = null;
                if (employeeNo1 != odRow["EMPLOYEENO"].ToString())
                {
                    odros1 = PayslipData.Select(" EmployeeNo='" + odRow["EMPLOYEENO"].ToString() + "'");
                    nCount = 0;
                }
                if (odros1.Length <= nCount) continue;
                oRow = odros1[nCount];

                if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.OtherItem) && (Convert.ToInt32(odRow["ItemCode"]) == (int)EnumSalaryItemCode.Inc_Tax_Deduction))
                    oRow["IncomTaxAmount"] = odRow["CHANGEDAMOUNT"];
                nCount = nCount + 1;
                employeeNo1 = odRow["EMPLOYEENO"].ToString();
            }

            nCount = 0;
            DataSet oSalaryMonthlysLaonAmount = new SalaryMonthlyService().GetEmpPaySlipDeductForLR(GlobalFunctions.LastDateOfMonth(salaryMonth), sEmpID);
            string employeeNo12 = "";
            DataRow[] odros12 = null;
            if (oSalaryMonthlysLaonAmount.Tables[0].Rows.Count > 0)
            {
                employeeNo12 = oSalaryMonthlysLaonAmount.Tables[0].Rows[0]["EMPLOYEENO"].ToString();
                odros12 = PayslipData.Select(" EmployeeNo='" + oSalaryMonthlysLaonAmount.Tables[0].Rows[0]["EMPLOYEENO"].ToString() + "'");
            }

            foreach (DataRow odRow in oSalaryMonthlysLaonAmount.Tables[0].Rows)
            {
                DataRow oRow = null;
                if (employeeNo12 != odRow["EMPLOYEENO"].ToString())
                {
                    odros12 = PayslipData.Select(" EmployeeNo='" + odRow["EMPLOYEENO"].ToString() + "'");
                    nCount = 0;
                }
                if (odros12.Length <= nCount) continue;
                oRow = odros12[nCount];
                if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.Miscellaneous) && (Convert.ToInt32(odRow["ItemCode"]) == (int)EnumSalaryItemCode.Loan_Remain_Balance))
                {
                    oRow["LoanDescription"] = odRow["Description"];
                    oRow["LoanAmount"] = odRow["CHANGEDAMOUNT"];
                }
                nCount = nCount + 1;
                employeeNo12 = odRow["EMPLOYEENO"].ToString();
            }

            bool isDesigFromEmp = false;// ConfigurationManager.GetBoolValue("designation", "desigfromdescriptiontext", EnumConfigurationType.Logic);

            foreach (DataRow oRow in PayslipData.Rows)
            {
                Employee oEmp = oEmps
                                .Where(o => o.EmployeeNo.ToUpper().Trim() == oRow["EMPLOYEENO"].ToString().ToUpper().Trim())
                                .SingleOrDefault();

                if (oEmp != null)
                {
                    if (isDesigFromEmp)
                    {
                        oRow["Designation"] = oEmp.DescriptionText;
                    }
                    else
                    {
                        Designation oDesg = oDesigs.Where(o => o.ID == oEmp.DesignationID).SingleOrDefault();
                        if (oDesg != null)
                        {
                            oRow["Designation"] = oDesg.Name;
                        }
                    }
                }
            }
            basicInfo = oSalaryMonthlysGross.Tables[0].Copy();

            basicInfo.TableName = "BasicInfo";
            DateTime joinDate = DateTime.MinValue;
            foreach (DataRow oRow in basicInfo.Rows)
            {
                joinDate = oRow["JoinIngDate"] == DBNull.Value ? DateTime.MinValue : Convert.ToDateTime(oRow["JoinIngDate"]);
                if (joinDate != DateTime.MinValue)
                    oRow["JOININGDATE"] = joinDate.ToString("dd MMM yyyy");
                if (oRow["PaymentMode"].ToString() == "1")
                {
                    oRow["PaymentMode"] = "CashPayment";
                    oRow["AccountNO"] = oRow["OutAccountNo"];
                    oRow["BName"] = oRow["OutBank"];
                }
                else if (oRow["PaymentMode"].ToString() == "2")
                {
                    oRow["PaymentMode"] = "BankTransfer";
                }
                else if (oRow["PaymentMode"] == "3")
                {
                    oRow["PaymentMode"] = "Provision";
                }
            }

            //DataSet dsSubReport = new DataSet();
            //PayslipData.TableName = "SalaryMonthlysGross";
            //dsSubReport.Tables.Add(PayslipData);
            //rlforPayslipdt.TableName = "RemainingLoanforPayslip";
            //dsSubReport.Tables.Add(rlforPayslipdt);

            loanDT.TableName = "RemainingLoanforPayslip";
            PayslipData.TableName = "SalaryMonthlysGross";
            oFDST.Tables.Add(PayslipData);
            oFDST.Tables.Add(loanDT);
            if (PayslipData != null && PayslipData.Rows.Count <= 0)
            {
                return null;
            }
            return reportProcessor.ShowDlgForNewPaySlip(null, basicInfo, oFDST, payrollTypeID);
        }
        private DataRow GetItem(PayrollDataSet.PayrollDataSet.PayslipDataTable Source, string sEmpNo, EnumSalaryGroup groupCode, EnumSalaryItemCode itemCode, int ITemID)
        {
            foreach (DataRow odRow in Source.Rows)
            {
                if (Convert.ToString(odRow["EMPLOYEENO"]) == sEmpNo &&
                    Convert.ToInt32(odRow["ItemCode"]) == (int)itemCode && Convert.ToInt32(odRow["ItemID"]) == ITemID)
                {
                    return odRow;
                }

            }
            return null;
        }
        private DataRow GrossMerge(DataRow destination, DataRow source)
        {
            if (Convert.ToInt32(source["ItemGroup"]) == 3)
            {
                destination["Name"] = source["Name"];
                destination["EMPLOYEENO"] = source["EMPLOYEENO"];
                destination["Grade"] = source["Grade"];
                destination["Designation"] = source["Designation"];
                destination["Department"] = source["Department"];
                destination["LName"] = source["LName"];
                destination["RC"] = source["RC"];
                destination["BName"] = source["BName"];
                destination["ActualBasic"] = source["ActualBasic"];
                if (source["PAYMENTMODE"].Equals(1))
                {
                    destination["PAYMENTMODE"] = "CashPayment";
                }
                else if (source["PAYMENTMODE"].Equals(2))
                {
                    destination["PAYMENTMODE"] = "BankTransfer";
                }
                else if (source["PAYMENTMODE"].Equals(3))
                {
                    destination["PAYMENTMODE"] = "Provision";
                }
                destination["ACCOUNTNO"] = source["ACCOUNTNO"];
                destination["SalaryMonth"] = Convert.ToDateTime(source["SalaryMonth"]).ToString("dd MMM yyyy");
                destination["Description"] = "";
                destination["ItemGroup"] = source["ITEMGROUP"];
                destination["ItemCode"] = source["ITEMCode"];
                destination["ItemID"] = source["ITEMID"];

                if (_SalaryMonth.Month >= 1 && _SalaryMonth.Month < 7)
                {
                    _fiscalyearStart = new DateTime(_SalaryMonth.Year - 1, 7, 1);
                    destination["TaxMonth"] = _fiscalyearStart.ToString("MMM yyyy");
                }
                else
                {
                    _fiscalyearStart = new DateTime(_SalaryMonth.Year, 7, 1);
                    destination["TaxMonth"] = _fiscalyearStart.ToString("MMM yyyy");
                }

                //destination["TaxMonth"] = Payroll.BO.SystemInformation.CurrentSysInfo.TaxYearEndDate.AddMonths(1);
                // destination["TaxFiscalYearAmount"] = GlobalFunctions.Round(item.GetAmountOnRange(oEmp, _dFiscalYear, _SalaryMonth.AddMinutes(1), EnumSalaryGroup.Deductions, EnumSalaryItemCode.Inc_Tax_Deduction, (int)EnumSalaryItemCode.Inc_Tax_Deduction)); 
                return destination;

            }
            else
            {
                destination["Name"] = source["Name"];
                destination["EMPLOYEENO"] = source["EMPLOYEENO"];
                destination["Grade"] = source["Grade"];
                destination["Designation"] = source["Designation"];
                destination["Department"] = source["Department"];
                destination["LName"] = source["LName"];
                //  destination["RC"] = source["RC"];
                destination["BName"] = source["BName"];
                destination["ActualBasic"] = source["ActualBasic"];
                if (source["PAYMENTMODE"].Equals(1))
                {
                    destination["PAYMENTMODE"] = "CashPayment";
                }
                else if (source["PAYMENTMODE"].Equals(2))
                {
                    destination["PAYMENTMODE"] = "BankTransfer";
                }
                else if (source["PAYMENTMODE"].Equals(3))
                {
                    destination["PAYMENTMODE"] = "Provision";
                }
                destination["ACCOUNTNO"] = source["ACCOUNTNO"];
                destination["SalaryMonth"] = Convert.ToDateTime(source["SalaryMonth"]).ToString("dd MMM yyyy");
                destination["Description"] = source["Description"];
                destination["ItemGroup"] = source["ITEMGROUP"];
                destination["ItemCode"] = source["ITEMCode"];
                destination["ItemID"] = source["ITEMID"];

                if (_SalaryMonth.Month >= 1 && _SalaryMonth.Month < 7)
                {
                    _fiscalyearStart = new DateTime(_SalaryMonth.Year - 1, 7, 1);
                    destination["TaxMonth"] = _fiscalyearStart.ToString("MMM yyyy");
                }
                else
                {
                    _fiscalyearStart = new DateTime(_SalaryMonth.Year, 7, 1);
                    destination["TaxMonth"] = _fiscalyearStart.ToString("MMM yyyy");
                }



                // destination["TaxFiscalYearAmount"] = GlobalFunctions.Round(item.GetAmountOnRange(oEmp, _dFiscalYear, _SalaryMonth.AddMinutes(1), EnumSalaryGroup.Deductions, EnumSalaryItemCode.Inc_Tax_Deduction, (int)EnumSalaryItemCode.Inc_Tax_Deduction)); 
                return destination;

            }
        }
        public double GetPFAmount(Employee oEmp, DateTime salaryMonth)
        {
            double nAmout = 0.0;

            DataSet ds = new PFTransactionService().GetPFBalance(oEmp.ID, GlobalFunctions.LastDateOfMonth(salaryMonth));

            double nServiceLength = ServiceYears(GlobalFunctions.LastDateOfMonth(salaryMonth), oEmp);

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                if (Convert.ToInt16(dr["TranTP"]) == 1)
                {
                    nAmout = Convert.ToDouble(dr["Amount"]);
                }
                //if (nServiceLength > 5)
                //{
                //    nAmout += Convert.ToDouble(dr["Amount"]);
                //}
                //else
                //{
                //    if (Convert.ToInt16(dr["TranTP"]) != 2)
                //    {
                //        nAmout += Convert.ToDouble(dr["Amount"]);
                //    }                    
                //}
            }
            return nAmout;
        }
        private double ServiceYears(DateTime dt, Employee oEmp)
        {
            double n = Global.DateFunctions.DateDiff("d", oEmp.JoiningDate, dt);
            if (n >= 365)
                return n / 365;
            else
                return 0.0;
        }
        //public void ShowReport(int payrollTypeId)
        //{
        //    DataSet oFDST = new DataSet();
        //    _oGratuityParams = new ESBDefinitionService().Get();
        //    Employee oEmployee = null;
        //    List<Employee> oEmps = new List<Employee>();
        //    oEmps = Employee.Get();
        //    List<Designation> oDesigs = new DesignationService().Get(EnumStatus.Regardless, payrollTypeId);

        //    ReportProcessor form = new ReportProcessor();
        //    _SalaryMonth = _selectedParameter.FromDate.Value.LastDateOfMonth();

        //    string sEmpID = _selectedParameter.ReportItem.INSQL;

        //    List<SalaryProcess> oSaProcess = new List<SalaryProcess>();
        //    oSaProcess = SalaryProcess.Get(_SalaryMonth);


        //    DataSet oSalaryMonthlysGross = SalaryMonthly.GetEmpPaySlipGrossForOthers(_SalaryMonth, sEmpID);

        //    PayrollDataSet.PayrollDataSet.PayslipDataTable PayslipData = new Payroll.Report.PayrollDataSet.PayrollDataSet.PayslipDataTable();

        //    PayrollDataSet.PayrollDataSet.LoanDataDataTable loanDT = new Payroll.Report.PayrollDataSet.PayrollDataSet.LoanDataDataTable();
        //    //bool IsApproved = oSaProcess.GetBySMonth(GlobalFunctions.LastDateOfMonth(salaryMonth));



        //    if (oSaProcess != null && oSaProcess.Count > 0 && oSalaryMonthlysGross.Tables[0].Rows.Count > 0)
        //    {
        //        if (oSaProcess[0].PaymentDate != DateTime.MinValue)
        //        {
        //            _dMonthEndDate = Convert.ToDateTime(oSaProcess[0].PaymentDate);
        //        }
        //        else
        //        {
        //            _dMonthEndDate = DateTime.MinValue;
        //        }
        //    }

        //    foreach (DataRow odRow in oSalaryMonthlysGross.Tables[0].Rows)
        //    {
        //        double dbl = Convert.ToDouble(odRow["CHANGEDAMOUNT"].ToString());
        //        if (dbl == 0)
        //        {
        //            continue;
        //        }
        //        DataRow oRow = this.GetItem(PayslipData, Convert.ToString(odRow["EMPLOYEENO"]), (EnumSalaryGroup)Convert.ToInt32(odRow["ITEMGROUP"]), (EnumSalaryItemCode)Convert.ToInt32(odRow["ItemCode"]), Convert.ToInt32(odRow["ItemID"]));
        //        if (oRow == null)
        //        {
        //            oRow = PayslipData.NewRow();
        //            oRow = this.GrossMerge(oRow, odRow);
        //            PayslipData.Rows.Add(oRow);
        //        }
        //        if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.Gross))
        //        {
        //            oRow["Earning"] = odRow["CHANGEDAMOUNT"];
        //        }

        //        else if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.Arrear))
        //        {
        //            double dArrear = Convert.ToDouble(odRow["CHANGEDAMOUNT"].ToString());
        //            oRow["Arrear"] = dArrear;
        //        }
        //        else if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.UnauthLeave))
        //        {
        //            oRow["unAuthLeave"] = odRow["CHANGEDAMOUNT"];
        //        }
        //    }

        //    int nCount = 0;
        //    DataSet oSalaryMonthlysDeduct = SalaryMonthly.GetEmpPaySlipDeductForOthers(_SalaryMonth, sEmpID);

        //    string employeeNo = "";
        //    DataRow[] odros = null;
        //    if (oSalaryMonthlysDeduct.Tables[0].Rows.Count > 0)
        //    {
        //        employeeNo = oSalaryMonthlysDeduct.Tables[0].Rows[0]["EMPLOYEENO"].ToString();
        //        odros = PayslipData.Select(" EmployeeNo='" + oSalaryMonthlysDeduct.Tables[0].Rows[0]["EMPLOYEENO"].ToString() + "'");
        //    }

        //    double dGratuityAmount = 0;
        //    double dPFAmount = 0;
        //    string sTEmpEmpNo = "";
        //    double nCurrPFAmount = 0;
        //    foreach (DataRow odRow in oSalaryMonthlysDeduct.Tables[0].Rows)
        //    {
        //        double dbl = Convert.ToDouble(odRow["CHANGEDAMOUNT"].ToString());
        //        if (dbl == 0)
        //        {
        //            continue;
        //        }

        //        DataRow oRow = null;
        //        if (employeeNo != odRow["EMPLOYEENO"].ToString())
        //        {
        //            odros = PayslipData.Select(" EmployeeNo='" + odRow["EMPLOYEENO"].ToString() + "'");
        //            nCount = 0;
        //        }

        //        if (odros.Length <= nCount)
        //        {
        //            oRow = PayslipData.NewRow();
        //            oRow = this.GrossMerge(oRow, odRow);
        //            PayslipData.Rows.Add(oRow);
        //        }
        //        else oRow = odros[nCount];

        //        oRow["DeducDescription"] = odRow["Description"];
        //        if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.Deductions))
        //            oRow["DeducAmount"] = odRow["CHANGEDAMOUNT"];

        //        oRow["DeducDescription"] = odRow["Description"];

        //        //oEmployee = oEmps.Find(delegate(Employee oEmpItem) { return oEmpItem.EmployeeNo == odRow["EMPLOYEENO"].ToString().Trim(); });

        //        if (sTEmpEmpNo == "" || sTEmpEmpNo != odRow["EMPLOYEENO"].ToString())
        //        {
        //            nCurrPFAmount = 0;
        //            dPFAmount = 0;
        //            oEmployee = oEmps.Find(delegate (Employee oEmpItem) { return oEmpItem.EmployeeNo == odRow["EMPLOYEENO"].ToString().Trim(); });

        //            DataRow[] odrosPF = oSalaryMonthlysDeduct.Tables[0].Select(" ItemCode='" + (int)EnumSalaryItemCode.PF_Contribution + "' AND EMPLOYEENO='" + odRow["EMPLOYEENO"].ToString() + "'");
        //            if (odrosPF.Length > 0)
        //            {
        //                DataRow oRowPF = odrosPF[0];
        //                nCurrPFAmount = Convert.ToDouble(oRowPF["CHANGEDAMOUNT"]);
        //            }

        //            if (oEmployee != null)
        //            {
        //                if (_oGratuityParams.Count > 0 && _oGratuityParams != null)
        //                {
        //                    dGratuityAmount = GetGratuityAmount(_oGratuityParams, oEmployee, _SalaryMonth);
        //                }
        //                else
        //                {
        //                    dGratuityAmount = 0;
        //                }
        //                dPFAmount = GetPFAmount(oEmployee, _SalaryMonth);
        //            }
        //        }

        //        oRow["Gratuity"] = dGratuityAmount;
        //        //double nServiceLength = 0;
        //        //if (oEmployee != null)
        //        //    nServiceLength = ServiceYears(_SalaryMonth, oEmployee);

        //        //if (nServiceLength > 5)
        //        //{
        //        //    //oRow["PF"] = dPFAmount + nCurrPFAmount * 2;
        //        //    oRow["PF"] = dPFAmount + nCurrPFAmount;
        //        //}
        //        //else
        //        //{
        //        //    oRow["PF"] = dPFAmount + nCurrPFAmount;
        //        //}

        //        oRow["PF"] = dPFAmount + nCurrPFAmount;
        //        nCount = nCount + 1;
        //        employeeNo = odRow["EMPLOYEENO"].ToString();
        //        sTEmpEmpNo = odRow["EMPLOYEENO"].ToString();
        //    }

        //    nCount = 0;
        //    DataSet oSalaryMonthlysIncomeTax = SalaryMonthly.GetEmpPaySlipIncomeTaxAmountForOthers(_SalaryMonth, sEmpID);

        //    string employeeNo1 = "";
        //    DataRow[] odros1 = null;
        //    if (oSalaryMonthlysIncomeTax.Tables[0].Rows.Count > 0)
        //    {
        //        employeeNo1 = oSalaryMonthlysIncomeTax.Tables[0].Rows[0]["EMPLOYEENO"].ToString();
        //        odros1 = PayslipData.Select(" EmployeeNo='" + oSalaryMonthlysIncomeTax.Tables[0].Rows[0]["EMPLOYEENO"].ToString() + "'");
        //    }

        //    foreach (DataRow odRow in oSalaryMonthlysIncomeTax.Tables[0].Rows)
        //    {
        //        DataRow oRow = null;
        //        if (employeeNo1 != odRow["EMPLOYEENO"].ToString())
        //        {
        //            odros1 = PayslipData.Select(" EmployeeNo='" + odRow["EMPLOYEENO"].ToString() + "'");
        //            nCount = 0;
        //        }
        //        if (odros1.Length <= nCount) continue;
        //        oRow = odros1[nCount];

        //        if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.OtherItem) && (Convert.ToInt32(odRow["ItemCode"]) == (int)EnumSalaryItemCode.Inc_Tax_Deduction))
        //            oRow["IncomTaxAmount"] = odRow["CHANGEDAMOUNT"];
        //        nCount = nCount + 1;
        //        employeeNo1 = odRow["EMPLOYEENO"].ToString();
        //    }

        //    nCount = 0;
        //    DataSet oSalaryMonthlysLaonAmount = SalaryMonthly.GetEmpPaySlipDeductForLR(_SalaryMonth, sEmpID);
        //    string employeeNo12 = "";
        //    DataRow[] odros12 = null;
        //    if (oSalaryMonthlysLaonAmount.Tables[0].Rows.Count > 0)
        //    {
        //        employeeNo12 = oSalaryMonthlysLaonAmount.Tables[0].Rows[0]["EMPLOYEENO"].ToString();
        //        odros12 = PayslipData.Select(" EmployeeNo='" + oSalaryMonthlysLaonAmount.Tables[0].Rows[0]["EMPLOYEENO"].ToString() + "'");
        //    }

        //    foreach (DataRow odRow in oSalaryMonthlysLaonAmount.Tables[0].Rows)
        //    {
        //        DataRow oRow = null;
        //        if (employeeNo12 != odRow["EMPLOYEENO"].ToString())
        //        {
        //            odros12 = PayslipData.Select(" EmployeeNo='" + odRow["EMPLOYEENO"].ToString() + "'");
        //            nCount = 0;
        //        }
        //        if (odros12.Length <= nCount) continue;
        //        oRow = odros12[nCount];
        //        if ((Convert.ToInt32(odRow["ITEMGROUP"]) == (int)EnumSalaryGroup.Miscellaneous) && (Convert.ToInt32(odRow["ItemCode"]) == (int)EnumSalaryItemCode.Loan_Remain_Balance))
        //        {
        //            oRow["LoanDescription"] = odRow["Description"];
        //            oRow["LoanAmount"] = odRow["CHANGEDAMOUNT"];
        //        }
        //        nCount = nCount + 1;
        //        employeeNo12 = odRow["EMPLOYEENO"].ToString();
        //    }

        //    bool isDesigFromEmp = ConfigurationManager.GetBoolValue("designation", "desigfromdescriptiontext", EnumConfigurationType.Logic);

        //    foreach (DataRow oRow in PayslipData.Rows)
        //    {
        //        Employee oEmp = oEmps
        //                        .Where(o => o.EmployeeNo.ToUpper().Trim() == oRow["EMPLOYEENO"].ToString().ToUpper().Trim())
        //                        .SingleOrDefault();

        //        if (oEmp != null)
        //        {
        //            if (isDesigFromEmp)
        //            {
        //                oRow["Designation"] = oEmp.DescriptionText;
        //            }
        //            else
        //            {
        //                Designation oDesg = oDesigs.Where(o => o.ID == oEmp.DesignationID).SingleOrDefault();
        //                if (oDesg != null)
        //                {
        //                    oRow["Designation"] = oDesg.Name;
        //                }
        //            }
        //        }
        //    }

        //    loanDT.TableName = "PayrollDataSet_LoanData";
        //    PayslipData.TableName = "PayrollDataSet_Payslip";
        //    oFDST.Tables.Add(PayslipData);
        //    oFDST.Tables.Add(loanDT);
        //    form.ShowDlgForPaySlipCiti1(_selectedParameter.ReportItem, oFDST);
        //}
        #endregion

        #region SalarySheetEchoTex
        public byte[] ShowSalarySheet(int payrollTypeId, DateTime salaryMonth, int reportId, string sEmpID, string reportType)
        {
            ReportProcessor form = new ReportProcessor();
            string RDLCName = "HRM.Report.RDLC.SalarySheetEchoTex.rdlc";
            string[] sEmp = sEmpID.Split(',');
            TotalEmp = sEmp.Length;
            DataTable dTSalarySheet = SalarySheetEchoTex(salaryMonth, sEmpID);
            dTSalarySheet.TableName = "PayrollDataSet_SalarySheet";

            PayrollDataSet.PayrollDataSet.SalarySheetDataTable _SalarySheet;
            DataSet resultDataSet = new DataSet();
            resultDataSet.Tables.Add(dTSalarySheet);
            _SalarySheet = new PayrollDataSet.PayrollDataSet.SalarySheetDataTable();

            List<ReportParameter> reportParameters = new List<ReportParameter>();
            ReportParameter rParam = new ReportParameter("PreparedBy", "");
            reportParameters.Add(rParam);

            rParam = new ReportParameter("CheckedBy", "");
            reportParameters.Add(rParam);

            rParam = new ReportParameter("HeadofHRApprovedBy", "");
            reportParameters.Add(rParam);

            rParam = new ReportParameter("CCOApprovedBy", "");
            reportParameters.Add(rParam);

            return form.CommonReportView(null, RDLCName, resultDataSet, null, reportParameters, true, payrollTypeId, reportType);
        }
        public DataTable SalarySheetEchoTex(DateTime dSalaryMonth, string sEmpID)
        {
            //fReportViewer form = new fReportViewer();
            //_SalaryMonth = dSalaryMonth;
            //ID nReportID = _selectedParameter.ReportItem.ReportID;
            //string sEmpID = _selectedParameter.ReportItem.INSQL;
            DataRow oDR = null;
            DataSet oSalarySheets = null;

            oSalarySheets = new EchoTexExceptionReportService().GetEmpSalarySheetEchoTex(GlobalFunctions.LastDateOfMonth(dSalaryMonth), sEmpID);
            PayrollDataSet.PayrollDataSet.SalarySheetDataTable dTSalarySheet = new PayrollDataSet.PayrollDataSet.SalarySheetDataTable();

            foreach (DataRow source in oSalarySheets.Tables["GrossItem"].Rows)
            {
                oDR = dTSalarySheet.NewRow();
                this.CopySalarySheetEchoTex(oDR, source);
                dTSalarySheet.Rows.Add(oDR);
            }

            foreach (DataRow source in oSalarySheets.Tables["TotalGross"].Rows)
            {
                oDR = dTSalarySheet.NewRow();
                this.CopySalarySheetEchoTex(oDR, source);
                dTSalarySheet.Rows.Add(oDR);
            }

            foreach (DataRow source in oSalarySheets.Tables["AttendenceDays"].Rows)
            {
                oDR = dTSalarySheet.NewRow();
                this.CopySalarySheetEchoTex(oDR, source);
                dTSalarySheet.Rows.Add(oDR);
            }

            foreach (DataRow source in oSalarySheets.Tables["DeductItem"].Rows)
            {
                //if (Convert.ToInt16(source["ItemCode"]) == (int)EnumSalaryItemCode.Loan_Monthly_Interest)
                //{
                //    continue;
                //}
                //else
                //{
                oDR = dTSalarySheet.NewRow();
                this.CopyDeductSalarySheetEchoTex(oDR, source, oSalarySheets.Tables["DeductItem"]);
                dTSalarySheet.Rows.Add(oDR);
                //}
            }

            foreach (DataRow source in oSalarySheets.Tables["TotalDeduction"].Rows)
            {
                oDR = dTSalarySheet.NewRow();
                this.CopySalarySheetEchoTex(oDR, source);
                dTSalarySheet.Rows.Add(oDR);
            }

            foreach (DataRow source in oSalarySheets.Tables["NetPay"].Rows)
            {
                oDR = dTSalarySheet.NewRow();
                this.CopySalarySheetEchoTex(oDR, source);
                dTSalarySheet.Rows.Add(oDR);
            }

            foreach (DataRow source in oSalarySheets.Tables["CPF"].Rows)
            {
                oDR = dTSalarySheet.NewRow();
                this.CopySalarySheetEchoTex(oDR, source);
                dTSalarySheet.Rows.Add(oDR);
            }


            foreach (DataRow source in oSalarySheets.Tables["LeaveDays"].Rows)
            {
                oDR = dTSalarySheet.NewRow();
                this.CopySalarySheetEchoTex(oDR, source);
                dTSalarySheet.Rows.Add(oDR);
            }

            return dTSalarySheet;
            //form.ShowDlgForSalarySheet(_selectedParameter.ReportItem, dTSalarySheet, nReportID);
        }
        private void CopySalarySheetEchoTex(DataRow source, DataRow destination)
        {
            if (tempEmpID == string.Empty)
            {
                tempEmpID = Convert.ToString(destination["EMPLOYEENO"]);
                source["SLNo"] = count;
                count++;
            }
            if (tempEmpID != Convert.ToString(destination["EMPLOYEENO"]))
            {
                tempEmpID = Convert.ToString(destination["EMPLOYEENO"]);
                source["SLNo"] = count;
                count++;
            }
            source["EmpNo"] = destination["EMPLOYEENO"];
            source["EmpName"] = destination["Name"];
            source["Grade"] = destination["GName"];
            source["Department"] = destination["DName"];
            source["Description"] = destination["Description"];
            source["Amount"] = destination["Amount"];
            source["SalaryMonth"] = _SalaryMonth;
            source["JoiningDate"] = destination["JoiningDate"];
            //source["SLNo"] = destination["EMPLOYEEID"]; 
        }
        private void CopyDeductSalarySheetEchoTex(DataRow source, DataRow destination, DataTable oDt)
        {
            if (tempEmpID == string.Empty)
            {
                tempEmpID = Convert.ToString(destination["EMPLOYEENO"]);
                source["SLNo"] = count;
                count++;
            }
            if (tempEmpID != Convert.ToString(destination["EMPLOYEENO"]))
            {
                tempEmpID = Convert.ToString(destination["EMPLOYEENO"]);
                source["SLNo"] = count;
                count++;
            }
            //if (Convert.ToInt16(destination["ItemCode"]) == (int)EnumSalaryItemCode.Loan_Monthly_Installment)
            //{
            //    DataRow[] odrosAmount = oDt.Select(" ItemCode='" + (int)EnumSalaryItemCode.Loan_Monthly_Interest + "' AND EMPLOYEENO='" + destination["EMPLOYEENO"].ToString() + "'" + " AND ItemID='" + Convert.ToInt16(destination["ItemID"]) + "'");
            //    source["EmpNo"] = destination["EMPLOYEENO"];
            //    source["Grade"] = destination["GName"];
            //    source["EmpName"] = destination["Name"];
            //    source["Grade"] = destination["GName"];
            //    source["Department"] = destination["DName"];
            //    source["Description"] = destination["Description"];

            //    if (odrosAmount.Length > 0)
            //    {
            //        nCurrLoanInterstAmount = 0;
            //        DataRow oRowLoanInterest = odrosAmount[0];
            //        nCurrLoanInterstAmount = Convert.ToDouble(oRowLoanInterest["Amount"]);
            //    }

            //    source["Amount"] = Convert.ToDouble(destination["Amount"]) + nCurrLoanInterstAmount;
            //    source["SalaryMonth"] = _SalaryMonth;
            //    source["JoiningDate"] = destination["JoiningDate"];
            //}
            //else
            //{
            source["EmpNo"] = destination["EMPLOYEENO"];
            source["Grade"] = destination["GName"];
            source["EmpName"] = destination["Name"];
            source["Grade"] = destination["GName"];
            source["Department"] = destination["DName"];
            source["Description"] = destination["Description"];
            source["Amount"] = destination["Amount"];
            source["SalaryMonth"] = _SalaryMonth;
            source["JoiningDate"] = destination["JoiningDate"];
            //source["SLNo"] = destination["EMPLOYEEID"]; 
            //}
        }

        #endregion

        #region BankAdvice
        public byte[] ShowBankAdviceReportEcho(int payrollTypeId, DateTime SalaryMonth, string sEmpID, int BankId, string reportType)
        {

            DateTime salaryMonth = SalaryMonth.LastDateOfMonth();
            int count = 1;
            DataRow oDR = null;
            Bank oBank = new BankService().Get(BankId);



            DataSet oEmpBankAcc = new EchoTexExceptionReportService().GetEmpBankAdvice(GlobalFunctions.LastDateOfMonth(salaryMonth), sEmpID);

            PayrollDataSet.dsCompany.BankAdviceDataTable bankAdvice = new PayrollDataSet.dsCompany.BankAdviceDataTable();

            double nTotal = 0.0;
            foreach (DataRow oDRow in oEmpBankAcc.Tables[0].Rows)
            {
                //oDR = bankAdvice.NewRow();
                //oDR["EmpNo"] = oDRow["EMPLOYEENO"];
                //oDR["EmpName"] = oDRow["NAME"];                                                     //Beneficiary Name(120)
                //oDR["AccountNo"] = oDRow["ACCOUNTNO"];                                              //Beneficiary Account Number
                //oDR["Amount"] = Math.Round(Convert.ToDouble(oDRow["CHANGEDAMOUNT"]));               //Payment Amount
                //oDR["SalaryMonth"] = salaryMonth;                                                   //Reason(140)
                //oDR["PaymentDate"] = oDRow["PAYMENTDATE"];                                          //Payment Date(DD/MM/YYYY)
                //oDR["Email"] = oDRow["EMAILADDRESS"];                                               //Beneficiary Email ID(Optional)
                //oDR["SLNo"] = count;

                ////if(oDRow["EMAILADDRESS"] != null)
                ////{
                ////    oDR["Email"] = oDRow["EMAILADDRESS"];
                ////}
                ////oDR["CostCenter"] = oDRow["CostCenter"].ToString();
                //bankAdvice.Rows.Add(oDR);
                //nTotal += Convert.ToDouble(oDR["Amount"]);
                //count++;
                oDR = bankAdvice.NewRow();
                oDR["EmpNo"] = oDRow["EMPLOYEENO"];
                oDR["EmpName"] = oDRow["NAME"];
                oDR["AccountNo"] = oDRow["ACCOUNTNO"];
                oDR["Amount"] = Math.Round(Convert.ToDouble(oDRow["CHANGEDAMOUNT"]));
                oDR["Email"] = oDRow["EMAILADDRESS"];
                oDR["SalaryMonth"] = salaryMonth;
                oDR["SLNo"] = count;
                //oDR["CostCenter"] = oDRow["CostCenter"].ToString();
                bankAdvice.Rows.Add(oDR);
                nTotal += Convert.ToDouble(oDR["Amount"]);
                count++;
            }

            // bankAdvice.TableName = "dsCompany_BankAdvice";
            // resultDataSet.Tables.Add(bankAdvice);

            //string RDLCName = "HRM.Report.RDLC.SalaryBankDisbursement.rdlc";
            ReportProcessor reportProcessor = new ReportProcessor();
            string rdlcName = "BankAdvice.rdlc";

            return reportProcessor.ShowDlgForNewBankDisbursment(null, bankAdvice, reportType, payrollTypeId, rdlcName, SalaryMonth);
            //return reportProcessor.CommonReportView(null, RDLCName, resultDataSet, null, null, true, payrollTypeId, reportType);
        }
        #endregion

        #region EchotexSalarySheetnew

        public byte[] ShowSalarySheetEchoNew(int payrollTypeId, DateTime salaryMonth, int reportId, string sEmpID, string reportType)
        {
            ReportProcessor reportProcessor = new ReportProcessor();
            string RDLCName = (salaryMonth.LastDateOfMonth() == new DateTime(2020, 5, 31)) ?
                          "HRM.Report.RDLC.StaticSalarySheetModifyMay2020.rdlc" :
                          "HRM.Report.RDLC.StaticSalarySheetModify.rdlc";
            SystemInformation systemInfo = new SystemInformationService().Get();

            string[] sEmp = sEmpID.Split(',');
            TotalEmp = sEmp.Length;
            //DataTable dTSalarySheet = SalarySheetEchoTex(salaryMonth, sEmpID);
            DataTable dTSalarySheet = ShowReportSalarySheetStaticModify(salaryMonth, sEmpID, payrollTypeId);
            dTSalarySheet.TableName = "PayrollDataSet_SalarySheetStatic";

            PayrollDataSet.PayrollDataSet.SalarySheetDataTable _SalarySheet;
            DataSet resultDataSet = new DataSet();
            resultDataSet.Tables.Add(dTSalarySheet);
            _SalarySheet = new PayrollDataSet.PayrollDataSet.SalarySheetDataTable();

            List<ReportParameter> reportParameters = new List<ReportParameter>();

            ReportParameter rParam = new ReportParameter("SalaryMonth", salaryMonth.ToString("MMM yyyy"));
            reportParameters.Add(rParam);

            rParam = new ReportParameter("SalaryDate", salaryMonth.ToString("dd MMM yyyy"));
            reportParameters.Add(rParam);

            rParam = new ReportParameter("Fax", string.Empty);
            reportParameters.Add(rParam);

            rParam = new ReportParameter("Email", systemInfo.email);
            reportParameters.Add(rParam);

            //rParam = new ReportParameter("HeadofHRApprovedBy", "");
            //reportParameters.Add(rParam);

            //rParam = new ReportParameter("CCOApprovedBy", "");
            //reportParameters.Add(rParam);

            return reportProcessor.CommonReportView(null, RDLCName, resultDataSet, null, reportParameters, true, payrollTypeId, reportType);
        }
        public DataTable ShowReportSalarySheetStaticModify(DateTime dSalaryMonth, string sEmpID, int payrollTypeId)
        {
            int roundofdegit = Convert.ToInt32(new SystemConfigarationService().GetconfigValue(EnumConfigurationType.Logic, "root", "roundofdegit"));

            PayrollType payrollType = new PayrollTypeService().Get(payrollTypeId);
            TermParameter termParameter = new TermParameter();
            _SalaryMonth = dSalaryMonth;
            //int nReportID = reportId;
            //string sEmpID = _selectedParameter.ReportItem.INSQL;
            EnumBankCash? eBnkCash = EnumBankCash.All;
            double fractionamount = 0.0;
            DataSet oSalarySheets = new DataSet();
            double basicEarned, houserentEarned, conveyanceEarned, medicalEarned, foodEarned, grossEarned;
            double totalDaysInMonth = _SalaryMonth.TotalDaysInMonth();
            double totalDays;
            List<SalaryMonthly> oSalaryMonthlys = new List<SalaryMonthly>();
            if (eBnkCash != null && eBnkCash.Value != EnumBankCash.All)
            {
                oSalaryMonthlys = eBnkCash.Value == EnumBankCash.Bank ? new SalaryMonthlyService().Get(sEmpID, _SalaryMonth.LastDateOfMonth(), payrollTypeId)
                                                                                     .Where(x => !x.AccountNo.IsNullOrWhiteSpace())
                                                                                     .ToList()
                                                                      : new SalaryMonthlyService().Get(sEmpID, _SalaryMonth.LastDateOfMonth(), payrollTypeId)
                                                                                     .Where(x => x.AccountNo.IsNullOrWhiteSpace())
                                                                                     .ToList();

                sEmpID = oSalaryMonthlys.Aggregate(new StringBuilder(), (sb, sm) => sb.AppendFormat("{0},", sm.EmployeeID), sb => sb.ToString().Trim(','));
            }
            else
            {
                oSalaryMonthlys = new SalaryMonthlyService().Get(sEmpID, _SalaryMonth.LastDateOfMonth(), payrollTypeId);
            }

            //if (sEmpID.IsNullOrWhiteSpace())
            //{
            //    MessageBox.Show("No Employee Found");
            //    return;
            //}

            //DateTime dSalaryDate = (new fDateSelection()).ShowDlg("Salary Date");

            DataTable dTblEmps = new EmployeeService().GetAllEmpBasicInfo(sEmpID).Tables[0];
            DataTable dTblCC = new EmployeeService().GetCostCenterInfo(sEmpID);
            List<Designation> oDesignations = new DesignationService().Get(EnumStatus.Regardless, payrollTypeId);
            //List<Grade> oGrades = new GradeService().Get(EnumStatus.Regardless);
            List<Grade> oGrades = new GradeService().GetAllPayrollTypes(EnumStatus.Regardless);
            List<Department> oDepartments = new DepartmentService().Get(EnumStatus.Regardless, payrollTypeId);
            List<Leave> oLeaves = new LeaveService().Get();
            List<AllowanceDeduction> oAllDeducts = new AllowanceDeductionService().Get(EnumStatus.Regardless);
            //List<ADParameter> oAllADParameters = new ADParameterService().Get(EnumStatus.Active);
            List<ADParameter> oAllADParameters = new ADParameterService().GetWithPayrollType(EnumStatus.Active, payrollTypeId);
            foreach(ADParameter item in oAllADParameters)
            {
                if (item.ADParameterGrades == null)
                    item.ADParameterGrades = new ADParameterService().GetGrades(item.ID);
            }
            
            oAllADParameters.ForEach(x => x.ADParameterGrades = x.ADParameterGrades);
            //List<TermParameter> oAllTermParameters = new TermParameterService().Get(true);
            List<TermParameter> oAllTermParameters = new TermParameterService().Get(true, payrollTypeId);
            SalaryCalculator salaryCalculator = new SalaryCalculator();
            //salaryCalculator.SalaryMonthlies = null;
            //salaryCalculator.SalaryMonthlies(oSalaryMonthlys);
            //salaryCalculator.SalaryMonthlies.Add(oSalaryMonthlys);
            List<SalaryMonthly> salMon = new List<SalaryMonthly>();
            foreach (SalaryMonthly item in oSalaryMonthlys)
            {
                //salaryCalculator.SalaryMonthlies.Add(item);
                salMon.Add(item);
            }
            
            Func<int, double> invertedGrossRatio = (empID) => salaryCalculator.CalculateInvertedGrossFraction(_SalaryMonth.LastDateOfMonth(), empID);
            PayrollDataSet.PayrollDataSet.SalarySheetStaticDataTable dTable = new PayrollDataSet.PayrollDataSet.SalarySheetStaticDataTable();

            foreach (SalaryMonthly itemMonthly in oSalaryMonthlys)
            {
                SalaryMonthlyService itemMonthlyService = new SalaryMonthlyService();

                grossEarned = basicEarned = basicEarned = houserentEarned = conveyanceEarned = medicalEarned = foodEarned = totalDays = 0;
                //Employee oEmp = oEmployees.FirstOrDefault(x => x.ID == itemMonthly.EmployeeID);
                DataRow drEmp = dTblEmps.AsEnumerable().FirstOrDefault(x => itemMonthly.EmployeeID == x.Field<int>("EmployeeID"));
                DataRow drCC = dTblCC.AsEnumerable().FirstOrDefault(x => itemMonthly.EmployeeID == x.Field<int>("EmployeeID"));
                TermParameter oEmpTermParameter = null;
                if (drEmp == null) continue;
                if (drEmp["GradeID"] != DBNull.Value && !string.IsNullOrWhiteSpace(drEmp["GradeID"].ToString()))
                {
                    oEmpTermParameter = oAllTermParameters.FirstOrDefault(x => x.SetupDetails.Any(y => y.TranID == drEmp.Field<int>("GradeID")));
                }
                DataRow dr = dTable.NewRow();

                #region Employee General Information

                dr["Name"] = drEmp["Name"].ToString();
                DateTime joiningDate = Convert.ToDateTime(drEmp["JoiningDate"].ToString());
                dr["JoiningDate"] = joiningDate.ToString("dd MMM yyyy");
                //dr["Remarks"] = joiningDate.Date < Payroll.BO.SystemInformation.CurrentSysInfo.NextPayProcessDate.FirstDateOfMonth() ? "" : " (New) ";
                dr["Remarks"] = joiningDate.Date < payrollType.NextPayProcessDate.FirstDateOfMonth() ? "" : " (New) ";
                dr["EmpNo"] = drEmp["EmployeeNo"].ToString();
                dr["ACCNO"] = drEmp["ACCOUNTNO"].ToString();
                dr["Designation"] = drEmp["Designation"].ToString();
                dr["Department"] = drEmp["Department"].ToString();
                dr["FLOOR"] = drEmp["Floor"].ToString();
                dr["Line"] = drEmp["Line"].ToString();
                dr["Section"] = drEmp["Section"].ToString();
                dr["TINNO"] = dTblEmps.Columns.Contains("TINNO") ? drEmp["TINNO"].ToString() : "";
                dr["Grade"] = drEmp["GradeName"].ToString();
                dr["GroosSalary"] = Convert.ToDouble(drEmp["GROSSSALARY"].ToString());
                dr["CostCenter"] = drCC == null ? string.Empty : drCC["CostCenter"].ToString();
                dr["CostCenterCode"] = drCC == null ? string.Empty : drCC["CostCenterCode"].ToString();

                #endregion

                #region Days Calcullation

                totalDays = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Total_Days, itemMonthly);
                fractionamount = totalDays == 0 ? 0.0 : (double)totalDaysInMonth / totalDays;
                dr["TotalDays"] = totalDays;
                dr["WorkingDays"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Tot_Attend_Days, itemMonthly);
                dr["Holiday"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Total_HoliDays, itemMonthly);
                dr["Absent"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Tot_UnauthLeave_Days, itemMonthly);

                // test
                //fractionamount = 1;

                #endregion

                #region Gross Payment

                basicEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Basic_Salary, itemMonthly)
                              + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Basic_Salary, itemMonthly);
                dr["Basic"] = Math.Round(fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Basic_Salary, itemMonthly))
                    + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Basic_Salary, itemMonthly));


                // House rent code: 008
                dr["HouseRent"] = 0;
                AllowanceDeduction oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Allowance && x.Code.Trim() == "008");
                if (oAllDeduct != null)
                {
                    houserentEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                              + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                    //double y = (double)invertedGrossRatio(itemMonthly.EmployeeID) *( new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)) + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    //double x = (double)(fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID))) + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    //double z = Math.Round(x);

                    dr["HouseRent"] = Math.Round(fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)) + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID), 0);

                }

                // medical code: 011
                dr["Medical"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Allowance && x.Code.Trim() == "011");
                if (oAllDeduct != null)
                {
                    medicalEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                 + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                    dr["Medical"] = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)) + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                }

                // Conveyance code: 010
                dr["Conveyance"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Allowance && x.Code.Trim() == "010");
                if (oAllDeduct != null)
                {
                    conveyanceEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                     + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    dr["Conveyance"] = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)) + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                }

                // FoodAllowance code: 006
                dr["FoodAllowance"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Allowance && x.Code.Trim() == "006");
                if (oAllDeduct != null)
                {
                    foodEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                  + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                    dr["FoodAllowance"] = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)) + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                }

                grossEarned = basicEarned +
                              houserentEarned +
                              medicalEarned +
                              conveyanceEarned +
                              foodEarned;

                dr["GrossSalaryOriginal"] = Convert.ToDouble(dr["Basic"]) +
                                            Convert.ToDouble(dr["HouseRent"]) +
                                            Convert.ToDouble(dr["Medical"]) +
                                            Convert.ToDouble(dr["Conveyance"]) +
                                            Convert.ToDouble(dr["FoodAllowance"]);

                #endregion

                #region Deductions

                //double shopAdvance = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Loan_Monthly_Installment, itemMonthly, "Shop Advance");
                double shopAdvance = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Loan_Monthly_Installment, itemMonthly, "Shop Advance Principle");
                dr["ShopAdvance"] = Math.Round(shopAdvance, 0);

                double DeductSalaryAdvance = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Loan_Monthly_Installment, itemMonthly) - shopAdvance;
                dr["DeductSalaryAdvance"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Loan_Monthly_Installment, itemMonthly) - shopAdvance;
                dr["DeductBasic"] = Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.UnauthLeave, EnumSalaryItemCode.Basic_Salary, itemMonthly), 0);
                dr["PF"] = Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.PF_Contribution, itemMonthly), 0);
                dr["TDS"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Inc_Tax_Deduction, itemMonthly);

                dr["DeductPF"] = Math.Round(Convert.ToDouble(dr["PF"]), 0);

                // Deduct Conduct Bonus code: 005
                dr["ConductBonusDeduct"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Deduction && x.Code.Trim() == "005");
                if (oAllDeduct != null)
                {

                    dr["ConductBonusDeduct"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Deduction, itemMonthly, oAllDeduct.ID)
                                  + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Deduction, itemMonthly, oAllDeduct.ID);
                }

                #endregion

                dr["SalaryPayment"] = Math.Round(grossEarned -
                                                (Convert.ToDouble(dr["DeductBasic"]) +
                                                 Convert.ToDouble(dr["DeductSalaryAdvance"]) +
                                                 Convert.ToDouble(dr["ShopAdvance"]) +
                                                 Convert.ToDouble(dr["DeductPF"]) +
                                                 Convert.ToDouble(dr["ConductBonusDeduct"]) +
                                                 Convert.ToDouble(dr["TDS"])), 0);


                #region Overtime

                dr["OtHour"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Over_Time_Hours, itemMonthly);
                //double otPayment = GlobalFunctions.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Over_Time_Amount, itemMonthly));
                double otPayment = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Over_Time_Amount, itemMonthly);

                //double test = GlobalFunctions.Round(otPayment, 0);//For Echotex

                dr["OtPayment"] = Math.Round(otPayment, 0, MidpointRounding.AwayFromZero);
                dr["OtRate"] = 0.0;
                if (oEmpTermParameter != null)
                {
                    dr["OtRate"] = new TermParameterService().ConvertToHourlyRate(Convert.ToDouble(dr["Basic"]), 200);
                }

                #endregion

                #region Other Allowance

                // Attendence Bonus code: 001
                dr["AttnBonus"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "001");
                if (oAllDeduct != null)
                {
                    dr["AttnBonus"] = GlobalFunctions.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                    + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID));
                }

                // Conduct Bonus code: 002
                dr["ConductBonus"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "002");
                if (oAllDeduct != null)
                {
                    dr["ConductBonus"] = GlobalFunctions.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                 + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID));
                }

                // Production Bonus code: 013
                dr["TtlBonus"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "013");
                if (oAllDeduct != null)
                {

                    double prodBonus = GlobalFunctions.Round(itemMonthly.Details.Where(x => x.itemGroupCode == EnumSalaryGroup.Gross && x.ItemCode == EnumSalaryItemCode.Allowance && x.SalaryMonthlyID == itemMonthly.ID && x.ItemID == oAllDeduct.ID).Sum(x => x.ChangedAmount)
                                 + itemMonthly.Details.Where(x => x.itemGroupCode == EnumSalaryGroup.Arrear && x.ItemCode == EnumSalaryItemCode.Allowance && x.ID == itemMonthly.ID && x.ItemID == oAllDeduct.ID).Sum(x => x.ChangedAmount), 0);

                    //dr["TtlBonus"] = Math.Round(prodBonus);
                    dr["TtlBonus"] = prodBonus;
                }

                // Iftari Allowance code: 012
                dr["IfterBill"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "012");
                if (oAllDeduct != null)
                {
                    dr["IfterBill"] = GlobalFunctions.Round(itemMonthly.Details.Where(x => x.itemGroupCode == EnumSalaryGroup.Gross && x.ItemCode == EnumSalaryItemCode.Allowance && x.ItemID == oAllDeduct.ID).Sum(x => x.ChangedAmount)
                                 + itemMonthly.Details.Where(x => x.itemGroupCode == EnumSalaryGroup.Arrear && x.ItemCode == EnumSalaryItemCode.Allowance && x.ID == itemMonthly.ID && x.ItemID == oAllDeduct.ID).Sum(x => x.ChangedAmount));
                }

                // Extra Allowance 
                dr["ExtraAmount"] = 0;
                dr["ExtraDay"] = 0;
                dr["ExtraRate"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "004");

                if (oAllDeduct != null)
                {
                    ADParameter tempADParameter = (drEmp["GradeID"] != DBNull.Value && !string.IsNullOrWhiteSpace(drEmp["GradeID"].ToString())) ?
                                                  oAllADParameters.FirstOrDefault(x => x.AllowDeductID == oAllDeduct.ID && x.ADParameterGrades.Any(y => y.GradeID == Convert.ToInt32(drEmp["GradeID"].ToString()))) :
                                                  null;
                    dr["ExtraRate"] = tempADParameter != null ? tempADParameter.FlatAmount : 0;
                    dr["ExtraAmount"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    dr["ExtraDay"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Extra_Allowance_Days, itemMonthly, oAllDeduct.ID);
                }

                // Lunch Allowance 
                dr["LunchAmount"] = 0;
                dr["LunchDays"] = 0;
                dr["LunchRate"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "015");
                if (oAllDeduct != null)
                {
                    dr["LunchAmount"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID));
                    dr["LunchDays"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Lunch_Allowance_Days, itemMonthly, oAllDeduct.ID));
                    dr["LunchRate"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Lunch_Allowance_Rate, itemMonthly, oAllDeduct.ID));

                }
                // Night Shift Allowance 
                dr["NightShiftAmount"] = 0;
                dr["NightShiftDays"] = 0;
                dr["NightShiftRate"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "023");
                if (oAllDeduct != null)
                {
                    dr["NightShiftAmount"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID));
                    dr["NightShiftDays"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Night_Allowance_Days, itemMonthly, oAllDeduct.ID));
                    dr["NightShiftRate"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Night_Allowance_Rate, itemMonthly, oAllDeduct.ID));

                }
                // Special Allowance 
                dr["SpecialAmount"] = 0;
                dr["SpecialDays"] = 0;
                dr["SpecialRate"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "022");
                if (oAllDeduct != null)
                {
                    dr["SpecialAmount"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID));
                    dr["SpecialDays"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Special_Allowance_Days, itemMonthly, oAllDeduct.ID));
                    dr["SpecialRate"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Special_Allowance_Rate, itemMonthly, oAllDeduct.ID));

                }
                // NationalHoliday Allowance 
                dr["NHAmount"] = 0;
                dr["NHDays"] = 0;
                dr["NHRate"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "028");
                if (oAllDeduct != null)
                {
                    dr["NHAmount"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID));
                    dr["NHDays"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.National_Holiday_Allowance_Days, itemMonthly, oAllDeduct.ID));
                    dr["NHRate"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.National_Holiday_Allowance_Rate, itemMonthly, oAllDeduct.ID));

                }
                // Tiffin Allowance 
                dr["TiffinAmount"] = 0;
                dr["TiffinDay"] = 0;
                dr["TiffinRate"] = 0;
                oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "016");
                if (oAllDeduct != null)
                {
                    dr["TiffinAmount"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID));
                    dr["TiffinDay"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Tifin_Allowance_Days, itemMonthly, oAllDeduct.ID));
                    dr["TiffinRate"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Tifin_Allowance_Rate, itemMonthly, oAllDeduct.ID));
                }

                dr["GrossPercentage"] = 0;
                if (_SalaryMonth.LastDateOfMonth() == new DateTime(2020, 5, 31))//MAY_2020
                {
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "020");
                    if (oAllDeduct != null)
                    {
                        dr["GrossPercentage"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    }
                }

                #endregion

                #region Bonus Amount

                dr["EidBonus"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Bonus, itemMonthly);

                #endregion


                dr["NetPayment"] = Math.Round(Convert.ToDouble(dr["SalaryPayment"]) +
                                          Convert.ToDouble(dr["AttnBonus"]) +
                                          Convert.ToDouble(dr["OtPayment"]) +
                                          Convert.ToDouble(dr["ConductBonus"]) +
                                          Convert.ToDouble(dr["TtlBonus"]) +
                                          Convert.ToDouble(dr["IfterBill"]) +
                                          Convert.ToDouble(dr["EidBonus"]) +
                                           Convert.ToDouble(dr["ExtraAmount"]) +
                                           Convert.ToDouble(dr["LunchAmount"]) +
                                           Convert.ToDouble(dr["NightShiftAmount"]) +
                                           Convert.ToDouble(dr["SpecialAmount"]) +
                                           Convert.ToDouble(dr["TiffinAmount"]) +
                                            Convert.ToDouble(dr["NHAmount"]) +
                                           Convert.ToDouble(dr["GrossPercentage"]));
                //dr["NetPayment"] = itemMonthly.Details.Find(x => x.ItemCode == EnumSalaryItemCode.Net_Payable).ChangedAmount;
                List<SalaryMonthlyDetail> oSMDLeaveList
                              = itemMonthly
                              .Details
                              .Where(x => x.itemGroupCode == EnumSalaryGroup.Miscellaneous &&
                                     x.ItemCode == EnumSalaryItemCode.Leave_Days)
                              .ToList();

                #region Leave Calculation
                Leave currentLeave = null;
                dr["CL"] = dr["SL"] = dr["EL"] = dr["PL"] = dr["ML"] = dr["LWP"] = dr["SPL"] = dr["COM"] = dr["LOWT"] = 0;
                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "CL");
                if (currentLeave != null)
                {
                    dr["CL"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                            .Sum(x => x.ChangedAmount);
                }

                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "SL");
                if (currentLeave != null)
                {
                    dr["SL"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                         .Sum(x => x.ChangedAmount);
                }

                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "EL");
                if (currentLeave != null)
                {
                    dr["EL"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                            .Sum(x => x.ChangedAmount);
                }

                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "PL");
                if (currentLeave != null)
                {
                    dr["PL"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                            .Sum(x => x.ChangedAmount);
                }

                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "ML");
                if (currentLeave != null)
                {
                    dr["ML"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                            .Sum(x => x.ChangedAmount);
                }

                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "LWOP");
                if (currentLeave != null)
                {
                    dr["LWP"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                            .Sum(x => x.ChangedAmount);
                }

                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "SPL");
                if (currentLeave != null)
                {
                    dr["SPL"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                            .Sum(x => x.ChangedAmount);
                }

                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "COM");
                if (currentLeave != null)
                {
                    dr["COM"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                            .Sum(x => x.ChangedAmount);
                }

                currentLeave = oLeaves.SingleOrDefault(x => x.Code.ToUpper().Trim() == "L/OUT");
                if (currentLeave != null)
                {
                    dr["LOWT"] = oSMDLeaveList.Where(x => x.ItemID == currentLeave.ID)
                                            .Sum(x => x.ChangedAmount);
                }
                #endregion

                dr["Remarks"] = itemMonthly.Remarks;
                dTable.Rows.Add(dr);
            }

            //dTable.TableName = "PayrollDataSet_SalarySheetStatic";
            //oSalarySheets.Tables.Add(dTable);


            return dTable;
        }
        

        #endregion

        #region BanglaPaySlip
        public byte[] ShowBanglaPaySlip(int payrollTypeID, DateTime salaryMonth, string sEmpID, int reportId, string reportType, EnumBankCash reportItem)
        {
            string empNo = string.Empty;
            try
            {
                #region Initialize Components

                ReportProcessor form = new ReportProcessor();
                //string RDLCName = "HRM.Report.RDLC.BanglaPayslip.rdlc";
                string RDLCName = "BanglaPSlip.rdlc";
                _SalaryMonth = salaryMonth;
                //fReportViewer form = new fReportViewer();
                //string sEmpID = _selectedParameter.ReportItem.INSQL;
                //EnumBankCash? eBnkCash = _selectedParameter.BankCash;
                DateTime MAY_2020 = new DateTime(2020, 5, 31);
                //string sEmpID = null;
                EnumBankCash? eBnkCash = null;
                List<SalaryMonthly> salarymonthlies = null;
                //int payrollTypeID = 0;
                DataSet oSalaryMonthlyDetails = new SalaryMonthlyService().GetEmpPaySlipGrossForOthers(_SalaryMonth.LastDateOfMonth(), sEmpID);
                if (eBnkCash != null && eBnkCash.Value != EnumBankCash.All)
                {
                    salarymonthlies = eBnkCash.Value == EnumBankCash.Bank ? new SalaryMonthlyService().Get(sEmpID, _SalaryMonth.LastDateOfMonth(), payrollTypeID)
                                                                                         .Where(x => !GlobalExtensions.IsNullOrWhiteSpace(x.AccountNo))
                                                                                         .ToList()
                                                                          : new SalaryMonthlyService().Get(sEmpID, _SalaryMonth.LastDateOfMonth(), payrollTypeID)
                                                                                         .Where(x => GlobalExtensions.IsNullOrWhiteSpace(x.AccountNo))
                                                                                         .ToList();

                    sEmpID = salarymonthlies.Aggregate(new StringBuilder(), (sb, sm) => sb.AppendFormat("{0},", sm.EmployeeID), sb => sb.ToString().Trim(','));
                }
                else
                {
                    salarymonthlies = new SalaryMonthlyService().Get(sEmpID, _SalaryMonth.LastDateOfMonth(), payrollTypeID);
                }
                SalaryCalculator salaryCalculator = new SalaryCalculator();
                //salaryCalculator.SetSalaryMontlys(salarymonthlies);
                Func<int, double> invertedGrossRatio = (empID) => salaryCalculator.CalculateInvertedGrossFraction(_SalaryMonth.LastDateOfMonth(), empID);

                //if (sEmpID.IsNullOrWhiteSpace())
                //{
                //    //MessageBox.Show("No Employee Found");
                //    throw new Exception("No Employee Found");
                //    return;
                //}
                List<AllowanceDeduction> oAllDeducts = new AllowanceDeductionService().Get(EnumStatus.Regardless);
                List<Leave> oLeaves = new LeaveService().GetAll();
                List<Employee> oEmployees = new EmployeeService().GetByEmpIDs(sEmpID);
                List<AccessCard> oCards = new AccessCardService().Get();

                //List<TermParameter> oAllTermParameters = new TermParameterService().Get(true);

                List<TermParameter> oAllTermParameters = new TermParameterService().GetByPayrollTypeID(payrollTypeID);

                //List<ADParameter> oAllADParameters = new ADParameterService().Get(status, payrollTypeID);
                int status = (int)EnumStatus.Active;
                ADParameter oADParameter = new ADParameterService().Get(status, payrollTypeID);
                List<ADParameter> oAllADParameters = new List<ADParameter>();

                if (oADParameter != null)
                {
                    oAllADParameters.Add(oADParameter);
                }
                oAllADParameters.ForEach(x => x.ADParameterGrades = x.ADParameterGrades);
                double totalDaysInMonth = _SalaryMonth.TotalDaysInMonth();
                DataRow oDR = null;
                double totalGross = 0.0, totalDays = 0.0, fractionamount = 0.0;
                double basicEarned, houserentEarned, conveyanceEarned, medicalEarned, foodEarned, grossEarned;

                PayrollDataSet.PayrollDataSet.BanglaPaySlipNewDataTable banglaPaySlipData = new PayrollDataSet.PayrollDataSet.BanglaPaySlipNewDataTable();

                PayrollDataSet.PayrollDataSet.BanglaPaySlipNewProdBonusDataTable banglaPaySlipProdData = new PayrollDataSet.PayrollDataSet.BanglaPaySlipNewProdBonusDataTable();

                PayrollDataSet.dsBonusDataSet.BanglaPSlipBonusDataTable banglaPaySlipBonusData = new PayrollDataSet.dsBonusDataSet.BanglaPSlipBonusDataTable();

                DataSet dsProdBonus = new ProdBonusProcessService().GetDetailItems(_SalaryMonth.LastDateOfMonth());

                //DataSet dsEmpBasicInfo = new EmployeeService().GetEmpReportRelatedInfo(sEmpID);
                DataSet dsEmpBasicInfo = new EmployeeService().GetAllEmpBasicInfo(sEmpID);


                #region Calcullate Bangla Month

                string printDateBangla = DateTime.Today.Day + " " + GlobalExtensions.BanglaMonth(DateTime.Today) + " " + DateTime.Today.Year;

                string month = GlobalExtensions.BanglaMonth(_SalaryMonth) + "-" + _SalaryMonth.Year + " gv‡mi Rb¨";

                #endregion

                #endregion

                #region Production Bonus Related
                if (dsProdBonus.Tables != null && dsProdBonus.Tables.Count > 0)
                {
                    foreach (DataRow dRow in dsProdBonus.Tables[0].Rows)
                    {
                        DataRow ToRow = banglaPaySlipProdData.NewRow();
                        ToRow["EmployeeNo"] = dRow["EMPLOYEENO"];
                        ToRow["Name"] = dRow["Description"];
                        ToRow["Amount"] = dRow["Amount"];
                        banglaPaySlipProdData.Rows.Add(ToRow);
                    }
                }
                #endregion

                foreach (SalaryMonthly itemMonthly in salarymonthlies)
                {
                    totalGross = 0.0; grossEarned = basicEarned = houserentEarned = conveyanceEarned = medicalEarned = foodEarned = totalDays = 0;
                    DataRow drEmpInfo = dsEmpBasicInfo.Tables[0].AsEnumerable().FirstOrDefault(x => Convert.ToInt32(x["EmployeeID"].ToString()) == itemMonthly.EmployeeID);

                    oDR = banglaPaySlipData.NewRow();
                    TermParameter oEmpTermParameter = null;

                    //SalaryMonthlyService new SalaryMonthlyService() = new SalaryMonthlyService();

                    if (drEmpInfo != null)
                    {
                        //Need to change
                        //oEmpTermParameter = drEmpInfo["GradeID"] != DBNull.Value ? oAllTermParameters.FirstOrDefault(x => x.SetupDetails.Any(y => y.TranID == Convert.ToInt32(drEmpInfo["GradeID"].ToString())))
                        //: null;
                        oDR["Division"] = drEmpInfo["Department"];
                        oDR["BanglaDivision"] = drEmpInfo["DepartmentBangla"];

                        oDR["Line"] = drEmpInfo["Line"];
                        oDR["BanglaLine"] = drEmpInfo["LineBangla"];

                        oDR["Floor"] = drEmpInfo["Floor"];
                        oDR["FloorBangla"] = drEmpInfo["FloorBangla"];

                        oDR["Section"] = drEmpInfo["Section"];
                        oDR["SectionBangla"] = drEmpInfo["SectionBangla"];

                        oDR["EmpNo"] = drEmpInfo["EmployeeNo"];
                        empNo = drEmpInfo["EmployeeNo"].ToString();
                        oDR["Name"] = drEmpInfo["Name"];
                        oDR["BanglaName"] = drEmpInfo["BanglaName"];
                        oDR["Designation"] = drEmpInfo["Designation"];
                        oDR["BanglaDesignation"] = drEmpInfo["BanglaDesignation"];
                        DateTime joiningDate = Convert.ToDateTime(drEmpInfo["JoiningDate"].ToString());
                        oDR["DOfJoining"] = joiningDate.Day.ToString() + " " + GlobalExtensions.BanglaMonth(joiningDate) + " " + joiningDate.Year.ToString();
                        AccessCard ac = drEmpInfo["CardID"] != DBNull.Value ? oCards.FirstOrDefault(x => x.ID == Convert.ToInt32(drEmpInfo["CardID"].ToString()))
                                                                            : null;
                        oDR["CardNo"] = ac != null ? ac.CardNumber : string.Empty;
                        oDR["BankAccountNo"] = drEmpInfo["AccountNo"];
                        oDR["TINNO"] = drEmpInfo["TINNO"];

                    }

                    oDR["SalaryMonth"] = _SalaryMonth;

                    #region Day Calcullation

                    //totalDays = itemMonthly.GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Total_Days);
                    totalDays = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Total_Days, itemMonthly);

                    fractionamount = totalDays == 0 ? 1 : totalDaysInMonth / totalDays;
                    // test
                    //fractionamount = 1;

                    oDR["TotalWorkDays"] = totalDays;

                    oDR["PresentDays"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Tot_Attend_Days, itemMonthly);

                    oDR["HolidayDays"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Total_HoliDays, itemMonthly);

                    oDR["AbsentDays"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Tot_UnauthLeave_Days, itemMonthly);


                    #endregion

                    #region Gross Payment

                    basicEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Basic_Salary, itemMonthly)
                                 + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Basic_Salary, itemMonthly);

                    oDR["BasicSalary"] = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Basic_Salary, itemMonthly)) +
                                  +new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Basic_Salary, itemMonthly);

                    double definedBasic = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Basic_Salary, itemMonthly);

                    #region Calcullate Basic Allowances

                    // House rent code: 008
                    AllowanceDeduction oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Allowance && x.Code.Trim() == "008");
                    if (oAllDeduct != null)
                    {
                        houserentEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                 + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                        oDR["HouseRent"] = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)) +
                                           new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    }
                    else
                    {
                        oDR["HouseRent"] = 0;
                    }

                    // medical code: 011
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Allowance && x.Code.Trim() == "011");

                    if (oAllDeduct != null)
                    {
                        medicalEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                    + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                        oDR["Medical"] = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID))
                                            + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    }
                    else
                    {
                        oDR["Medical"] = 0;
                    }

                    // Conveyance code: 010
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Allowance && x.Code.Trim() == "010");

                    if (oAllDeduct != null)
                    {
                        conveyanceEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                         + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                        oDR["Conveynce"] = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID))
                                         + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    }
                    else
                    {
                        oDR["Conveynce"] = 0;
                    }


                    // FoodAllowance code: 006
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Allowance && x.Code.Trim() == "006");

                    if (oAllDeduct != null)
                    {
                        foodEarned = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                      + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                        oDR["Food"] = fractionamount * invertedGrossRatio(itemMonthly.EmployeeID) * (new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID))
                                      + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);
                    }
                    else
                    {
                        oDR["Food"] = 0;
                    }

                    #endregion

                    grossEarned = basicEarned +
                                houserentEarned +
                                medicalEarned +
                                conveyanceEarned +
                                foodEarned;

                    totalGross = Convert.ToDouble(oDR["BasicSalary"]) +
                                 Convert.ToDouble(oDR["HouseRent"]) +
                                 Convert.ToDouble(oDR["Medical"]) +
                                 Convert.ToDouble(oDR["Conveynce"]) +
                                 Convert.ToDouble(oDR["Food"]);

                    oDR["NetPayment"] = totalGross;

                    #endregion

                    #region Deductions

                    // variable used if muliple basic deduction exist
                    double deductBasic = 0;
                    // UnAuthorize Leave Basic Deduct
                    deductBasic = new SalaryMonthlyService()
                                   .GetAmount(EnumSalaryGroup.UnauthLeave, EnumSalaryItemCode.Basic_Salary, itemMonthly);

                    oDR["DeductAmnt"] = deductBasic;



                    oDR["DeductPF"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.PF_Contribution, itemMonthly);

                    double shopAdvance = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Loan_Monthly_Installment, itemMonthly, "Shop Advance");
                    double salaryAdvance = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Loan_Monthly_Installment, itemMonthly)
                                           - shopAdvance;

                    oDR["ShopAdvance"] = shopAdvance;

                    oDR["DeductSalaryAdvance"] = salaryAdvance;

                    // Deduct Conduct Bonus code: 005
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.AllowOrDeductType == EnumAllowOrDeduct.Deduction && x.Code.Trim() == "005");
                    if (oAllDeduct != null)
                    {
                        oDR["ConductBonusDeduct"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Deduction, itemMonthly, oAllDeduct.ID)
                                 + new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Deduction, itemMonthly, oAllDeduct.ID);


                    }
                    else
                    {
                        oDR["ConductBonusDeduct"] = 0;
                    }

                    oDR["TDS"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Deductions, EnumSalaryItemCode.Inc_Tax_Deduction, itemMonthly);
                    // For Now Only Deduct Basic
                    oDR["DeductOther"] = 0;
                    double givenTaka = 0.0;
                    double allDeductions = Convert.ToDouble(oDR["DeductPF"]) +
                                Convert.ToDouble(oDR["DeductSalaryAdvance"]) +
                                Convert.ToDouble(oDR["ShopAdvance"]) +
                                Convert.ToDouble(oDR["DeductAmnt"]) +
                                Convert.ToDouble(oDR["ConductBonusDeduct"]) +
                                Convert.ToDouble(oDR["TDS"])
                                ;
                    oDR["DeductOther"] = allDeductions;

                    #endregion

                    givenTaka = Math.Round(grossEarned - allDeductions, 0);

                    oDR["GivenSalary"] = givenTaka;


                    #region Calcullate Other Allowances

                    // Attendence Bonus code: 001
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "001");

                    oDR["AttBon"] = oAllDeduct != null ?
                                       new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID) +
                                       new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                        : 0;



                    // Conduct Bonus code: 002
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "002");

                    oDR["ConductBonus"] = oAllDeduct != null ?
                                   new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID) +
                                   new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                    : 0;


                    // Production Bonus code: 012
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "012");

                    oDR["ProdBonus"] = oAllDeduct != null ?
                                       new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID) +
                                       new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Arrear, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID)
                                       : 0;

                    // Extra Allowance Code : 004
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "004");

                    if (oAllDeduct != null)
                    {
                        oDR["ExtraAllowance"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                        oDR["ExtraAllowanceDays"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Extra_Allowance_Days, itemMonthly, oAllDeduct.ID);

                        ADParameter TempADParameter = oAllADParameters.FirstOrDefault(x => x.AllowDeductID == oAllDeduct.ID && x.ADParameterGrades.Any(y => y.GradeID == itemMonthly.Employee.GradeID));

                        oDR["ExtraAllowanceRate"] = TempADParameter != null ? TempADParameter.FlatAmount : 0;

                    }
                    else
                    {
                        oDR["ExtraAllowance"] = 0;

                        oDR["ExtraAllowanceDays"] = 0;

                        oDR["ExtraAllowanceRate"] = 0;
                    }

                    double tiffinAndLunch = 0;
                    // Lunch Allowance Code : 015
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "015");

                    if (oAllDeduct != null)
                    {
                        tiffinAndLunch += new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                    }

                    // Tiffin Allowance Code : 016
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "016");

                    if (oAllDeduct != null)
                    {
                        tiffinAndLunch += new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                    }
                    oDR["TifinLunch"] = tiffinAndLunch;
                    #region SpecialNightShift
                    double special = 0;
                    // Specisl Allowance Code : 015
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "022");

                    if (oAllDeduct != null)
                    {
                        special = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                    }
                    oDR["Special"] = special;
                    // NightShift Allowance Code : 016
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "023");
                    double NightShift = 0;
                    if (oAllDeduct != null)
                    {
                        NightShift = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                    }
                    oDR["NightShift"] = NightShift;
                    #endregion
                    double ifterBill = 0;
                    // ifterBill Allowance Code : 012
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "012");

                    if (oAllDeduct != null)
                    {
                        ifterBill += new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                    }
                    oDR["IfterBill"] = ifterBill;


                    oDR["GrossPercentage"] = 0;
                    // ifterBill Allowance Code : 012
                    if (_SalaryMonth.LastDateOfMonth() == MAY_2020)//if (_SalaryMonth.LastDateOfMonth() == SalaryCalculator.MAY_2020)
                    {
                        oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "020");

                        if (oAllDeduct != null)
                        {
                            oDR["GrossPercentage"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID);

                        }
                    }

                    #endregion

                    #region Bonus

                    double totalBonus = 0;

                    foreach (var item in itemMonthly.Details.Where(x => x.ItemCode == EnumSalaryItemCode.Bonus &&
                                                                   x.itemGroupCode == EnumSalaryGroup.Gross))
                    {
                        DataRow dRB = banglaPaySlipBonusData.NewRow();
                        dRB["EmpNo"] = drEmpInfo["EmployeeNo"];
                        dRB["Description"] = item.Description;
                        dRB["Amount"] = item.ChangedAmount;
                        totalBonus += item.ChangedAmount;
                        banglaPaySlipBonusData.Rows.Add(dRB);
                    }

                    oDR["EidBonus"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Bonus, itemMonthly);
                    //oDR["Bonus"] = itemMonthly.GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Bonus,);

                    #endregion

                    #region Production Bonus
                    if (dsProdBonus.Tables != null && dsProdBonus.Tables.Count > 0)
                    {
                        if (dsProdBonus.Tables[0] != null && dsProdBonus.Tables[0].Rows.Count > 0)
                        {
                            DataTable dt2 = new DataTable();
                            oDR["ProdBonus"] = 0;
                            var accItems = dsProdBonus.Tables[0].AsEnumerable().Where(x => x["EMPLOYEENO"].ToString().Trim() == oDR["EmpNo"].ToString());
                            if (accItems.Count() > 0)
                                dt2 = accItems.CopyToDataTable();
                            if (dt2 != null && dt2.Rows.Count > 0)
                            {
                                //int i = 1;
                                foreach (DataRow dr in dt2.Rows)
                                {
                                    // This is not needed as we show detail in a subreport
                                    //oDR["ProdBonusName" + i.ToString()] = dr["LineName"];
                                    //oDR["ProdBonusAmount" + i.ToString()] = Convert.ToDouble(dr["Amount"]);
                                    oDR["ProdBonus"] = Convert.ToDouble(oDR["ProdBonus"]) + Convert.ToDouble(dr["Amount"]);
                                    //i++;
                                }
                            }
                        }
                    }
                    #endregion
                    // NationalHoliday Allowance 
                    oDR["NHAmount"] = 0;
                    oDR["NHDays"] = 0;
                    oDR["NHRate"] = 0;
                    oAllDeduct = oAllDeducts.FirstOrDefault(x => x.Code.Trim() == "028");
                    if (oAllDeduct != null)
                    {
                        oDR["NHAmount"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Allowance, itemMonthly, oAllDeduct.ID));
                        oDR["NHDays"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.National_Holiday_Allowance_Days, itemMonthly, oAllDeduct.ID));
                        oDR["NHRate"] = (int)Math.Round(new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.National_Holiday_Allowance_Rate, itemMonthly, oAllDeduct.ID));

                    }
                    #region Overtime


                    oDR["OTHours"] = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Miscellaneous, EnumSalaryItemCode.Over_Time_Hours, itemMonthly);

                    double otPayment = new SalaryMonthlyService().GetAmount(EnumSalaryGroup.Gross, EnumSalaryItemCode.Over_Time_Amount, itemMonthly);

                    oDR["OTPayable"] = GlobalFunctions.Round(otPayment);


                    if (Convert.ToDouble(oDR["OTHours"]) > 0)
                    {
                        oDR["OTRate"] = Math.Round(Convert.ToDouble(oDR["OTPayable"]) / Convert.ToDouble(oDR["OTHours"]), 2);
                    }
                    else
                    {
                        if (oEmpTermParameter != null)
                        {
                            //Need to Solve
                            //oDR["OTRate"] = Math.Round(new TermParameterService().GetOTRate(Math.Round(definedBasic * fractionamount), _SalaryMonth.LastDateOfMonth()), 2);
                            oDR["OTRate"] = "";
                        }
                        else
                        {
                            oDR["OTRate"] = 0.00;
                        }
                    }
                    #endregion

                    double totalTaka = givenTaka + Convert.ToDouble(oDR["AttBon"]) +
                               Convert.ToDouble(oDR["ConductBonus"]) +
                               Convert.ToDouble(oDR["ExtraAllowance"]) +
                               Convert.ToDouble(oDR["TifinLunch"]) +
                               totalBonus +
                               Convert.ToDouble(oDR["ProdBonus"]) +
                               Convert.ToDouble(oDR["IfterBill"]) +
                               Convert.ToDouble(oDR["OTPayable"]) +
                               Convert.ToDouble(oDR["GrossPercentage"]) +
                               special + NightShift;
                    oDR["TotalTaka"] = totalTaka;

                    banglaPaySlipData.Rows.Add(oDR);
                }


                DataSet ds = new DataSet();
                //banglaPaySlipData.TableName = "PayrollDataSet_BanglaPaySlipNew";
                banglaPaySlipData.TableName = "PayrollDataSet_BanglaPaySlipNew";
                ds.Tables.Add(banglaPaySlipData);
                DataSet dsSub = new DataSet();
                banglaPaySlipProdData.TableName = "PayrollDataSet_BanglaPaySlipNewProdBonus";
                dsSub.Tables.Add(banglaPaySlipProdData);
                banglaPaySlipBonusData.TableName = "dsBonusDataSet_BanglaPSlipBonus";
                dsSub.Tables.Add(banglaPaySlipBonusData);

                List<ReportParameter> _parameters = new List<ReportParameter>();


                ReportParameter parameter = new ReportParameter("rptMonth", month);
                _parameters.Add(parameter);

                parameter = new ReportParameter("printDate", DateTime.Today.ToString("dd-MMM-yy"));
                _parameters.Add(parameter);

                parameter = new ReportParameter("printDateBangla", printDateBangla);
                _parameters.Add(parameter);

                parameter = new ReportParameter("companyName", System.Configuration.ConfigurationManager.AppSettings["CompanyName"]);
                _parameters.Add(parameter);

                parameter = new ReportParameter("companyNameBangla", System.Configuration.ConfigurationManager.AppSettings["CompanyNameBangla"]);
                _parameters.Add(parameter);

                parameter = new ReportParameter("salaryMonthEng", _SalaryMonth.ToString("MMM-yy"));
                _parameters.Add(parameter);
                //string RDLC = (_SalaryMonth.LastDateOfMonth() == MAY_2020) ?//string RDLC = (_SalaryMonth.LastDateOfMonth() == SalaryCalculator.MAY_2020) ?
                //        "Payroll.Report.RDLC.BanglaPSlipMay2020.rdlc" :
                //        "Payroll.Report.RDLC.BanglaPSlip.rdlc";

                return form.CommonReportViewForReports(null, ds, dsSub, RDLCName, _parameters, false, payrollTypeID, reportType);
                //return form.CommonReportView(null, RDLCName, resultDataSet, null, reportParameters, true, payrollTypeId, reportType);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
        #endregion


        #region DailyPresent
        public byte[] ShowDailyPresent(DateTime dFromDate, string sEmpID, string reportType, int payrollTypeID)
        {
            ReportProcessor reportProcessor = new ReportProcessor();
            DateTime attnDate = dFromDate;
            //string sEmpID = sEmpID;

            DataRow oDR = null;
            DataSet oDailyInOut = null;
            //new DailyAttnProcessService().GetDailyDataByStatus(attnDate, sEmpID, EnumAttendanceType.Present, EnumAttendanceType.Late, EnumAttendanceType.Early, EnumAttendanceType.Delay, EnumAttendanceType.On_Business_Travel, EnumAttendanceType.OutSideDuty);
            oDailyInOut = new DailyAttnProcessService().GetDailyDataByStatus(attnDate, sEmpID, EnumAttendanceType.Present, EnumAttendanceType.Late, EnumAttendanceType.Early, EnumAttendanceType.Delay, EnumAttendanceType.HalfDay, EnumAttendanceType.OutSideDuty);

            HRM.Report.Attendence.AttendenceDataSet.AttendenceDataSet.DailyInOutDataTable dTable = new HRM.Report.Attendence.AttendenceDataSet.AttendenceDataSet.DailyInOutDataTable();

            foreach (DataRow Dr in oDailyInOut.Tables[0].Rows)
            {
                oDR = dTable.NewRow();

                oDR["EmployeeNo"] = Dr["EMPLOYEENO"];
                oDR["Name"] = Dr["Name"];
                oDR["Designation"] = Dr["Designation"];
                oDR["InTime"] = Dr["InTime"] is DBNull ? "00:00" : Convert.ToDateTime(Dr["InTime"]).ToString("HH:mm");
                oDR["OutTime"] = Dr["OutTime"] is DBNull ? "00:00" : Convert.ToDateTime(Dr["OutTime"]).ToString("HH:mm");
                oDR["EmpType"] = Dr["EmpType"].ToString();
                oDR["Status"] = GlobalFunctions.GetShortAttnType((EnumAttendanceType)Convert.ToInt32(Dr["Status"]));
                oDR["OTHour"] = GlobalFunctions.ConvertDoubleHourToHourMinute(Convert.ToDouble(Dr["OTHour"]));
                oDR["OTHourDBL"] = Convert.ToDouble(Dr["OTHour"]);
                oDR["DeptID"] = Convert.ToInt32(Dr["DeptID"].ToString());
                oDR["DeptName"] = Dr["DeptName"].ToString();
                oDR["Department"] = Dr["Department"].ToString();
                oDR["Section"] = Dr["Section"].ToString();
                oDR["Line"] = Dr["Line"].ToString();
                oDR["Floor"] = Dr["Floor"].ToString();
                oDR["Shift"] = Dr["Shift"].ToString();
                oDR["CardNo"] = Dr["CardNo"].ToString();
                dTable.Rows.Add(oDR);
            }

            DataSet dSet = new DataSet();
            dTable.TableName = "AttendenceDataSet_DailyInOut";
            dSet.Tables.Add(dTable);

            //string RDLC = "HRM.Report.Attendence.RDLC.DailyPresent.rdlc";
            string RDLC = "DailyPresentEcho.rdlc";

            List<ReportParameter> _reportParameters = new List<ReportParameter>();
            ReportParameter rParam = new ReportParameter("AttnDate", attnDate.ToString("dd MMM yyyy"));
            _reportParameters.Add(rParam);
            //rParam = new ReportParameter("Fax", "");
            //_reportParameters.Add(rParam);
            //rParam = new ReportParameter("Email", systemInfo.email);
            //_reportParameters.Add(rParam);

            //return new ReportProcessor().CommonReportView(null, RDLC, dSet, null, _reportParameters, true, payrollTypeID, reportType);
            return reportProcessor.AttendanceReportsView(null, dSet, null, RDLC, _reportParameters, true, payrollTypeID, reportType);
            //AttendanceReportView(reportItem, dSet, dSubReportDataSet, reportName, parameters, defaultParameterNeeded, payrollTypeId, reportType)

        }
        #endregion

        #region Absent
        public byte[] ShowDailyAbsent(DateTime dFromDate, string sEmpID, string reportType, int payrollTypeID)
        {
            ReportProcessor reportProcessor = new ReportProcessor();
            DateTime attnDate = dFromDate;
            DataSet oDailyInOut = null;
            DataRow oDR = null;
            oDailyInOut = new DailyAttnProcessService().GetDailyDataByStatus(attnDate, sEmpID, EnumAttendanceType.Absent);

            HRM.Report.Attendence.AttendenceDataSet.AttendenceDataSet.DailyInOutDataTable dTable = new Attendence.AttendenceDataSet.AttendenceDataSet.DailyInOutDataTable();

            foreach (DataRow Dr in oDailyInOut.Tables[0].Rows)
            {
                oDR = dTable.NewRow();

                oDR["EmployeeNo"] = Dr["EMPLOYEENO"];
                oDR["Name"] = Dr["Name"];
                oDR["Designation"] = Dr["Designation"];
                oDR["InTime"] = Dr["InTime"] is DBNull ? "00:00" : Convert.ToDateTime(Dr["InTime"]).ToString("HH:mm tt");
                oDR["OutTime"] = Dr["OutTime"] is DBNull ? "00:00" : Convert.ToDateTime(Dr["OutTime"]).ToString("HH:mm tt");
                oDR["EmpType"] = Dr["EmpType"].ToString();
                oDR["Status"] = GlobalFunctions.GetShortAttnType(((EnumAttendanceType)Convert.ToInt32(Dr["Status"])));
                oDR["OTHour"] = GlobalFunctions.ConvertDoubleHourToHourMinute(Convert.ToDouble(Dr["OTHour"]));
                oDR["OTHourDBL"] = Convert.ToDouble(Dr["OTHour"]);
                oDR["DeptID"] = Convert.ToInt32(Dr["DeptID"].ToString());
                oDR["DeptName"] = Dr["DeptName"].ToString();
                oDR["Department"] = Dr["Department"].ToString();
                oDR["Section"] = Dr["Section"].ToString();
                oDR["Line"] = Dr["Line"].ToString();
                oDR["Floor"] = Dr["Floor"].ToString();
                oDR["Shift"] = Dr["Shift"].ToString();
                oDR["CardNo"] = Dr["CardNo"].ToString();
                dTable.Rows.Add(oDR);
            }


            DataSet dSet = new DataSet();
            dTable.TableName = "AttendenceDataSet_DailyInOut";
            dSet.Tables.Add(dTable);

            string RDLC = "DailyAbsentEcho.rdlc";

            ReportParameter rParam;
            List<ReportParameter> _reportParameters = new List<ReportParameter>();
            rParam = new ReportParameter("AttnDate", attnDate.ToString("dd MMM yyyy"));
            _reportParameters.Add(rParam);

            return reportProcessor.AttendanceReportsView(null, dSet, null, RDLC, _reportParameters, true, payrollTypeID, reportType);

        }
        #endregion

        #region Attendance Reports

        #region Monthly Detail
        public byte[] GetMonthlyDetailAttendance(DateTime dFromDate, string sEmpID, string reportType, int payrollTypeID)
        {
            //DateTime dFromDate = _selectedParameter.FromDate.Value;
            //DateTime dToDate = _selectedParameter.ToDate.Value;
            //string sEmpID = _selectedParameter.ReportItem.INSQL;
            DataSet oMonthlyDetail = null;
            DataRow oDR = null;
            oMonthlyDetail = new EchoTexExceptionReportService().GetMonthlyAttendanceDetail(GlobalFunctions.FirstDateOfMonth(dFromDate), GlobalFunctions.LastDateOfMonth(dFromDate), sEmpID);

            Attendence.AttendenceDataSet.AttendenceDataSet.MonthlyDetailDataTable dTable = new Attendence.AttendenceDataSet.AttendenceDataSet.MonthlyDetailDataTable();
            //int serial = 1;

            foreach (DataRow Dr in oMonthlyDetail.Tables[0].Rows)
            {
                oDR = dTable.NewRow();

                //oDR["Serial"] = serial.ToString();
                oDR["EmployeeNo"] = Dr["EMPLOYEENO"];
                oDR["Name"] = Dr["Name"];
                oDR["CardNo"] = Dr["CardNo"].ToString();
                oDR["Designation"] = Dr["Designation"];
                oDR["JoinDate"] = Convert.ToDateTime(Dr["JOININGDATE"]).ToString("dd MMM yyyy");
                oDR["Gross"] = Convert.ToDouble(Dr["GROSSSALARY"]);
                oDR["AttnDate"] = Convert.ToDateTime(Dr["AttnDate"]).ToString("dd/MM/yy");
                oDR["AttnType"] = GlobalFunctions.GetShortAttnType(((EnumAttendanceType)Convert.ToInt32(Dr["AttenType"])));
                oDR["Department"] = Dr["Department"].ToString();
                oDR["Section"] = Dr["Section"].ToString();
                oDR["Line"] = Dr["Line"].ToString();
                oDR["Floor"] = Dr["Floor"].ToString();

                dTable.Rows.Add(oDR);
                //serial++;
            }

            DataSet dSet = new DataSet();
            dTable.TableName = "AttendenceDataSet_MonthlyDetail";
            string RDLC = "HRM.Report.Attendence.RDLC.MonthlyDetailAttnEcho.rdlc";
            dSet.Tables.Add(dTable);

            List<ReportParameter> _parameters = new List<ReportParameter>();
            ReportParameter rParam = new ReportParameter("Fromdate", GlobalFunctions.FirstDateOfMonth(dFromDate).ToString("dd MMM yyyy"));
            _parameters.Add(rParam);
            rParam = new ReportParameter("ToDate", GlobalFunctions.LastDateOfMonth(dFromDate).ToString("dd MMM yyyy"));
            _parameters.Add(rParam);

            return new ReportProcessor().CommonReportView(null, RDLC, dSet, null, _parameters, true, payrollTypeID, reportType);
        }
        #endregion

        #region Multiple Employee Job Card
        public byte[] ShowJobCardMultiple(DateTime dFromDate, DateTime dToDate, string sEmpIDs, string reportType, int payrollTypeID)
        {
            //DateTime dFromDate = _selectedParameter.FromDate.Value.Date.FirstDateOfMonth();
            //DateTime dToDate = _selectedParameter.ToDate.Value.Date.LastDateOfMonth();
            if (dFromDate > dToDate)
            {
                var temp = dFromDate;
                dFromDate = dToDate;
                dToDate = temp;
            }
            //string sEmpID = _selectedParameter.ReportItem.INSQL;

            DataSet dsEmployee = new EmployeeService().GetAllEmpBasicInfo(sEmpIDs);
            var employees = new EmployeeService().GetByEmpIDs(sEmpIDs);
            var dAttnProcessess = new DailyAttnProcessService().Get(sEmpIDs, dFromDate, dToDate);
            //List<ADParameter> _adps = ADParameter.Get(EnumStatus.Regardless, EnumAllowOrDeduct.Allowance);
            //AllowanceDeduction oAttnNightAllowance = oAllDeducts.FirstOrDefault(x => x.Code.Trim().ToUpper() == "023" && x.AllowOrDeductType == EnumAllowOrDeduct.Allowance);
            //AllowanceDeduction oAttnSpacialAllowance = oAllDeducts.FirstOrDefault(x => x.Code.Trim().ToUpper() == "022" && x.AllowOrDeductType == EnumAllowOrDeduct.Allowance);
            //oShiftIDs = (_adps != null && _adps.Count > 0) ? _adps.Where(y => y.AllowDeductID == oAttnNightAllowance.ID).SelectMany(z => z.ADParameterShifts).Select(a => a.ShiftID).ToList() : null;
            //oShiftIDsSpecial = (_adps != null && _adps.Count > 0) ? _adps.Where(y => y.AllowDeductID == oAttnSpacialAllowance.ID).SelectMany(z => z.ADParameterShifts).Select(a => a.ShiftID).ToList() : null;

            List<ADParameter> _adps = new ADParameterService().Get(EnumStatus.Regardless, EnumAllowOrDeduct.Allowance, payrollTypeID);
            List<AllowanceDeduction> oAllowanceDeduction = new AllowanceDeductionService().Get(EnumStatus.Regardless);
            List<ADParameterEmployee> oADParameterEmployee = new ADParameterEmployeeService().Get(EnumADEmpType.NotApplicable);
            List<ADParameter.ADParameterShift> oADParameterShift = new ADParameterService().GetAllShifts();

            foreach (ADParameter item in _adps)
            {
                item.AllowanceDeduction = oAllowanceDeduction.Where(x => x.ID == item.AllowDeductID).FirstOrDefault();
                item.NotApplicable = oADParameterEmployee.Where(x => x.ADParameterID == item.ID && x.ADEmpType == EnumADEmpType.NotApplicable).ToList();
                item.ADParameterShifts = oADParameterShift.Where(x => x.ADParameterID == item.ID).ToList();

            }
            List<AllowanceDeduction>  oAllDeducts = new AllowanceDeductionService().Get(EnumStatus.Regardless);
            AllowanceDeduction oAttnNightAllowance = oAllDeducts.FirstOrDefault(x => x.Code.Trim().ToUpper() == "023" && x.AllowOrDeductType == EnumAllowOrDeduct.Allowance);
            AllowanceDeduction oAttnSpacialAllowance = oAllDeducts.FirstOrDefault(x => x.Code.Trim().ToUpper() == "022" && x.AllowOrDeductType == EnumAllowOrDeduct.Allowance);
            List<int> oShiftIDs = (_adps != null && _adps.Count > 0) ? _adps.Where(y => y.AllowDeductID == oAttnNightAllowance.ID).SelectMany(z => z.ADParameterShifts).Select(a => Convert.ToInt32(a.ShiftID)).ToList() : null;
            List<int> oShiftIDsSpecial = (_adps != null && _adps.Count > 0) ? _adps.Where(y => y.AllowDeductID == oAttnSpacialAllowance.ID).SelectMany(z => z.ADParameterShifts).Select(a => Convert.ToInt32(a.ShiftID)).ToList() : null;


            Attendence.AttendenceDataSet.AttendenceDataSet.EmpDailyAttnParentDataTable dTableParent = new Attendence.AttendenceDataSet.AttendenceDataSet.EmpDailyAttnParentDataTable();
            Attendence.AttendenceDataSet.AttendenceDataSet.EmpDailyAttnDataTable dTableChild = new Attendence.AttendenceDataSet.AttendenceDataSet.EmpDailyAttnDataTable();


            List<AttnNationalHoliday> oNationalHolidays = new AttnNationalHolidayService().GetByMonth(PayrollGlobalFunctions.FirstDateOfYear(dFromDate), PayrollGlobalFunctions.LastDateOfYear(dToDate));
            List<Leave> oLeaves = new LeaveService().Get();
            List<Shift> oShifts = new ShiftService().GetAllShift();

            List<int> oOverlappingShiftIDs = oShifts.Where(x => x.IsOverlapingDay).Select(x => x.ID).ToList();
            AllowanceDeduction oAttnLunchAssistanceAllowance = oAllDeducts.FirstOrDefault(x => x.Code.Trim().ToUpper() == "015" && x.AllowOrDeductType == EnumAllowOrDeduct.Allowance);
            string lunchAllowDaysString = new SystemConfigarationService().GetconfigStringValue(EnumConfigurationType.Logic, "attendence", "lunchallowanceday");
            DayOfWeek lunchAllowanceDOW;
            if (!Enum.TryParse(lunchAllowDaysString, out lunchAllowanceDOW)) lunchAllowanceDOW = DayOfWeek.Friday;

            string tiffinAllowanceCodeString = new SystemConfigarationService().GetconfigStringValue(EnumConfigurationType.Logic, "attendence", "nightshiftcodes");
            List<string> tiffinAllowanceCodes = tiffinAllowanceCodeString.Trim().Split(',').ToList();
            List<int> oNightShiftIDs = oShifts.Where(x => tiffinAllowanceCodes.Contains(x.Code.Trim())).Select(x => x.ID).ToList();

            List<ADParameter> _Adparameters = new ADParameterService().Get(EnumStatus.Active, EnumAllowOrDeduct.Allowance, payrollTypeID).Where(x => x.AllowDeductID == 4).ToList(); // AllowDeductID = 4 is Extra Allowance in ALLOWANCEDEDUCTION table
            //AllowanceDeduction oAttnExtraAllowance = oAllDeducts.FirstOrDefault(x => x.Code.Trim().ToUpper() == "004" && x.AllowOrDeductType == EnumAllowOrDeduct.Allowance);
            //_Adparameters = new ADParameterService().Get(EnumStatus.Active, EnumAllowOrDeduct.Allowance).Where(x => x.AllowDeductID == ID.FromInteger(4)).ToList(); // AllowDeductID = 4 is Extra Allowance in ALLOWANCEDEDUCTION table
            List<Grade> ogrades = new GradeService().GetAllPayrollTypes(EnumStatus.Regardless);

            foreach (DataRow drEmployee in dsEmployee.Tables[0].Rows)
            {

                for (DateTime currentMonth = dFromDate.LastDateOfMonth(); currentMonth <= dToDate; currentMonth = currentMonth.AddDays(1).LastDateOfMonth())
                {
                    var firstDateOfMonth = currentMonth.FirstDateOfMonth();
                    var lastDateOfMonth = currentMonth.LastDateOfMonth();
                    var month = currentMonth.ToString("MMM yyyy");
                    double totalOTHour = 0;
                    double totalLateHour = 0;
                    var employee = employees.FirstOrDefault(x => x.ID == Convert.ToInt32(drEmployee["EmployeeID"].ToString()));
                    if (employee == null)
                    {
                        continue;
                    }
                    var empDailyAttnProcess = dAttnProcessess.Where(x => x.EmployeeID == employee.ID &&
                                                                         x.AttnDate >= firstDateOfMonth && x.AttnDate <= lastDateOfMonth).ToList();
                    if (empDailyAttnProcess.Count > 0)
                    {
                        GetEmpDailyAttn(employee, empDailyAttnProcess, dTableChild, month, out totalOTHour, out totalLateHour, _adps, _Adparameters, oShiftIDs, oShiftIDsSpecial, oNationalHolidays,
                            lunchAllowanceDOW, oOverlappingShiftIDs, oNightShiftIDs, ogrades, oLeaves, oShifts);

                        var dRowParent = dTableParent.NewRow();

                        dRowParent["EmpNo"] = employee.EmployeeNo.ToString();
                        dRowParent["Month"] = month;
                        dRowParent["Name"] = drEmployee["Name"].ToString();
                        dRowParent["Designation"] = drEmployee["Designation"].ToString();
                        dRowParent["JoiningDate"] = Convert.ToDateTime(drEmployee["JoiningDate"].ToString()).ToString("dd MMM yyyy");
                        dRowParent["Department"] = drEmployee["Department"].ToString();
                        dRowParent["Section"] = drEmployee["Section"].ToString();
                        dRowParent["Floor"] = drEmployee["Floor"].ToString();
                        dRowParent["TotalOT"] = GlobalFunctions.ConvertDoubleHourToHourMinute(totalOTHour);
                        dRowParent["TotalLateHour"] = GlobalFunctions.ConvertDoubleHourToHourMinute(totalLateHour);
                        dRowParent["FromDate"] = firstDateOfMonth.ToString("dd MMM yyyy");
                        dRowParent["ToDate"] = lastDateOfMonth.ToString("dd MMM yyyy");
                        dTableParent.Rows.Add(dRowParent);
                    }

                }
            }
            DataSet dSetParent = new DataSet();
            dTableParent.TableName = "AttendenceDataSet_EmpDailyAttnParent";
            dSetParent.Tables.Add(dTableParent);

            DataSet dSetChild = new DataSet();
            dTableChild.TableName = "AttendenceDataSet_EmpDailyAttn";
            dSetChild.Tables.Add(dTableChild);
            string RDLC = "HRM.Report.Attendence.RDLC.MultipleJobCard.rdlc";
            List<ReportParameter> _parameters = null;
            //new fReportViewer().CommonReportView(_selectedParameter.ReportItem, dSetParent, dSetChild, RDLC, null, true);
            return new ReportProcessor().CommonReportView(null, RDLC, dSetParent, dSetChild, _parameters, true, payrollTypeID, reportType);

        }
        public void GetEmpDailyAttn(Employee employee, List<DailyAttnProcess> dAttnProcessess, Attendence.AttendenceDataSet.AttendenceDataSet.EmpDailyAttnDataTable dTableChild, string Month, out double totalOTHour, out double totalLateHour,
            List<ADParameter> _adps, List<ADParameter> _Adparameters, List<int> oShiftIDs, List<int> oShiftIDsSpecial, List<AttnNationalHoliday> oNationalHolidays,
            DayOfWeek lunchAllowanceDOW, List<int> oOverlappingShiftIDs, List<int> oNightShiftIDs,
            List<Grade> ogrades, List<Leave> oLeaves, List<Shift> oShifts)
        {
            DateTime fromDate = DateTime.Now;
            if (dAttnProcessess != null && dAttnProcessess.Count > 0)
            {
                fromDate = dAttnProcessess[0].AttnDate;
            }

            totalOTHour = 0; totalLateHour = 0;
            
            string sLeaveName = string.Empty;

            Employee emp = new EmployeeService().Get(employee.ID);
            //string sExtraAllowanceHour = Ease.CoreV35.Utility.ConfigUtility.GetAppSettings("ExtraAllowanceHour");
            //double dExtraAllowanceHours = 0;
            //if (!double.TryParse(sExtraAllowanceHour, out dExtraAllowanceHours))
            //{
            //    dExtraAllowanceHours = 13.5; // Default if Hour not given
            //}
            double dExtraAllowanceHours = 13.5;
            DateTime? startTime, endTime;

            string shortAttnType = "";
            if (!(dAttnProcessess == null || dAttnProcessess.Count <= 0))
            {
                foreach (DailyAttnProcess dAttnProcess in dAttnProcessess)
                {
                    sLeaveName = string.Empty;
                    StringBuilder sRemarks;
                    DataRow Rowbody = dTableChild.NewRow();
                    DailyAttnProcess dap = dAttnProcessess.Where(x => x.ShiftID != null &&
                                                                    x.ShiftID != 0 &&
                                                                    oShiftIDs.Contains(Convert.ToInt32(x.ShiftID)) &&
                                                                    x.AttenType != EnumAttendanceType.Absent &&
                                                                    x.AttenType != EnumAttendanceType.Holiday &&
                                                                    x.AttenType != EnumAttendanceType.Leave &&
                                                                    x.AttenType != EnumAttendanceType.WeeklyHoliday
                                                                    && x.AttnDate == dAttnProcess.AttnDate).FirstOrDefault();
                    Rowbody["NightShiftAllowance"] = dap != null ? 1 : 0;
                    DailyAttnProcess dapSpecial = dAttnProcessess.Where(x => x.ShiftID != null &&
                                                                    x.ShiftID != 0 &&
                                                                    oShiftIDsSpecial.Contains(Convert.ToInt32(x.ShiftID)) &&
                                                                    x.AttenType != EnumAttendanceType.Absent &&
                                                                    x.AttenType != EnumAttendanceType.Holiday &&
                                                                    x.AttenType != EnumAttendanceType.Leave &&
                                                                    x.AttenType != EnumAttendanceType.WeeklyHoliday && x.AttnDate == dAttnProcess.AttnDate).FirstOrDefault();
                    Rowbody["SpecialAllowance"] = dapSpecial != null ? 1 : 0;
                    Rowbody["EmployeeNo"] = employee.EmployeeNo.ToString();
                    Rowbody["Month"] = Month;

                    Rowbody["Date"] = dAttnProcess.AttnDate.ToString("dd MMM yy");
                    Rowbody["Day"] = dAttnProcess.AttnDate.ToString("ddd");
                    if (dAttnProcess.InTime == DateTime.MinValue || dAttnProcess.InTime == null)
                    {
                        Rowbody["InTime"] = "00:00";
                    }
                    else
                    {
                        Rowbody["InTime"] = ((DateTime)dAttnProcess.InTime).ToString("HH:mm:ss");
                    }
                    if (dAttnProcess.OutTime == DateTime.MinValue || dAttnProcess.OutTime == null)
                    {
                        Rowbody["OutTime"] = "00:00";
                    }
                    else
                    {
                        Rowbody["OutTime"] = ((DateTime)dAttnProcess.OutTime).ToString("HH:mm:ss");
                    }


                    totalLateHour += dAttnProcess.LateHour;

                    Rowbody["LateBy"] = GlobalFunctions.ConvertDoubleHourToHourMinute(dAttnProcess.LateHour);

                    totalOTHour += dAttnProcess.OTHour;
                    Rowbody["OTHr"] = GlobalFunctions.ConvertDoubleHourToHourMinute(dAttnProcess.OTHour);
                    shortAttnType = GlobalFunctions.GetShortAttnType(dAttnProcess.AttenType);
                    Rowbody["Status"] = shortAttnType;
                    AttnNationalHoliday nh = oNationalHolidays.Find(x => dAttnProcess.AttnDate >= x.FromDate && dAttnProcess.AttnDate <= x.ToDate);
                    if (nh != null)
                        Rowbody["Status"] = "N";

                    Rowbody["Lunch"] = 0;
                    //if (dAttnProcess.AttnDate != Convert.ToDateTime("18 Feb 2022") &&
                    //    dAttnProcess.AttnDate != Convert.ToDateTime("25 Feb 2022") &&
                    //    dAttnProcess.AttnDate != Convert.ToDateTime("29 Apr 2022") &&
                    //    dAttnProcess.AttnDate != Convert.ToDateTime("27 May 2022") &&
                    //    dAttnProcess.AttnDate != Convert.ToDateTime("10 Jun 2022") &&
                    //    dAttnProcess.AttnDate != Convert.ToDateTime("24 Jun 2022") &&
                    //    dAttnProcess.AttnDate != Convert.ToDateTime("05 Aug 2022") &&
                    //    dAttnProcess.AttnDate != Convert.ToDateTime("12 Aug 2022") &&
                    //    dAttnProcess.AttnDate != Convert.ToDateTime("19 Aug 2022"))
                    //{
                    //    if (dAttnProcess.AttnDate.DayOfWeek == lunchAllowanceDOW &&
                    //                    dAttnProcess.AttenType != EnumAttendanceType.Absent &&
                    //                    dAttnProcess.AttenType != EnumAttendanceType.Holiday &&
                    //                    dAttnProcess.AttenType != EnumAttendanceType.Leave &&
                    //                    dAttnProcess.AttenType != EnumAttendanceType.WeeklyHoliday &&
                    //                    !oOverlappingShiftIDs.Contains((dAttnProcess.ShiftID != null && !dAttnProcess.ShiftID.IsUnassigned) ? dAttnProcess.ShiftID : 0))
                    //    {
                    //        Rowbody["Lunch"] = 1;
                    //    }
                    //}
                    if (dAttnProcess.AttnDate.DayOfWeek == lunchAllowanceDOW &&
                        dAttnProcess.AttenType != EnumAttendanceType.Absent &&
                        dAttnProcess.AttenType != EnumAttendanceType.Holiday &&
                        dAttnProcess.AttenType != EnumAttendanceType.Leave &&
                        dAttnProcess.AttenType != EnumAttendanceType.WeeklyHoliday &&
                        !oOverlappingShiftIDs.Contains((dAttnProcess.ShiftID != null && dAttnProcess.ShiftID != 0) ? Convert.ToInt32(dAttnProcess.ShiftID) : 0))
                    {
                        Rowbody["Lunch"] = 1;
                    }

                    Rowbody["Tiffin"] = 0;
                    if (dAttnProcess.ShiftID != null &&
                         dAttnProcess.ShiftID != 0 &&
                         oNightShiftIDs.Contains(Convert.ToInt32(dAttnProcess.ShiftID)) &&
                         dAttnProcess.AttenType != EnumAttendanceType.Absent &&
                         dAttnProcess.AttenType != EnumAttendanceType.Holiday &&
                         dAttnProcess.AttenType != EnumAttendanceType.Leave &&
                         dAttnProcess.AttenType != EnumAttendanceType.WeeklyHoliday)
                    {
                        Rowbody["Tiffin"] = 1;
                    }
                    ADParameter ad = _adps.Where(x => x.AllowanceDeduction.Code == "016").FirstOrDefault();
                    if (ad != null && ad.NotApplicable != null && ad.NotApplicable.Count > 0)
                    {
                        ADParameterEmployee adpe = ad.NotApplicable.Where(x => x.EmployeeID == emp.ID).FirstOrDefault();
                        if (adpe != null)
                        {
                            Rowbody["Tiffin"] = 0;
                        }

                    }
                    Rowbody["ExtraAllowance"] = 0;
                    if (_Adparameters != null && emp != null)
                    {
                        foreach (ADParameter adparam in _Adparameters)
                        {
                            foreach (ADParameter.ADParameterGrade grn in adparam.ADParameterGrades)
                            {
                                //Grade gr = ogrades.GetItem(grn.GradeID);
                                Grade gr = ogrades.Where(x => x.ID == grn.GradeID).FirstOrDefault();
                                if (gr != null && gr.ID == emp.GradeID)
                                {
                                    if (/*dAttnProcess.InTime != DateTime.MinValue ||*/ dAttnProcess.InTime != null)
                                    {
                                        Shift sft = oShifts.FirstOrDefault(x => x.ID == dAttnProcess.ShiftID);
                                        if (sft != null || dAttnProcess.ShiftID != null)
                                        {
                                            startTime = dAttnProcess.InTime.Value.Add(sft.InTime.TimeOfDay);

                                            startTime = startTime.Value.AddMinutes(-15) > dAttnProcess.InTime ? startTime.Value.AddMinutes(-15) : dAttnProcess.InTime;

                                            endTime = dAttnProcess.OutTime;
                                            if (endTime != null)
                                            {
                                                if (endTime.Value.Subtract(startTime.Value).Add(TimeSpan.FromMinutes(1)).TotalHours >= dExtraAllowanceHours)
                                                {
                                                    Rowbody["ExtraAllowance"] = 1;
                                                }
                                            }

                                        }

                                    }
                                }
                            }
                        }
                    }

                    if (dAttnProcess.AttenType == EnumAttendanceType.Leave)
                    {
                        var oLeave = oLeaves.FirstOrDefault(x => x.ID == dAttnProcess.ReferenceID);
                        if (oLeave != null)
                        {
                            sLeaveName = oLeave.Description;
                        }
                    }

                    sRemarks = new StringBuilder();
                    sRemarks.AppendFormat("{0}.", sLeaveName);
                    sRemarks.AppendFormat("{0}.", dAttnProcess.Comments);
                    Rowbody["Remarks"] = sRemarks.ToString().Trim('.');
                    Shift oSft = oShifts.Where(o => o.ID == dAttnProcess.ShiftID).FirstOrDefault();
                    if (oSft != null)
                    {
                        Rowbody["Shift"] = oSft.ShortName;
                    }
                    else
                    {
                        Rowbody["Shift"] = string.Empty;
                    }
                    Rowbody["IsManualEntry"] = dAttnProcess.IsManualEntry;
                    dTableChild.Rows.Add(Rowbody);
                }
            }

        }
        #endregion

        #region Attendance Information
        public byte[] GetEmpAttenInfo(int payrollTypeID, string sEmpIDs, string reportType)
        {
            ReportProcessor form = new ReportProcessor();
            DataSet oEmpAttenInfo = null;
            DataRow oDR = null;
            oEmpAttenInfo = new DailyAttnProcessService().GetEmpAttenInfo(sEmpIDs);

            Attendence.AttendenceDataSet.AttendenceDataSet.EmpAttenInfoDataTable dTable = new Attendence.AttendenceDataSet.AttendenceDataSet.EmpAttenInfoDataTable();
            //int serial = 1;

            foreach (DataRow Dr in oEmpAttenInfo.Tables[0].Rows)
            {
                oDR = dTable.NewRow();

                //oDR["Serial"] = serial.ToString();
                oDR["EmpNo"] = Dr["EMPLOYEENO"];
                oDR["EmpName"] = Dr["Name"];
                oDR["AccessCardID"] = Dr["CardNumber"];
                oDR["Shift"] = Dr["ShortName"];
                oDR["WorkPlanGroup"] = Dr["Name1"];
                oDR["DeptName"] = Dr["Department"].ToString();
                oDR["Section"] = Dr["Section"].ToString();
                oDR["Line"] = Dr["Line"].ToString();
                oDR["Floor"] = Dr["Floor"].ToString();
                dTable.Rows.Add(oDR);
                //serial++;
            }
            DataSet dSet = new DataSet();
            dTable.TableName = "AttendenceDataSet_EmpAttenInfo";
            string RDLC = "EmpAttenInfo.rdlc";
            dSet.Tables.Add(dTable);
            
            return form.CommonReportViewForReports(null, dSet, null, RDLC, null, true, payrollTypeID, reportType);
        }
        #endregion

        #region DailyInOut
        public byte[] ShowDailyInOut(DateTime dFromDate, string sEmpID, string reportType, int payrollTypeID)
        {
            ReportProcessor reportProcessor = new ReportProcessor();
            int position = 0;

            DateTime attnDate = dFromDate;
            DateTime PreviousAttnDate = attnDate.AddDays(-1);
            DataSet oDailyInOut = null;
            DataSet oPreviousDayInOut = null;
            DataRow oDR = null;
            oDailyInOut = new EchoTexExceptionReportService().GetDailyInOut(attnDate, sEmpID);
            oPreviousDayInOut = new EchoTexExceptionReportService().GetDailyInOut(PreviousAttnDate, sEmpID);
            position = 1;
            //DailyAttnProcess dailyData = null;
            Attendence.AttendenceDataSet.AttendenceDataSet.DailyInOutDataTable dTable = new Attendence.AttendenceDataSet.AttendenceDataSet.DailyInOutDataTable();

            foreach (DataRow Dr in oDailyInOut.Tables[0].Rows)
            {
                oDR = dTable.NewRow();
                DataRow dailyData = oPreviousDayInOut.Tables[0].AsEnumerable()
                                               .Where(x => x["EMPLOYEENO"].ToString() == Dr["EMPLOYEENO"].ToString()).FirstOrDefault();
                string previousShift = dailyData == null ? "" : dailyData["Shift"].ToString();
                oDR["EmployeeNo"] = Dr["EMPLOYEENO"];
                oDR["Name"] = Dr["Name"];
                position = 2;
                oDR["PreviousDayShift"] = previousShift;
                oDR["Designation"] = Dr["Designation"];
                position = 3;
                oDR["InTime"] = Dr["InTime"] is DBNull ? "00:00" : Convert.ToDateTime(Dr["InTime"]).ToString("HH:mm");
                oDR["OutTime"] = Dr["OutTime"] is DBNull ? "00:00" : Convert.ToDateTime(Dr["OutTime"]).ToString("HH:mm");
                oDR["ShiftInTime"] = Dr["ShiftInTime"] is DBNull ? "00:00" : Convert.ToDateTime(Dr["ShiftInTime"]).ToString("HH:mm");
                oDR["ShiftOutTime"] = Dr["ShiftOutTime"] is DBNull ? "00:00" : Convert.ToDateTime(Dr["ShiftOutTime"]).ToString("HH:mm");
                position = 3;
                oDR["Department"] = Dr["Department"].ToString();
                oDR["Section"] = Dr["Section"].ToString();
                oDR["Line"] = Dr["Line"].ToString();
                oDR["Floor"] = Dr["Floor"].ToString();
                position = 4;
                oDR["EmpType"] = Dr["EmpType"].ToString();
                oDR["Status"] = GlobalFunctions.GetShortAttnType((EnumAttendanceType)Convert.ToInt32(Dr["Status"].ToString()));
                oDR["OTHour"] = GlobalFunctions.ConvertDoubleHourToHourMinute(Convert.ToDouble(Dr["OTHour"].ToString()));
                oDR["OTHourDBL"] = Convert.ToDouble(Dr["OTHour"].ToString());
                oDR["DeptID"] = Convert.ToInt32(Dr["DeptID"].ToString());
                position = 5;
                oDR["DeptName"] = Dr["DeptName"].ToString();
                oDR["Shift"] = Dr["Shift"].ToString();
                oDR["CardNo"] = Dr["CardNo"].ToString();

                dTable.Rows.Add(oDR);
            }
            position = 6;

            DataSet dSet = new DataSet();
            dTable.TableName = "AttendenceDataSet_DailyInOut";
            dSet.Tables.Add(dTable);

            string RDLC = "DailyInOutEcho.rdlc";

            ReportParameter rParam;
            List<ReportParameter> _reportParameters = new List<ReportParameter>();
            rParam = new ReportParameter("AttnDate", attnDate.ToString("dd MMM yyyy"));
            _reportParameters.Add(rParam);
            position = 7;

            return reportProcessor.AttendanceReportsView(null, dSet, null, RDLC, _reportParameters, true, payrollTypeID, reportType);

        }
        #endregion

        #region DailyAttenSummary
        public byte[] ShowDailyAttnSummary(DateTime dFromDate, string sEmpID, string reportType, int payrollTypeID)
        {
            ReportProcessor reportProcessor = new ReportProcessor();
            DateTime attnDate = dFromDate;
            double totalMale = 0, totalFemale = 0, totalOther = 0;
            DataSet oDailyAttnSummary = null;
            oDailyAttnSummary = new EchoTexExceptionReportService().GetDailyAttnSummary(attnDate, sEmpID);

            totalMale = oDailyAttnSummary.Tables[0].AsEnumerable()
                                                   .Where(x => Convert.ToInt32(x["GenderSerial"]) == (int)EnumGender.Male)
                                                   .Sum(x => Convert.ToDouble(x["HeadCount"].ToString()));
            totalFemale = oDailyAttnSummary.Tables[0].AsEnumerable()
                                                   .Where(x => Convert.ToInt32(x["GenderSerial"]) == (int)EnumGender.Female)// && Convert.ToInt32(x["StatusSerial"]) == 0)
                                                   .Sum(x => Convert.ToDouble(x["HeadCount"].ToString()));
            totalOther = oDailyAttnSummary.Tables[0].AsEnumerable()
                                                               .Where(x => Convert.ToInt32(x["GenderSerial"]) == (int)EnumGender.Other)
                                                               .Sum(x => Convert.ToDouble(x["HeadCount"].ToString()));

            string RDLC = "DailyAttnSummary.rdlc";
            ReportParameter rParam;
            List<ReportParameter> _reportParameters = new List<ReportParameter>();
            rParam = new ReportParameter("AttnDate", attnDate.ToString("dd MMM yyyy"));
            _reportParameters.Add(rParam);

            rParam = new ReportParameter("TotalMale", totalMale.ToString());
            _reportParameters.Add(rParam);
            rParam = new ReportParameter("TotalFemale", totalFemale.ToString());
            _reportParameters.Add(rParam);
            rParam = new ReportParameter("TotalOther", totalOther.ToString());
            _reportParameters.Add(rParam);

            oDailyAttnSummary.Tables[0].TableName = "tblSummary";

            return reportProcessor.AttendanceReportsView(null, oDailyAttnSummary, null, RDLC, _reportParameters, true, payrollTypeID, reportType);

        }
        #endregion

        #region InOutMissing
        public byte[] ShowInOutMissing(DateTime dFromDate, DateTime dToDate,  string sEmpID, string reportType, int payrollTypeID)
        {
            ReportProcessor reportProcessor = new ReportProcessor();
            DateTime attnFromDate, attnToDate;
            var sinMissingHour = new SystemConfigarationService().GetconfigValue(EnumConfigurationType.Logic, "overtime", "inmissinghour");
            double inMissingHour = 0;
            if (sinMissingHour != null) inMissingHour = Convert.ToDouble(sinMissingHour);

            if (dFromDate <= dToDate)
            {
                attnFromDate = dFromDate;
                attnToDate = dToDate.Date.AddDays(1).AddSeconds(-1);
            }
            else
            {
                attnFromDate = dToDate;
                attnToDate = dFromDate.Date.AddDays(1).AddSeconds(-1);
            }
            List<Shift> shifts = new ShiftService().GetAllShift();
            DataSet oDailyInOut = null;
            DataRow oDR = null;
            oDailyInOut = new EchoTexExceptionReportService().GetDateRangeDataByStatus(attnFromDate, attnToDate, sEmpID, EnumAttendanceType.Present, EnumAttendanceType.Delay, EnumAttendanceType.Late, EnumAttendanceType.Early, EnumAttendanceType.OutSideDuty, EnumAttendanceType.HalfDay);


            Attendence.AttendenceDataSet.AttendenceDataSet.InOutMissingDataTable dTable = new Attendence.AttendenceDataSet.AttendenceDataSet.InOutMissingDataTable();

            DateTime Intime, OutTime, AttnDate, ShiftInTime, ShiftOutTime;


            foreach (DataRow Dr in oDailyInOut.Tables[0].AsEnumerable().Where(x => x["OutTime"] is DBNull || x["InTime"] is DBNull))
            {
                Intime = DateTime.MinValue; OutTime = DateTime.MinValue;
                oDR = dTable.NewRow();

                oDR["EmployeeNo"] = Dr["EMPLOYEENO"];
                oDR["Name"] = Dr["Name"];
                oDR["Designation"] = Dr["Designation"];
                oDR["EmpType"] = Dr["EmpType"].ToString();
                oDR["Status"] = GlobalFunctions.GetShortAttnType((EnumAttendanceType)Convert.ToInt32(Dr["Status"]));
                oDR["OTHour"] = GlobalFunctions.ConvertDoubleHourToHourMinute(Convert.ToDouble(Dr["OTHour"]));
                oDR["OTHourDBL"] = Convert.ToDouble(Dr["OTHour"]);
                oDR["DeptID"] = Convert.ToInt32(Dr["DeptID"].ToString());
                oDR["DeptName"] = Dr["Department"].ToString();
                oDR["Shift"] = Dr["Shift"].ToString();
                oDR["CardNo"] = Dr["CardNo"].ToString();
                oDR["AttnDate"] = Convert.ToDateTime(Dr["AttnDate"]);

                if (Dr["OutTime"] is DBNull)
                {
                    Intime = Convert.ToDateTime(Dr["InTime"]);
                    AttnDate = Intime.Date;
                    oDR["InTime"] = Intime.ToString("HH:mm");
                    oDR["OutTime"] = string.Empty;
                    oDR["MissingStatus"] = "Out Missing";
                }
                else
                {
                    OutTime = Convert.ToDateTime(Dr["OutTime"]);
                    AttnDate = OutTime.Date;
                    oDR["InTime"] = string.Empty;
                    oDR["OutTime"] = OutTime.ToString("HH:mm");
                    oDR["MissingStatus"] = "In Missing";
                }

                oDR["Floor"] = Dr["Floor"].ToString();
                oDR["Section"] = Dr["Section"].ToString();
                oDR["Line"] = Dr["Line"].ToString();

                Shift shft = shifts.SingleOrDefault(x => x.ID == Convert.ToInt32(Dr["ShiftID"].ToString()));
                if (shft != null)
                {

                    ShiftInTime = new DateTime(AttnDate.Year, AttnDate.Month, AttnDate.Day, shft.InTime.Hour, shft.InTime.Minute, shft.InTime.Second);
                    ShiftOutTime = new DateTime(AttnDate.Year, AttnDate.Month, AttnDate.Day, shft.OutTime.Hour, shft.OutTime.Minute, shft.OutTime.Second);
                    if (ShiftInTime > ShiftOutTime)
                        ShiftOutTime = ShiftOutTime.AddDays(1);

                    oDR["ShiftIn"] = ShiftInTime.ToString("HH:mm");
                    oDR["ShiftOut"] = ShiftOutTime.ToString("HH:mm");

                    if (Intime == DateTime.MinValue && ShiftInTime.AddHours(inMissingHour) < Intime)
                    {
                        oDR["OutTime"] = oDR["InTime"].ToString();
                        oDR["InTime"] = string.Empty;
                        oDR["MissingStatus"] = "In Missing";
                    }
                }



                dTable.Rows.Add(oDR);
            }

            DataSet dSet = new DataSet();
            dTable.TableName = "AttendenceDataSet_InOutMissing";
            dSet.Tables.Add(dTable);

            string RDLC = "InOutMissing.rdlc";

            ReportParameter rParam;
            List<ReportParameter> _reportParameters = new List<ReportParameter>();
            rParam = new ReportParameter("AttnFromDate", attnFromDate.ToString("dd MMM yyyy"));
            _reportParameters.Add(rParam);
            rParam = new ReportParameter("AttnToDate", attnToDate.ToString("dd MMM yyyy"));
            _reportParameters.Add(rParam);


            return reportProcessor.AttendanceReportsView(null, dSet, null, RDLC, _reportParameters, true, payrollTypeID, reportType);
        }
        #endregion

        #region MonthlyKPI
        public byte[] ShowMonthlyKPI(DateTime dFromDate, DateTime dToDate, string sEmpID, string reportType, int payrollTypeID)
        {
            ReportProcessor reportProcessor = new ReportProcessor();

            DataSet oMonthlyKPIDetail = null;
            oMonthlyKPIDetail = new EchoTexExceptionReportService().GetMonthlyKPIDetail(dFromDate, dToDate, sEmpID);


            DataTable oMnthlyKPIDtlSummary = new AttendenceDataSet.MnthlyKPIDtlSummaryDataTable();

            #region Summary Parts


            if (oMonthlyKPIDetail.Tables.Count > 0 && oMonthlyKPIDetail.Tables[0].Rows.Count > 0)
            {
                var groupedData = oMonthlyKPIDetail.Tables[0]
                                                   .AsEnumerable()
                                                   .GroupBy(x => x.Field<string>("IDNo"))
                                                   .Select(g => new { EmployeeNo = g.Key, OTSum = g.Sum(x => Convert.ToDouble(x["OTHour"].ToString())), OTAvg = g.Sum(x => Convert.ToDouble(x["OTHour"].ToString())) / g.Count(), OTGreaterThan5 = g.Count(x => Convert.ToDouble(x["OTHour"].ToString()) > 5), WH = g.Sum(x => Convert.ToDouble(x["Minutes"].ToString())) })
                                                   .ToList();

                DataRow dRow = oMnthlyKPIDtlSummary.NewRow();
                dRow["ManPower"] = groupedData.Count();
                dRow["PerAvgOTGreater2"] = groupedData.Count(x => x.OTAvg > 2);
                dRow["PerSumOTGreater75"] = groupedData.Count(x => x.OTSum > 75);
                dRow["PerSumOTGreater100"] = groupedData.Count(x => x.OTSum > 100);
                dRow["PerSumOTGreater52"] = groupedData.Count(x => x.OTSum > 52);
                dRow["PerOneOTGreater5"] = groupedData.Count(x => x.OTGreaterThan5 > 0);
                double wh = groupedData.Sum(c => c.WH);
                oMnthlyKPIDtlSummary.Rows.Add(dRow);

            }
            #endregion

            oMnthlyKPIDtlSummary.TableName = "MnthlyKPIDtlSummary";
            oMonthlyKPIDetail.Tables.Add(oMnthlyKPIDtlSummary);

            string RDLC = "rptMonthlyKPI.rdlc";

            List<ReportParameter> _parameters = new List<ReportParameter>();
            ReportParameter rParam = new ReportParameter("FromDate", dFromDate.ToString("dd MMM yyyy"));
            _parameters.Add(rParam);
            rParam = new ReportParameter("ToDate", dToDate.LastDateOfMonth().ToString("dd MMM yyyy"));
            _parameters.Add(rParam);

            return reportProcessor.AttendanceReportsView(null, oMonthlyKPIDetail, null, RDLC, _parameters, true, payrollTypeID, reportType);
        }
        #endregion

        #endregion
    }
}