
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class EmployeesDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const employees = await db.employees.create(
            {
                id: data.id || undefined,
        
        employeeCode: data.employeeCode
        ||
        null
            ,
            
        firstName: data.firstName
        ||
        null
            ,
            
        middleName: data.middleName
        ||
        null
            ,
            
        lastName: data.lastName
        ||
        null
            ,
            
        nameExtension: data.nameExtension
        ||
        null
            ,
            
        dateOfBirth: data.dateOfBirth
        ||
        null
            ,
            
        placeOfBirth: data.placeOfBirth
        ||
        null
            ,
            
        sex: data.sex
        ||
        null
            ,
            
        civilStatus: data.civilStatus
        ||
        null
            ,
            
        nationality: data.nationality
        ||
        null
            ,
            
        religion: data.religion
        ||
        null
            ,
            
        bloodType: data.bloodType
        ||
        null
            ,
            
        homeStreet: data.homeStreet
        ||
        null
            ,
            
        homeBarangay: data.homeBarangay
        ||
        null
            ,
            
        homeCity: data.homeCity
        ||
        null
            ,
            
        homeProvince: data.homeProvince
        ||
        null
            ,
            
        homeZipCode: data.homeZipCode
        ||
        null
            ,
            
        permanentAddressSame: data.permanentAddressSame
        ||
        false
        
            ,
            
        permanentStreet: data.permanentStreet
        ||
        null
            ,
            
        permanentBarangay: data.permanentBarangay
        ||
        null
            ,
            
        permanentCity: data.permanentCity
        ||
        null
            ,
            
        permanentProvince: data.permanentProvince
        ||
        null
            ,
            
        permanentZipCode: data.permanentZipCode
        ||
        null
            ,
            
        personalEmail: data.personalEmail
        ||
        null
            ,
            
        personalMobile: data.personalMobile
        ||
        null
            ,
            
        emergencyContactName: data.emergencyContactName
        ||
        null
            ,
            
        emergencyContactRel: data.emergencyContactRel
        ||
        null
            ,
            
        emergencyContactMobile: data.emergencyContactMobile
        ||
        null
            ,
            
        sssNumber: data.sssNumber
        ||
        null
            ,
            
        philhealthNumber: data.philhealthNumber
        ||
        null
            ,
            
        pagibigNumber: data.pagibigNumber
        ||
        null
            ,
            
        tinNumber: data.tinNumber
        ||
        null
            ,
            
        bankName: data.bankName
        ||
        null
            ,
            
        bankAccountNumber: data.bankAccountNumber
        ||
        null
            ,
            
        bankAccountName: data.bankAccountName
        ||
        null
            ,
            
        employmentDate: data.employmentDate
        ||
        null
            ,
            
        regularizationDate: data.regularizationDate
        ||
        null
            ,
            
        employmentStatus: data.employmentStatus
        ||
        null
            ,
            
        employmentType: data.employmentType
        ||
        null
            ,
            
        jobLevel: data.jobLevel
        ||
        null
            ,
            
        salaryType: data.salaryType
        ||
        null
            ,
            
        basicSalary: data.basicSalary
        ||
        null
            ,
            
        taxStatus: data.taxStatus
        ||
        null
            ,
            
        workLocation: data.workLocation
        ||
        null
            ,
            
        separationDate: data.separationDate
        ||
        null
            ,
            
        separationType: data.separationType
        ||
        null
            ,
            
        separationReason: data.separationReason
        ||
        null
            ,
            
        clearanceStatus: data.clearanceStatus
        ||
        null
            ,
            
        finalPayAmount: data.finalPayAmount
        ||
        null
            ,
            
        finalPayReleasedDate: data.finalPayReleasedDate
        ||
        null
            ,
            
        isActive: data.isActive
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await employees.setDepartment( data.department || null, {
            transaction,
        });
        
        await employees.setPosition( data.position || null, {
            transaction,
        });
        
        await employees.setShift( data.shift || null, {
            transaction,
        });
        
        await employees.setReportingTo( data.reportingTo || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.employees.getTableName(),
                belongsToColumn: 'profilePhoto',
                belongsToId: employees.id,
            },
            data.profilePhoto,
            options,
        );
        

        return employees;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const employeesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                employeeCode: item.employeeCode
            ||
            null
            ,
            
                firstName: item.firstName
            ||
            null
            ,
            
                middleName: item.middleName
            ||
            null
            ,
            
                lastName: item.lastName
            ||
            null
            ,
            
                nameExtension: item.nameExtension
            ||
            null
            ,
            
                dateOfBirth: item.dateOfBirth
            ||
            null
            ,
            
                placeOfBirth: item.placeOfBirth
            ||
            null
            ,
            
                sex: item.sex
            ||
            null
            ,
            
                civilStatus: item.civilStatus
            ||
            null
            ,
            
                nationality: item.nationality
            ||
            null
            ,
            
                religion: item.religion
            ||
            null
            ,
            
                bloodType: item.bloodType
            ||
            null
            ,
            
                homeStreet: item.homeStreet
            ||
            null
            ,
            
                homeBarangay: item.homeBarangay
            ||
            null
            ,
            
                homeCity: item.homeCity
            ||
            null
            ,
            
                homeProvince: item.homeProvince
            ||
            null
            ,
            
                homeZipCode: item.homeZipCode
            ||
            null
            ,
            
                permanentAddressSame: item.permanentAddressSame
            ||
            false
        
            ,
            
                permanentStreet: item.permanentStreet
            ||
            null
            ,
            
                permanentBarangay: item.permanentBarangay
            ||
            null
            ,
            
                permanentCity: item.permanentCity
            ||
            null
            ,
            
                permanentProvince: item.permanentProvince
            ||
            null
            ,
            
                permanentZipCode: item.permanentZipCode
            ||
            null
            ,
            
                personalEmail: item.personalEmail
            ||
            null
            ,
            
                personalMobile: item.personalMobile
            ||
            null
            ,
            
                emergencyContactName: item.emergencyContactName
            ||
            null
            ,
            
                emergencyContactRel: item.emergencyContactRel
            ||
            null
            ,
            
                emergencyContactMobile: item.emergencyContactMobile
            ||
            null
            ,
            
                sssNumber: item.sssNumber
            ||
            null
            ,
            
                philhealthNumber: item.philhealthNumber
            ||
            null
            ,
            
                pagibigNumber: item.pagibigNumber
            ||
            null
            ,
            
                tinNumber: item.tinNumber
            ||
            null
            ,
            
                bankName: item.bankName
            ||
            null
            ,
            
                bankAccountNumber: item.bankAccountNumber
            ||
            null
            ,
            
                bankAccountName: item.bankAccountName
            ||
            null
            ,
            
                employmentDate: item.employmentDate
            ||
            null
            ,
            
                regularizationDate: item.regularizationDate
            ||
            null
            ,
            
                employmentStatus: item.employmentStatus
            ||
            null
            ,
            
                employmentType: item.employmentType
            ||
            null
            ,
            
                jobLevel: item.jobLevel
            ||
            null
            ,
            
                salaryType: item.salaryType
            ||
            null
            ,
            
                basicSalary: item.basicSalary
            ||
            null
            ,
            
                taxStatus: item.taxStatus
            ||
            null
            ,
            
                workLocation: item.workLocation
            ||
            null
            ,
            
                separationDate: item.separationDate
            ||
            null
            ,
            
                separationType: item.separationType
            ||
            null
            ,
            
                separationReason: item.separationReason
            ||
            null
            ,
            
                clearanceStatus: item.clearanceStatus
            ||
            null
            ,
            
                finalPayAmount: item.finalPayAmount
            ||
            null
            ,
            
                finalPayReleasedDate: item.finalPayReleasedDate
            ||
            null
            ,
            
                isActive: item.isActive
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const employees = await db.employees.bulkCreate(employeesData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < employees.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.employees.getTableName(),
                    belongsToColumn: 'profilePhoto',
                    belongsToId: employees[i].id,
                },
                data[i].profilePhoto,
                options,
            );
        }
        

        return employees;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        

        const employees = await db.employees.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.employeeCode !== undefined) updatePayload.employeeCode = data.employeeCode;
        
        
        if (data.firstName !== undefined) updatePayload.firstName = data.firstName;
        
        
        if (data.middleName !== undefined) updatePayload.middleName = data.middleName;
        
        
        if (data.lastName !== undefined) updatePayload.lastName = data.lastName;
        
        
        if (data.nameExtension !== undefined) updatePayload.nameExtension = data.nameExtension;
        
        
        if (data.dateOfBirth !== undefined) updatePayload.dateOfBirth = data.dateOfBirth;
        
        
        if (data.placeOfBirth !== undefined) updatePayload.placeOfBirth = data.placeOfBirth;
        
        
        if (data.sex !== undefined) updatePayload.sex = data.sex;
        
        
        if (data.civilStatus !== undefined) updatePayload.civilStatus = data.civilStatus;
        
        
        if (data.nationality !== undefined) updatePayload.nationality = data.nationality;
        
        
        if (data.religion !== undefined) updatePayload.religion = data.religion;
        
        
        if (data.bloodType !== undefined) updatePayload.bloodType = data.bloodType;
        
        
        if (data.homeStreet !== undefined) updatePayload.homeStreet = data.homeStreet;
        
        
        if (data.homeBarangay !== undefined) updatePayload.homeBarangay = data.homeBarangay;
        
        
        if (data.homeCity !== undefined) updatePayload.homeCity = data.homeCity;
        
        
        if (data.homeProvince !== undefined) updatePayload.homeProvince = data.homeProvince;
        
        
        if (data.homeZipCode !== undefined) updatePayload.homeZipCode = data.homeZipCode;
        
        
        if (data.permanentAddressSame !== undefined) updatePayload.permanentAddressSame = data.permanentAddressSame;
        
        
        if (data.permanentStreet !== undefined) updatePayload.permanentStreet = data.permanentStreet;
        
        
        if (data.permanentBarangay !== undefined) updatePayload.permanentBarangay = data.permanentBarangay;
        
        
        if (data.permanentCity !== undefined) updatePayload.permanentCity = data.permanentCity;
        
        
        if (data.permanentProvince !== undefined) updatePayload.permanentProvince = data.permanentProvince;
        
        
        if (data.permanentZipCode !== undefined) updatePayload.permanentZipCode = data.permanentZipCode;
        
        
        if (data.personalEmail !== undefined) updatePayload.personalEmail = data.personalEmail;
        
        
        if (data.personalMobile !== undefined) updatePayload.personalMobile = data.personalMobile;
        
        
        if (data.emergencyContactName !== undefined) updatePayload.emergencyContactName = data.emergencyContactName;
        
        
        if (data.emergencyContactRel !== undefined) updatePayload.emergencyContactRel = data.emergencyContactRel;
        
        
        if (data.emergencyContactMobile !== undefined) updatePayload.emergencyContactMobile = data.emergencyContactMobile;
        
        
        if (data.sssNumber !== undefined) updatePayload.sssNumber = data.sssNumber;
        
        
        if (data.philhealthNumber !== undefined) updatePayload.philhealthNumber = data.philhealthNumber;
        
        
        if (data.pagibigNumber !== undefined) updatePayload.pagibigNumber = data.pagibigNumber;
        
        
        if (data.tinNumber !== undefined) updatePayload.tinNumber = data.tinNumber;
        
        
        if (data.bankName !== undefined) updatePayload.bankName = data.bankName;
        
        
        if (data.bankAccountNumber !== undefined) updatePayload.bankAccountNumber = data.bankAccountNumber;
        
        
        if (data.bankAccountName !== undefined) updatePayload.bankAccountName = data.bankAccountName;
        
        
        if (data.employmentDate !== undefined) updatePayload.employmentDate = data.employmentDate;
        
        
        if (data.regularizationDate !== undefined) updatePayload.regularizationDate = data.regularizationDate;
        
        
        if (data.employmentStatus !== undefined) updatePayload.employmentStatus = data.employmentStatus;
        
        
        if (data.employmentType !== undefined) updatePayload.employmentType = data.employmentType;
        
        
        if (data.jobLevel !== undefined) updatePayload.jobLevel = data.jobLevel;
        
        
        if (data.salaryType !== undefined) updatePayload.salaryType = data.salaryType;
        
        
        if (data.basicSalary !== undefined) updatePayload.basicSalary = data.basicSalary;
        
        
        if (data.taxStatus !== undefined) updatePayload.taxStatus = data.taxStatus;
        
        
        if (data.workLocation !== undefined) updatePayload.workLocation = data.workLocation;
        
        
        if (data.separationDate !== undefined) updatePayload.separationDate = data.separationDate;
        
        
        if (data.separationType !== undefined) updatePayload.separationType = data.separationType;
        
        
        if (data.separationReason !== undefined) updatePayload.separationReason = data.separationReason;
        
        
        if (data.clearanceStatus !== undefined) updatePayload.clearanceStatus = data.clearanceStatus;
        
        
        if (data.finalPayAmount !== undefined) updatePayload.finalPayAmount = data.finalPayAmount;
        
        
        if (data.finalPayReleasedDate !== undefined) updatePayload.finalPayReleasedDate = data.finalPayReleasedDate;
        
        
        if (data.isActive !== undefined) updatePayload.isActive = data.isActive;
        
        
        updatePayload.updatedById = currentUser.id;

        await employees.update(updatePayload, {transaction});

        
        
        if (data.department !== undefined) {
            await employees.setDepartment(
              
              data.department,
              
              { transaction }
            );
        }
        
        if (data.position !== undefined) {
            await employees.setPosition(
              
              data.position,
              
              { transaction }
            );
        }
        
        if (data.shift !== undefined) {
            await employees.setShift(
              
              data.shift,
              
              { transaction }
            );
        }
        
        if (data.reportingTo !== undefined) {
            await employees.setReportingTo(
              
              data.reportingTo,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.employees.getTableName(),
                belongsToColumn: 'profilePhoto',
                belongsToId: employees.id,
            },
            data.profilePhoto,
            options,
        );
        

        return employees;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const employees = await db.employees.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of employees) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of employees) {
                await record.destroy({transaction});
            }
        });


        return employees;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const employees = await db.employees.findByPk(id, options);

        await employees.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await employees.destroy({
            transaction
        });

        return employees;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const employees = await db.employees.findOne(
            { where },
            { transaction },
        );

        if (!employees) {
            return employees;
        }

        const output = employees.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee_documents_employee = await employees.getEmployee_documents_employee({
            transaction
        });
        
        
        output.time_records_employee = await employees.getTime_records_employee({
            transaction
        });
        
        
        
        
        output.leave_balances_employee = await employees.getLeave_balances_employee({
            transaction
        });
        
        
        output.leave_applications_employee = await employees.getLeave_applications_employee({
            transaction
        });
        
        
        output.employee_loans_employee = await employees.getEmployee_loans_employee({
            transaction
        });
        
        
        
        
        output.payroll_items_employee = await employees.getPayroll_items_employee({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.applicants_convertedEmployee = await employees.getApplicants_convertedEmployee({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.profilePhoto = await employees.getProfilePhoto({
            transaction
        });
        
        
        output.department = await employees.getDepartment({
            transaction
        });
        
        
        output.position = await employees.getPosition({
            transaction
        });
        
        
        output.shift = await employees.getShift({
            transaction
        });
        
        
        output.reportingTo = await employees.getReportingTo({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.departments,
        as: 'department',
        
        where: filter.department ? {
          [Op.or]: [
            { id: { [Op.in]: filter.department.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.department.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.positions,
        as: 'position',
        
        where: filter.position ? {
          [Op.or]: [
            { id: { [Op.in]: filter.position.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.position.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.shifts,
        as: 'shift',
        
        where: filter.shift ? {
          [Op.or]: [
            { id: { [Op.in]: filter.shift.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.shift.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.employees,
        as: 'reportingTo',
        
        where: filter.reportingTo ? {
          [Op.or]: [
            { id: { [Op.in]: filter.reportingTo.split('|').map(term => Utils.uuid(term)) } },
            {
              employeeCode: {
                [Op.or]: filter.reportingTo.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'profilePhoto',
      },

    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            
            if (filter.employeeCode) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'employeeCode',
                        filter.employeeCode,
                    ),
                };
            }
            
            if (filter.firstName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'firstName',
                        filter.firstName,
                    ),
                };
            }
            
            if (filter.middleName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'middleName',
                        filter.middleName,
                    ),
                };
            }
            
            if (filter.lastName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'lastName',
                        filter.lastName,
                    ),
                };
            }
            
            if (filter.nameExtension) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'nameExtension',
                        filter.nameExtension,
                    ),
                };
            }
            
            if (filter.placeOfBirth) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'placeOfBirth',
                        filter.placeOfBirth,
                    ),
                };
            }
            
            if (filter.nationality) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'nationality',
                        filter.nationality,
                    ),
                };
            }
            
            if (filter.religion) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'religion',
                        filter.religion,
                    ),
                };
            }
            
            if (filter.bloodType) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'bloodType',
                        filter.bloodType,
                    ),
                };
            }
            
            if (filter.homeStreet) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'homeStreet',
                        filter.homeStreet,
                    ),
                };
            }
            
            if (filter.homeBarangay) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'homeBarangay',
                        filter.homeBarangay,
                    ),
                };
            }
            
            if (filter.homeCity) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'homeCity',
                        filter.homeCity,
                    ),
                };
            }
            
            if (filter.homeProvince) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'homeProvince',
                        filter.homeProvince,
                    ),
                };
            }
            
            if (filter.homeZipCode) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'homeZipCode',
                        filter.homeZipCode,
                    ),
                };
            }
            
            if (filter.permanentStreet) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'permanentStreet',
                        filter.permanentStreet,
                    ),
                };
            }
            
            if (filter.permanentBarangay) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'permanentBarangay',
                        filter.permanentBarangay,
                    ),
                };
            }
            
            if (filter.permanentCity) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'permanentCity',
                        filter.permanentCity,
                    ),
                };
            }
            
            if (filter.permanentProvince) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'permanentProvince',
                        filter.permanentProvince,
                    ),
                };
            }
            
            if (filter.permanentZipCode) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'permanentZipCode',
                        filter.permanentZipCode,
                    ),
                };
            }
            
            if (filter.personalEmail) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'personalEmail',
                        filter.personalEmail,
                    ),
                };
            }
            
            if (filter.personalMobile) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'personalMobile',
                        filter.personalMobile,
                    ),
                };
            }
            
            if (filter.emergencyContactName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'emergencyContactName',
                        filter.emergencyContactName,
                    ),
                };
            }
            
            if (filter.emergencyContactRel) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'emergencyContactRel',
                        filter.emergencyContactRel,
                    ),
                };
            }
            
            if (filter.emergencyContactMobile) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'emergencyContactMobile',
                        filter.emergencyContactMobile,
                    ),
                };
            }
            
            if (filter.sssNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'sssNumber',
                        filter.sssNumber,
                    ),
                };
            }
            
            if (filter.philhealthNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'philhealthNumber',
                        filter.philhealthNumber,
                    ),
                };
            }
            
            if (filter.pagibigNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'pagibigNumber',
                        filter.pagibigNumber,
                    ),
                };
            }
            
            if (filter.tinNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'tinNumber',
                        filter.tinNumber,
                    ),
                };
            }
            
            if (filter.bankName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'bankName',
                        filter.bankName,
                    ),
                };
            }
            
            if (filter.bankAccountNumber) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'bankAccountNumber',
                        filter.bankAccountNumber,
                    ),
                };
            }
            
            if (filter.bankAccountName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'bankAccountName',
                        filter.bankAccountName,
                    ),
                };
            }
            
            if (filter.workLocation) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'workLocation',
                        filter.workLocation,
                    ),
                };
            }
            
            if (filter.separationReason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'separationReason',
                        filter.separationReason,
                    ),
                };
            }
            
            if (filter.clearanceStatus) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'employees',
                        'clearanceStatus',
                        filter.clearanceStatus,
                    ),
                };
            }
            

            
            

            
            if (filter.dateOfBirthRange) {
                const [start, end] = filter.dateOfBirthRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    dateOfBirth: {
                    ...where.dateOfBirth,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    dateOfBirth: {
                    ...where.dateOfBirth,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.employmentDateRange) {
                const [start, end] = filter.employmentDateRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    employmentDate: {
                    ...where.employmentDate,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    employmentDate: {
                    ...where.employmentDate,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.regularizationDateRange) {
                const [start, end] = filter.regularizationDateRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    regularizationDate: {
                    ...where.regularizationDate,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    regularizationDate: {
                    ...where.regularizationDate,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.basicSalaryRange) {
                const [start, end] = filter.basicSalaryRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    basicSalary: {
                    ...where.basicSalary,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    basicSalary: {
                    ...where.basicSalary,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.separationDateRange) {
                const [start, end] = filter.separationDateRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    separationDate: {
                    ...where.separationDate,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    separationDate: {
                    ...where.separationDate,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.finalPayAmountRange) {
                const [start, end] = filter.finalPayAmountRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    finalPayAmount: {
                    ...where.finalPayAmount,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    finalPayAmount: {
                    ...where.finalPayAmount,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.finalPayReleasedDateRange) {
                const [start, end] = filter.finalPayReleasedDateRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    finalPayReleasedDate: {
                    ...where.finalPayReleasedDate,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    finalPayReleasedDate: {
                    ...where.finalPayReleasedDate,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.sex) {
                where = {
                    ...where,
                sex: filter.sex,
            };
            }
            
            if (filter.civilStatus) {
                where = {
                    ...where,
                civilStatus: filter.civilStatus,
            };
            }
            
            if (filter.permanentAddressSame) {
                where = {
                    ...where,
                permanentAddressSame: filter.permanentAddressSame,
            };
            }
            
            if (filter.employmentStatus) {
                where = {
                    ...where,
                employmentStatus: filter.employmentStatus,
            };
            }
            
            if (filter.employmentType) {
                where = {
                    ...where,
                employmentType: filter.employmentType,
            };
            }
            
            if (filter.jobLevel) {
                where = {
                    ...where,
                jobLevel: filter.jobLevel,
            };
            }
            
            if (filter.salaryType) {
                where = {
                    ...where,
                salaryType: filter.salaryType,
            };
            }
            
            if (filter.taxStatus) {
                where = {
                    ...where,
                taxStatus: filter.taxStatus,
            };
            }
            
            if (filter.separationType) {
                where = {
                    ...where,
                separationType: filter.separationType,
            };
            }
            
            if (filter.isActive) {
                where = {
                    ...where,
                isActive: filter.isActive,
            };
            }
            


      

      

      

      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.employees.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'employees',
                        'employeeCode',
                        query,
                    ),
                ],
            };
        }

        const records = await db.employees.findAll({
            attributes: [ 'id', 'employeeCode' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['employeeCode', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.employeeCode,
        }));
    }

    
};

