function setUser($ids)
 {
     if (is_array($ids)) {
         if (!$this->isNew()) {
             //If needed, delete mappings first.
             $ppsulf = new PayPeriodScheduleUserListFactory();
             $ppsulf->getByPayPeriodScheduleId($this->getId());
             $user_ids = array();
             foreach ($ppsulf as $pay_period_schedule) {
                 $user_id = $pay_period_schedule->getUser();
                 Debug::text('Schedule ID: ' . $pay_period_schedule->getPayPeriodSchedule() . ' User ID: ' . $user_id, __FILE__, __LINE__, __METHOD__, 10);
                 //Delete users that are not selected.
                 if (!in_array($user_id, $ids)) {
                     Debug::text('Deleting User: '******'s that need to be updated.
                     Debug::text('NOT Deleting User: '******'' and isset($user_ids) and !in_array($id, $user_ids)) {
                 $ppsuf = new PayPeriodScheduleUserFactory();
                 $ppsuf->setPayPeriodSchedule($this->getId());
                 $ppsuf->setUser($id);
                 $user_obj = $ulf->getById($id)->getCurrent();
                 if ($this->Validator->isTrue('user', $ppsuf->Validator->isValid(), TTi18n::gettext('Selected Employee is already assigned to another Pay Period') . ' (' . $user_obj->getFullName() . ')')) {
                     $ppsuf->save();
                 }
             }
         }
         return TRUE;
     }
     return FALSE;
 }
    function getSearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        //Debug::Arr($order,'aOrder Data:', __FILE__, __LINE__, __METHOD__,10);
        $additional_order_fields = array('name', 'description', 'last_name', 'start_date', 'user_id');
        if ($order == NULL) {
            $order = array('c.start_date' => 'asc', 'cb.user_id' => 'desc', 'a.week' => 'asc');
            $strict = FALSE;
        } else {
            $strict = TRUE;
        }
        if (isset($filter_data['exclude_user_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_user_ids'];
        }
        //This is used by Flex Schedule Summary report.
        if (isset($filter_data['include_user_id'])) {
            $filter_data['id'] = $filter_data['include_user_id'];
        }
        if (isset($filter_data['include_user_ids'])) {
            $filter_data['id'] = $filter_data['include_user_ids'];
        }
        /*
        if ( isset($filter_data['user_status_ids']) ) {
        	$filter_data['status_id'] = $filter_data['user_status_ids'];
        }
        */
        if (isset($filter_data['user_title_ids'])) {
            $filter_data['title_id'] = $filter_data['user_title_ids'];
        }
        if (isset($filter_data['group_ids'])) {
            $filter_data['group_id'] = $filter_data['group_ids'];
        }
        if (isset($filter_data['default_branch_ids'])) {
            $filter_data['default_branch_id'] = $filter_data['default_branch_ids'];
        }
        if (isset($filter_data['default_department_ids'])) {
            $filter_data['default_department_id'] = $filter_data['default_department_ids'];
        }
        if (isset($filter_data['branch_ids'])) {
            $filter_data['schedule_branch_id'] = $filter_data['branch_ids'];
        }
        if (isset($filter_data['department_ids'])) {
            $filter_data['schedule_department_id'] = $filter_data['department_ids'];
        }
        if (isset($filter_data['schedule_branch_ids'])) {
            $filter_data['schedule_branch_id'] = $filter_data['schedule_branch_ids'];
        }
        if (isset($filter_data['schedule_department_ids'])) {
            $filter_data['schedule_department_id'] = $filter_data['schedule_department_ids'];
        }
        if (isset($filter_data['exclude_job_ids'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_job_ids'];
        }
        if (isset($filter_data['include_job_ids'])) {
            $filter_data['include_job_id'] = $filter_data['include_job_ids'];
        }
        if (isset($filter_data['job_group_ids'])) {
            $filter_data['job_group_id'] = $filter_data['job_group_ids'];
        }
        if (isset($filter_data['job_item_ids'])) {
            $filter_data['job_item_id'] = $filter_data['job_item_ids'];
        }
        //Debug::Arr($order,'bOrder Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $uf = new UserFactory();
        $uwf = new UserWageFactory();
        $rscf = new RecurringScheduleControlFactory();
        $rsuf = new RecurringScheduleUserFactory();
        $rstcf = new RecurringScheduleTemplateControlFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $apf = new AbsencePolicyFactory();
        $ppsuf = new PayPeriodScheduleUserFactory();
        $ppsf = new PayPeriodScheduleFactory();
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $jf = new JobFactory();
            $jif = new JobItemFactory();
        }
        $ph = array('filter_end_date' => $this->db->BindDate($filter_data['end_date']), 'company_id' => $company_id);
        $query = '
					select 	a.*,
							apf.type_id as absence_policy_type_id,
							apf.name as absence_policy,
							cb.user_id as user_id,

							CASE WHEN a.branch_id = -1 THEN d.default_branch_id ELSE a.branch_id END as schedule_branch_id,
							CASE WHEN a.branch_id = -1 THEN bf.name ELSE bfb.name END as schedule_branch,
							CASE WHEN a.department_id = -1 THEN d.default_department_id ELSE a.department_id END as schedule_department_id,
							CASE WHEN a.department_id = -1 THEN df.name ELSE dfb.name END as schedule_department,

							c.start_date as recurring_schedule_control_start_date,
							c.end_date as recurring_schedule_control_end_date,
							c.start_week as recurring_schedule_control_start_week,
							zz.max_week as max_week,
							( (((a.week-1)+zz.max_week-(c.start_week-1))%zz.max_week) + 1) as remapped_week,

							d.first_name as first_name,
							d.last_name as last_name,
							d.default_branch_id as default_branch_id,
							bf.name as default_branch,
							d.default_department_id as default_department_id,
							df.name as default_department,
							d.title_id as title_id,
							utf.name as title,
							d.group_id as group_id,
							ugf.name as "group",
							d.created_by as user_created_by,
							d.hire_date as hire_date,
							d.termination_date as termination_date,

							uw.id as user_wage_id,
							uw.hourly_rate as user_wage_hourly_rate,
							uw.effective_date as user_wage_effective_date,

							ppsf.shift_assigned_day_id as shift_assigned_day_id,

							c.created_by as recurring_schedule_control_created_by
							';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= ',
						x.name as job,
						x.status_id as job_status_id,
						x.manual_id as job_manual_id,
						x.branch_id as job_branch_id,
						x.department_id as job_department_id,
						x.group_id as job_group_id,

						y.name as job_item,
						y.manual_id as job_item_manual_id,
						y.group_id as job_item_group_id';
        }
        //Since when dealing with recurring schedules, we don't have a row for each specific date, so when determining wages
        //we can only use the last wage entered that is earlier than the filter end date.
        //Since in theory committed schedules will occur before todays date anyways, the accuracy won't be off too much unless
        //the end date they specify is really far in the future, and post dated wage entry is also made.
        $query .= '
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ( select z.recurring_schedule_template_control_id, max(z.week) as max_week from recurring_schedule_template as z where deleted = 0 group by z.recurring_schedule_template_control_id ) as zz ON a.recurring_schedule_template_control_id = zz.recurring_schedule_template_control_id
						LEFT JOIN ' . $rstcf->getTable() . ' as b ON a.recurring_schedule_template_control_id = b.id
						LEFT JOIN ' . $rscf->getTable() . ' as c ON a.recurring_schedule_template_control_id = c.recurring_schedule_template_control_id
						LEFT JOIN ' . $rsuf->getTable() . ' as cb ON c.id = cb.recurring_schedule_control_id
						LEFT JOIN ' . $uf->getTable() . ' as d ON cb.user_id = d.id

						LEFT JOIN ' . $ppsuf->getTable() . ' as ppsuf ON d.id = ppsuf.user_id
						LEFT JOIN ' . $ppsf->getTable() . ' as ppsf ON ( ppsuf.pay_period_schedule_id = ppsf.id AND ppsf.deleted = 0 )

						LEFT JOIN ' . $bf->getTable() . ' as bf ON ( d.default_branch_id = bf.id AND bf.deleted = 0)
						LEFT JOIN ' . $bf->getTable() . ' as bfb ON ( a.branch_id = bfb.id AND bfb.deleted = 0)
						LEFT JOIN ' . $df->getTable() . ' as df ON ( d.default_department_id = df.id AND df.deleted = 0)
						LEFT JOIN ' . $df->getTable() . ' as dfb ON ( a.department_id = dfb.id AND dfb.deleted = 0)
						LEFT JOIN ' . $ugf->getTable() . ' as ugf ON ( d.group_id = ugf.id AND ugf.deleted = 0 )
						LEFT JOIN ' . $utf->getTable() . ' as utf ON ( d.title_id = utf.id AND utf.deleted = 0 )
						LEFT JOIN ' . $apf->getTable() . ' as apf ON ( a.absence_policy_id = apf.id AND apf.deleted = 0 )

						LEFT JOIN ' . $uwf->getTable() . ' as uw ON uw.id = (select uwb.id
																	from ' . $uwf->getTable() . ' as uwb
																	where uwb.user_id = cb.user_id
																		and uwb.effective_date <= ?
																		and uwb.deleted = 0
																		order by uwb.effective_date desc limit 1)

						';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= '	LEFT JOIN ' . $jf->getTable() . ' as x ON a.job_id = x.id';
            $query .= '	LEFT JOIN ' . $jif->getTable() . ' as y ON a.job_item_id = y.id';
        }
        $query .= ' where 	b.company_id = ?
					';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND d.id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND d.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_id']) and isset($filter_data['exclude_id'][0]) and !in_array(-1, (array) $filter_data['exclude_id'])) {
            $query .= ' AND d.id not in (' . $this->getListSQL($filter_data['exclude_id'], $ph) . ') ';
        }
        if (isset($filter_data['user_status_id']) and isset($filter_data['user_status_id'][0]) and !in_array(-1, (array) $filter_data['user_status_id'])) {
            $query .= ' AND d.status_id in (' . $this->getListSQL($filter_data['user_status_id'], $ph) . ') ';
        }
        if (isset($filter_data['status_id']) and isset($filter_data['status_id'][0]) and !in_array(-1, (array) $filter_data['status_id'])) {
            $query .= ' AND a.status_id in (' . $this->getListSQL($filter_data['status_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND d.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND d.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND d.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['schedule_branch_id']) and isset($filter_data['schedule_branch_id'][0]) and !in_array(-1, (array) $filter_data['schedule_branch_id'])) {
            $query .= ' AND ( a.branch_id in (' . $this->getListSQL($filter_data['schedule_branch_id'], $ph) . ') OR ( a.branch_id = -1 AND d.default_branch_id in (' . $this->getListSQL($filter_data['schedule_branch_id'], $ph) . ') ) )';
        }
        if (isset($filter_data['schedule_department_id']) and isset($filter_data['schedule_department_id'][0]) and !in_array(-1, (array) $filter_data['schedule_department_id'])) {
            $query .= ' AND ( a.department_id in (' . $this->getListSQL($filter_data['schedule_department_id'], $ph) . ') OR ( a.department_id = -1 AND d.default_department_id in (' . $this->getListSQL($filter_data['schedule_department_id'], $ph) . ') ) )';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND d.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        //Use the job_id in the schedule table so we can filter by '0' or No Job
        if (isset($filter_data['job_id']) and isset($filter_data['job_id'][0]) and !in_array(-1, (array) $filter_data['job_id'])) {
            $query .= ' AND a.job_id in (' . $this->getListSQL($filter_data['job_id'], $ph) . ') ';
        }
        if (isset($filter_data['job_group_id']) and isset($filter_data['job_group_id'][0]) and !in_array(-1, (array) $filter_data['job_group_id'])) {
            if (isset($filter_data['include_job_subgroups']) and (bool) $filter_data['include_job_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['job_group_id'] = $uglf->getByCompanyIdAndGroupIdAndjob_subgroupsArray($company_id, $filter_data['job_group_id'], TRUE);
            }
            $query .= ' AND x.group_id in (' . $this->getListSQL($filter_data['job_group_id'], $ph) . ') ';
        }
        if (isset($filter_data['job_item_id']) and isset($filter_data['job_item_id'][0]) and !in_array(-1, (array) $filter_data['job_item_id'])) {
            $query .= ' AND a.job_item_id in (' . $this->getListSQL($filter_data['job_item_id'], $ph) . ') ';
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '' and isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $start_date_stamp = $this->db->BindDate($filter_data['start_date']);
            $end_date_stamp = $this->db->BindDate($filter_data['end_date']);
            $ph[] = $start_date_stamp;
            $ph[] = $end_date_stamp;
            $ph[] = $start_date_stamp;
            $ph[] = $start_date_stamp;
            $ph[] = $end_date_stamp;
            $ph[] = $start_date_stamp;
            $ph[] = $end_date_stamp;
            $ph[] = $start_date_stamp;
            $ph[] = $end_date_stamp;
            $ph[] = $start_date_stamp;
            $ph[] = $end_date_stamp;
            $ph[] = $start_date_stamp;
            $ph[] = $end_date_stamp;
            $ph[] = $filter_data['end_date'];
            $ph[] = $filter_data['start_date'];
            $query .= ' AND (
								(c.start_date >= ? AND c.start_date <= ? AND c.end_date IS NULL )
								OR
								(c.start_date <= ? AND c.end_date IS NULL )
								OR
								(c.start_date <= ? AND c.end_date >= ? )
								OR
								(c.start_date >= ? AND c.end_date <= ? )
								OR
								(c.start_date >= ? AND c.start_date <= ? )
								OR
								(c.end_date >= ? AND c.end_date <= ? )
								OR
								(c.start_date <= ? AND c.end_date >= ? )
							)
							AND
							(
								( d.hire_date is NULL OR d.hire_date <= ? )
								AND
								( d.termination_date is NULL OR d.termination_date >= ? )
							)
						';
        }
        $query .= '
						AND ( a.deleted = 0 AND b.deleted = 0 AND c.deleted = 0 AND (d.deleted is NULL OR d.deleted = 0 ) )
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        //Debug::Arr($ph,' Query: '. $query, __FILE__, __LINE__, __METHOD__,10);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
    /**
     * Return user records based on advanced filter criteria.
     *
     * @param int $company_id Company ID
     * @param array $filter_data Filter criteria in array('id' => array(1,2), 'last_name' => 'smith' ) format, with possible top level array keys as follows: id, exclude_id, status_id, user_group_id, default_branch_id, default_department_id, title_id, currency_id, permission_control_id, pay_period_schedule_id, policy_group_id, sex_id, first_name, last_name, home_phone, work_phone, country, province, city, address1, address2, postal_code, employee_number, user_name, sin, work_email, home_email, tag, last_login_date, created_by, created_date, updated_by, updated_date
     * @param int $limit Optional. Restrict the number of records returned
     * @param int $page Optional. Specify the page of records to return
     * @param array $where Optional. Additional WHERE clauses in array( 'column' => 'value', 'column' => 'value' ) format.
     * @param array $order Optional. Sort order in array( 'column' => ASC, 'column2' => DESC ) format.
     *
     * @return object $this
     */
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        if (isset($filter_data['user_status_id'])) {
            $filter_data['status_id'] = $filter_data['user_status_id'];
        }
        if (isset($filter_data['include_user_id'])) {
            $filter_data['id'] = $filter_data['include_user_id'];
        }
        if (isset($filter_data['exclude_user_id'])) {
            $filter_data['exclude_id'] = $filter_data['exclude_user_id'];
        }
        //Some of these are passed from Flex Schedule view.
        if (isset($filter_data['default_branch_ids'])) {
            $filter_data['default_branch_id'] = $filter_data['default_branch_ids'];
        }
        if (isset($filter_data['default_department_ids'])) {
            $filter_data['default_department_id'] = $filter_data['default_department_ids'];
        }
        if (isset($filter_data['group_id'])) {
            $filter_data['user_group_id'] = $filter_data['group_id'];
        }
        if (isset($filter_data['user_title_id'])) {
            $filter_data['title_id'] = $filter_data['user_title_id'];
        }
        if (isset($filter_data['user_tag'])) {
            $filter_data['tag'] = $filter_data['user_tag'];
        }
        //$additional_order_fields = array('b.name', 'c.name', 'd.name', 'e.name');
        $additional_order_fields = array('default_branch', 'default_department', 'default_job', 'default_job_item', 'sex', 'user_group', 'title', 'currency', 'permission_control', 'pay_period_schedule', 'policy_group');
        $sort_column_aliases = array('type' => 'type_id', 'status' => 'status_id', 'sex' => 'sex_id', 'full_name' => 'last_name');
        $order = $this->getColumnsFromAliases($order, $sort_column_aliases);
        if ($order == NULL) {
            $order = array('status_id' => 'asc', 'last_name' => 'asc', 'first_name' => 'asc', 'middle_name' => 'asc');
            $strict = FALSE;
        } else {
            //Do order by column conversions, because if we include these columns in the SQL
            //query, they contaminate the data array.
            //Always try to order by status first so INACTIVE employees go to the bottom.
            if (!isset($order['status_id'])) {
                $order = Misc::prependArray(array('status_id' => 'asc'), $order);
            }
            //Always sort by last name,first name after other columns
            if (!isset($order['last_name'])) {
                $order['last_name'] = 'asc';
            }
            if (!isset($order['first_name'])) {
                $order['first_name'] = 'asc';
            }
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $compf = new CompanyFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $cf = new CurrencyFactory();
        $pcf = new PermissionControlFactory();
        $puf = new PermissionUserFactory();
        $ppsuf = new PayPeriodScheduleUserFactory();
        $ppsf = new PayPeriodScheduleFactory();
        $pguf = new PolicyGroupUserFactory();
        $pgf = new PolicyGroupFactory();
        $egf = new EthnicGroupFactory();
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $jf = new JobFactory();
            $jif = new JobItemFactory();
        }
        $ph = array('company_id' => $company_id);
        $query = '
					select
							a.*,
							compf.name as company,
							b.name as default_branch,
							c.name as default_department,
							d.name as user_group,
							e.name as title,
							f.name as currency,
							f.conversion_rate as currency_rate,
							g.id as permission_control_id,
							g.name as permission_control,
							h.id as pay_period_schedule_id,
							h.name as pay_period_schedule,
							i.id as policy_group_id,
							i.name as policy_group,
                            egf.name as ethnic_group, ';
        $query .= Permission::getPermissionIsChildIsOwnerSQL(isset($filter_data['permission_current_user_id']) ? $filter_data['permission_current_user_id'] : 0, 'a.id');
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= '	jf.name as default_job,
						jif.name as default_job_item, ';
        }
        $query .= '			y.first_name as created_by_first_name,
							y.middle_name as created_by_middle_name,
							y.last_name as created_by_last_name,
							z.first_name as updated_by_first_name,
							z.middle_name as updated_by_middle_name,
							z.last_name as updated_by_last_name
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $compf->getTable() . ' as compf ON ( a.company_id = compf.id AND compf.deleted = 0)
						LEFT JOIN ' . $bf->getTable() . ' as b ON ( a.default_branch_id = b.id AND b.deleted = 0)
						LEFT JOIN ' . $df->getTable() . ' as c ON ( a.default_department_id = c.id AND c.deleted = 0)
						LEFT JOIN ' . $ugf->getTable() . ' as d ON ( a.group_id = d.id AND d.deleted = 0 )
						LEFT JOIN ' . $utf->getTable() . ' as e ON ( a.title_id = e.id AND e.deleted = 0 )
						LEFT JOIN ' . $cf->getTable() . ' as f ON ( a.currency_id = f.id AND f.deleted = 0 )
                        LEFT JOIN ' . $egf->getTable() . ' as egf ON ( a.ethnic_group_id = egf.id AND egf.deleted = 0 ) ';
        if (getTTProductEdition() >= TT_PRODUCT_CORPORATE) {
            $query .= '	LEFT JOIN ' . $jf->getTable() . ' as jf ON a.default_job_id = jf.id';
            $query .= '	LEFT JOIN ' . $jif->getTable() . ' as jif ON a.default_job_item_id = jif.id';
        }
        $query .= '		LEFT JOIN
						(
							SELECT g2.*,g1.user_id
							FROM ' . $puf->getTable() . ' as g1, ' . $pcf->getTable() . ' as g2
							WHERE ( g1.permission_control_id = g2.id AND g2.deleted = 0)
						) as g ON ( a.id = g.user_id )
						LEFT JOIN
						(
							SELECT h2.*, h1.user_id
							FROM ' . $ppsuf->getTable() . ' as h1, ' . $ppsf->getTable() . ' as h2
							WHERE ( h1.pay_period_schedule_id = h2.id AND h2.deleted = 0)
						) as h ON ( a.id = h.user_id )
						LEFT JOIN
						(
							SELECT i2.*, i1.user_id
							FROM ' . $pguf->getTable() . ' as i1, ' . $pgf->getTable() . ' as i2
							WHERE ( i1.policy_group_id = i2.id AND i2.deleted = 0)
						) as i ON ( a.id = i.user_id ) ';
        $query .= Permission::getPermissionHierarchySQL($company_id, isset($filter_data['permission_current_user_id']) ? $filter_data['permission_current_user_id'] : 0, 'a.id');
        $query .= '
						LEFT JOIN ' . $this->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $this->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
					where	a.company_id = ?
					';
        $query .= Permission::getPermissionIsChildIsOwnerFilterSQL($filter_data, 'a.id');
        $query .= isset($filter_data['permission_children_ids']) ? $this->getWhereClauseSQL('a.id', $filter_data['permission_children_ids'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['id']) ? $this->getWhereClauseSQL('a.id', $filter_data['id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['exclude_id']) ? $this->getWhereClauseSQL('a.id', $filter_data['exclude_id'], 'not_numeric_list', $ph) : NULL;
        if (isset($filter_data['status']) and trim($filter_data['status']) != '' and !isset($filter_data['status_id'])) {
            $filter_data['status_id'] = Option::getByFuzzyValue($filter_data['status'], $this->getOptions('status'));
        }
        $query .= isset($filter_data['status_id']) ? $this->getWhereClauseSQL('a.status_id', $filter_data['status_id'], 'numeric_list', $ph) : NULL;
        if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
            $uglf = new UserGroupListFactory();
            $filter_data['user_group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['user_group_id'], TRUE);
        }
        $query .= isset($filter_data['user_group_id']) ? $this->getWhereClauseSQL('a.group_id', $filter_data['user_group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['user_group']) ? $this->getWhereClauseSQL('d.name', $filter_data['user_group'], 'text', $ph) : NULL;
        $query .= isset($filter_data['default_branch_id']) ? $this->getWhereClauseSQL('a.default_branch_id', $filter_data['default_branch_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['default_branch']) ? $this->getWhereClauseSQL('b.name', $filter_data['default_branch'], 'text', $ph) : NULL;
        $query .= isset($filter_data['default_department_id']) ? $this->getWhereClauseSQL('a.default_department_id', $filter_data['default_department_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['default_department']) ? $this->getWhereClauseSQL('c.name', $filter_data['default_department'], 'text', $ph) : NULL;
        $query .= isset($filter_data['title_id']) ? $this->getWhereClauseSQL('a.title_id', $filter_data['title_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['title']) ? $this->getWhereClauseSQL('e.name', $filter_data['title'], 'text', $ph) : NULL;
        $query .= isset($filter_data['ethnic_group_id']) ? $this->getWhereClauseSQL('a.ethnic_group_id', $filter_data['ethnic_group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['ethnic_group']) ? $this->getWhereClauseSQL('egf.name', $filter_data['ethnic_group'], 'text', $ph) : NULL;
        $query .= isset($filter_data['currency_id']) ? $this->getWhereClauseSQL('a.currency_id', $filter_data['currency_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['currency']) ? $this->getWhereClauseSQL('f.name', $filter_data['currency'], 'text', $ph) : NULL;
        $query .= isset($filter_data['permission_control_id']) ? $this->getWhereClauseSQL('g.id', $filter_data['permission_control_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['permission_control']) ? $this->getWhereClauseSQL('g.name', $filter_data['permission_control'], 'text', $ph) : NULL;
        $query .= isset($filter_data['pay_period_schedule_id']) ? $this->getWhereClauseSQL('i.pay_period_schedule_id', $filter_data['pay_period_schedule_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['pay_period_schedule']) ? $this->getWhereClauseSQL('h.name', $filter_data['pay_period_schedule'], 'text', $ph) : NULL;
        $query .= isset($filter_data['policy_group_id']) ? $this->getWhereClauseSQL('k.policy_group_id', $filter_data['policy_group_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['policy_group']) ? $this->getWhereClauseSQL('i.name', $filter_data['policy_group'], 'text', $ph) : NULL;
        if (isset($filter_data['sex']) and trim($filter_data['sex']) != '' and !isset($filter_data['sex_id'])) {
            $filter_data['sex_id'] = Option::getByFuzzyValue($filter_data['sex'], $this->getOptions('sex'));
        }
        $query .= isset($filter_data['sex_id']) ? $this->getWhereClauseSQL('a.sex_id', $filter_data['sex_id'], 'text_list', $ph) : NULL;
        $query .= isset($filter_data['first_name']) ? $this->getWhereClauseSQL('a.first_name', $filter_data['first_name'], 'text_metaphone', $ph) : NULL;
        $query .= isset($filter_data['last_name']) ? $this->getWhereClauseSQL('a.last_name', $filter_data['last_name'], 'text_metaphone', $ph) : NULL;
        $query .= isset($filter_data['home_phone']) ? $this->getWhereClauseSQL('a.home_phone', $filter_data['home_phone'], 'phone', $ph) : NULL;
        $query .= isset($filter_data['work_phone']) ? $this->getWhereClauseSQL('a.work_phone', $filter_data['work_phone'], 'phone', $ph) : NULL;
        $query .= isset($filter_data['country']) ? $this->getWhereClauseSQL('a.country', $filter_data['country'], 'upper_text_list', $ph) : NULL;
        $query .= isset($filter_data['province']) ? $this->getWhereClauseSQL('a.province', $filter_data['province'], 'upper_text_list', $ph) : NULL;
        $query .= isset($filter_data['city']) ? $this->getWhereClauseSQL('a.city', $filter_data['city'], 'text', $ph) : NULL;
        $query .= isset($filter_data['address1']) ? $this->getWhereClauseSQL('a.address1', $filter_data['address1'], 'text', $ph) : NULL;
        $query .= isset($filter_data['address2']) ? $this->getWhereClauseSQL('a.address2', $filter_data['address2'], 'text', $ph) : NULL;
        $query .= isset($filter_data['postal_code']) ? $this->getWhereClauseSQL('a.postal_code', $filter_data['postal_code'], 'text', $ph) : NULL;
        $query .= isset($filter_data['employee_number']) ? $this->getWhereClauseSQL('a.employee_number', $filter_data['employee_number'], 'numeric', $ph) : NULL;
        $query .= isset($filter_data['user_name']) ? $this->getWhereClauseSQL('a.user_name', $filter_data['user_name'], 'text', $ph) : NULL;
        $query .= isset($filter_data['sin']) ? $this->getWhereClauseSQL('a.sin', $filter_data['sin'], 'numeric', $ph) : NULL;
        $query .= isset($filter_data['email']) ? 'AND (' . $this->getWhereClauseSQL('a.work_email', $filter_data['email'], 'text', $ph, NULL, FALSE) . ' OR ' . $this->getWhereClauseSQL('a.home_email', $filter_data['email'], 'text', $ph, NULL, FALSE) . ')' : NULL;
        $query .= isset($filter_data['work_email']) ? $this->getWhereClauseSQL('a.work_email', $filter_data['work_email'], 'text', $ph) : NULL;
        $query .= isset($filter_data['home_email']) ? $this->getWhereClauseSQL('a.home_email', $filter_data['home_email'], 'text', $ph) : NULL;
        $query .= isset($filter_data['tag']) ? $this->getWhereClauseSQL('a.id', array('company_id' => $company_id, 'object_type_id' => 200, 'tag' => $filter_data['tag']), 'tag', $ph) : NULL;
        //$query .= ( isset($filter_data['longitude']) ) ? $this->getWhereClauseSQL( 'a.longitude', $filter_data['longitude'], 'numeric', $ph ) : NULL;
        if (isset($filter_data['last_login_date']) and trim($filter_data['last_login_date']) != '') {
            $date_filter = $this->getDateRangeSQL($filter_data['last_login_date'], 'a.last_login_date');
            if ($date_filter != FALSE) {
                $query .= ' AND ' . $date_filter;
            }
            unset($date_filter);
        }
        if (isset($filter_data['created_date']) and trim($filter_data['created_date']) != '') {
            $date_filter = $this->getDateRangeSQL($filter_data['created_date'], 'a.created_date');
            if ($date_filter != FALSE) {
                $query .= ' AND ' . $date_filter;
            }
            unset($date_filter);
        }
        if (isset($filter_data['updated_date']) and trim($filter_data['updated_date']) != '') {
            $date_filter = $this->getDateRangeSQL($filter_data['updated_date'], 'a.updated_date');
            if ($date_filter != FALSE) {
                $query .= ' AND ' . $date_filter;
            }
            unset($date_filter);
        }
        $query .= isset($filter_data['created_by']) ? $this->getWhereClauseSQL(array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph) : NULL;
        $query .= isset($filter_data['updated_by']) ? $this->getWhereClauseSQL(array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph) : NULL;
        $query .= '
						AND ( a.deleted = 0 )
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        //Debug::Arr($ph, 'Query: '. $query, __FILE__, __LINE__, __METHOD__,10);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
    function getByUserIdListAndNotStatusAndStartDateAndEndDate($user_ids, $status_ids, $start_date, $end_date, $where = NULL, $order = NULL)
    {
        /*
        $key = Option::getByValue($status, $this->getOptions('status') );
        if ($key !== FALSE) {
        	$status = $key;
        }
        */
        if ($user_ids == '') {
            return FALSE;
        }
        if ($status_ids == '') {
            return FALSE;
        }
        if ($start_date == '') {
            return FALSE;
        }
        if ($end_date == '') {
            $end_date = TTDate::getTime() + 86400 * 355;
            //Only check ahead one year of open pay periods.
        }
        $ppsf = new PayPeriodScheduleFactory();
        $ppsuf = new PayPeriodScheduleUserFactory();
        $ph = array();
        $user_ids_sql = $this->getListSQL($user_ids, $ph);
        $ph['start_date'] = $this->db->BindTimeStamp($start_date);
        $ph['end_date'] = $this->db->BindTimeStamp($end_date);
        //Start Date arg should be greater then pay period END DATE.
        //So recurring PS amendments start_date can fall anywhere in the pay period and still get applied.
        $query = '
					select 	a.*
					from	' . $this->getTable() . ' as a
					where 	a.pay_period_schedule_id in
						( select distinct(x.pay_period_schedule_id)
							from
									' . $ppsuf->getTable() . ' as x,
									' . $ppsf->getTable() . ' as z
							where x.user_id in ( ' . $user_ids_sql . ' )
								AND z.deleted=0)
						AND a.end_date >= ?
						AND a.start_date <= ?
						AND a.status_id not in ( ' . $this->getListSQL($status_ids, $ph) . ' )
						AND a.deleted=0';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order);
        $this->rs = $this->db->Execute($query, $ph);
        return $this;
    }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        //$additional_order_fields = array('b.name', 'c.name', 'd.name', 'e.name');
        $additional_order_fields = array('default_branch', 'default_department', 'group', 'title', 'currency', 'permission_control', 'pay_period_schedule', 'policy_group');
        $sort_column_aliases = array('type' => 'type_id', 'status' => 'status_id');
        $order = $this->getColumnsFromAliases($order, $sort_column_aliases);
        if ($order == NULL) {
            $order = array('status_id' => 'asc', 'last_name' => 'asc', 'first_name' => 'asc', 'middle_name' => 'asc');
            $strict = FALSE;
        } else {
            //Do order by column conversions, because if we include these columns in the SQL
            //query, they contaminate the data array.
            //Always try to order by status first so INACTIVE employees go to the bottom.
            if (!isset($order['status_id'])) {
                $order = Misc::prependArray(array('status_id' => 'asc'), $order);
            }
            //Always sort by last name,first name after other columns
            if (!isset($order['last_name'])) {
                $order['last_name'] = 'asc';
            }
            if (!isset($order['first_name'])) {
                $order['first_name'] = 'asc';
            }
            $strict = TRUE;
        }
        Debug::Arr($order, 'Order Data:', __FILE__, __LINE__, __METHOD__, 10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $cf = new CurrencyFactory();
        $pcf = new PermissionControlFactory();
        $puf = new PermissionUserFactory();
        $ppsuf = new PayPeriodScheduleUserFactory();
        $ppsf = new PayPeriodScheduleFactory();
        $pguf = new PolicyGroupUserFactory();
        $pgf = new PolicyGroupFactory();
        $ph = array('company_id' => $company_id);
        $query = '
					select 	a.*,
							b.name as default_branch,
							c.name as default_department,
							d.name as group,
							e.name as title,
							f.name as currency,
							g.id as permission_control_id,
							g.name as permission_control,
							h.id as pay_period_schedule_id,
							h.name as pay_period_schedule,
							i.id as policy_group_id,
							i.name as policy_group,
							y.first_name as created_by_first_name,
							y.middle_name as created_by_middle_name,
							y.last_name as created_by_last_name,
							z.first_name as updated_by_first_name,
							z.middle_name as updated_by_middle_name,
							z.last_name as updated_by_last_name
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $bf->getTable() . ' as b ON ( a.default_branch_id = b.id AND b.deleted = 0)
						LEFT JOIN ' . $df->getTable() . ' as c ON ( a.default_department_id = c.id AND c.deleted = 0)
						LEFT JOIN ' . $ugf->getTable() . ' as d ON ( a.group_id = d.id AND d.deleted = 0 )
						LEFT JOIN ' . $utf->getTable() . ' as e ON ( a.title_id = e.id AND e.deleted = 0 )
						LEFT JOIN ' . $cf->getTable() . ' as f ON ( a.currency_id = f.id AND f.deleted = 0 )

						LEFT JOIN
						(
							SELECT g2.*,g1.user_id
							FROM ' . $puf->getTable() . ' as g1, ' . $pcf->getTable() . ' as g2
							WHERE ( g1.permission_control_id = g2.id AND g2.deleted = 0)
						) as g ON ( a.id = g.user_id )
						LEFT JOIN
						(
							SELECT h2.*, h1.user_id
							FROM ' . $ppsuf->getTable() . ' as h1, ' . $ppsf->getTable() . ' as h2
							WHERE ( h1.pay_period_schedule_id = h2.id AND h2.deleted = 0)
						) as h ON ( a.id = h.user_id )
						LEFT JOIN
						(
							SELECT i2.*, i1.user_id
							FROM ' . $pguf->getTable() . ' as i1, ' . $pgf->getTable() . ' as i2
							WHERE ( i1.policy_group_id = i2.id AND i2.deleted = 0)
						) as i ON ( a.id = i.user_id )

						LEFT JOIN ' . $this->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $this->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
					where	a.company_id = ?
					';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND a.id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND a.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_id']) and isset($filter_data['exclude_id'][0]) and !in_array(-1, (array) $filter_data['exclude_id'])) {
            $query .= ' AND a.id not in (' . $this->getListSQL($filter_data['exclude_id'], $ph) . ') ';
        }
        if (isset($filter_data['status_id']) and isset($filter_data['status_id'][0]) and !in_array(-1, (array) $filter_data['status_id'])) {
            $query .= ' AND a.status_id in (' . $this->getListSQL($filter_data['status_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND a.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['group']) and trim($filter_data['group']) != '') {
            $ph[] = strtolower(trim($filter_data['group']));
            $query .= ' AND lower(d.name) LIKE ?';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND a.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch']) and trim($filter_data['default_branch']) != '') {
            $ph[] = strtolower(trim($filter_data['default_branch']));
            $query .= ' AND lower(b.name) LIKE ?';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND a.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department']) and trim($filter_data['default_department']) != '') {
            $ph[] = strtolower(trim($filter_data['default_department']));
            $query .= ' AND lower(c.name) LIKE ?';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND a.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        if (isset($filter_data['title']) and trim($filter_data['title']) != '') {
            $ph[] = strtolower(trim($filter_data['title']));
            $query .= ' AND lower(e.name) LIKE ?';
        }
        if (isset($filter_data['currency_id']) and isset($filter_data['currency_id'][0]) and !in_array(-1, (array) $filter_data['currency_id'])) {
            $query .= ' AND a.currency_id in (' . $this->getListSQL($filter_data['currency_id'], $ph) . ') ';
        }
        if (isset($filter_data['currency']) and trim($filter_data['currency']) != '') {
            $ph[] = strtolower(trim($filter_data['currency']));
            $query .= ' AND lower(f.name) LIKE ?';
        }
        if (isset($filter_data['permission_control_id']) and isset($filter_data['permission_control_id'][0]) and !in_array(-1, (array) $filter_data['permission_control_id'])) {
            $query .= ' AND g.permission_control_id in (' . $this->getListSQL($filter_data['permission_control_id'], $ph) . ') ';
        }
        if (isset($filter_data['permission_control']) and trim($filter_data['permission_control']) != '') {
            $ph[] = strtolower(trim($filter_data['permission_control']));
            $query .= ' AND lower(g.name) LIKE ?';
        }
        if (isset($filter_data['pay_period_schedule_id']) and isset($filter_data['pay_period_schedule_id'][0]) and !in_array(-1, (array) $filter_data['pay_period_schedule_id'])) {
            $query .= ' AND i.pay_period_schedule_id in (' . $this->getListSQL($filter_data['pay_period_schedule_id'], $ph) . ') ';
        }
        if (isset($filter_data['pay_period_schedule']) and trim($filter_data['pay_period_schedule']) != '') {
            $ph[] = strtolower(trim($filter_data['pay_period_schedule']));
            $query .= ' AND lower(h.name) LIKE ?';
        }
        if (isset($filter_data['policy_group_id']) and isset($filter_data['policy_group_id'][0]) and !in_array(-1, (array) $filter_data['policy_group_id'])) {
            $query .= ' AND k.policy_group_id in (' . $this->getListSQL($filter_data['policy_group_id'], $ph) . ') ';
        }
        if (isset($filter_data['policy_group']) and trim($filter_data['policy_group']) != '') {
            $ph[] = strtolower(trim($filter_data['policy_group']));
            $query .= ' AND lower(i.name) LIKE ?';
        }
        if (isset($filter_data['sex']) and trim($filter_data['sex']) != '' and !isset($filter_data['sex_id'])) {
            $filter_data['sex_id'] = Option::getByFuzzyValue($filter_data['sex'], $this->getOptions('sex'));
        }
        if (isset($filter_data['sex_id']) and isset($filter_data['sex_id'][0]) and !in_array(-1, (array) $filter_data['sex_id'])) {
            $query .= ' AND a.sex_id in (' . $this->getListSQL($filter_data['sex_id'], $ph) . ') ';
        }
        if (isset($filter_data['country']) and isset($filter_data['country'][0]) and !in_array(-1, (array) $filter_data['country'])) {
            $query .= ' AND a.country in (' . $this->getListSQL($filter_data['country'], $ph) . ') ';
        }
        if (isset($filter_data['province']) and isset($filter_data['province'][0]) and !in_array(-1, (array) $filter_data['province']) and !in_array('00', (array) $filter_data['province'])) {
            $query .= ' AND a.province in (' . $this->getListSQL($filter_data['province'], $ph) . ') ';
        }
        if (isset($filter_data['city']) and trim($filter_data['city']) != '') {
            $ph[] = strtolower(trim($filter_data['city']));
            $query .= ' AND lower(a.city) LIKE ?';
        }
        if (isset($filter_data['first_name']) and trim($filter_data['first_name']) != '') {
            $ph[] = strtolower(trim($filter_data['first_name']));
            $query .= ' AND lower(a.first_name) LIKE ?';
        }
        if (isset($filter_data['last_name']) and trim($filter_data['last_name']) != '') {
            $ph[] = strtolower(trim($filter_data['last_name']));
            $query .= ' AND lower(a.last_name) LIKE ?';
        }
        if (isset($filter_data['home_phone']) and trim($filter_data['home_phone']) != '') {
            $ph[] = trim($filter_data['home_phone']);
            $query .= ' AND a.home_phone LIKE ?';
        }
        if (isset($filter_data['employee_number']) and trim($filter_data['employee_number']) != '') {
            $ph[] = trim($filter_data['employee_number']);
            $query .= ' AND a.employee_number LIKE ?';
        }
        if (isset($filter_data['user_name']) and trim($filter_data['user_name']) != '') {
            $ph[] = strtolower(trim($filter_data['user_name']));
            $query .= ' AND lower(a.user_name) LIKE ?';
        }
        if (isset($filter_data['sin']) and trim($filter_data['sin']) != '') {
            $ph[] = trim($filter_data['sin']);
            $query .= ' AND a.sin LIKE ?';
        }
        if (isset($filter_data['created_date']) and trim($filter_data['created_date']) != '') {
            $date_filter = $this->getDateRangeSQL($filter_data['created_date'], 'a.created_date');
            if ($date_filter != FALSE) {
                $query .= ' AND ' . $date_filter;
            }
            unset($date_filter);
        }
        if (isset($filter_data['updated_date']) and trim($filter_data['updated_date']) != '') {
            $date_filter = $this->getDateRangeSQL($filter_data['updated_date'], 'a.updated_date');
            if ($date_filter != FALSE) {
                $query .= ' AND ' . $date_filter;
            }
            unset($date_filter);
        }
        if (isset($filter_data['created_by']) and trim($filter_data['created_by']) != '') {
            $ph[] = $ph[] = strtolower(trim($filter_data['created_by']));
            $query .= ' AND (lower(y.first_name) LIKE ? OR lower(y.last_name) LIKE ? ) ';
        }
        if (isset($filter_data['updated_by']) and trim($filter_data['updated_by']) != '') {
            $ph[] = $ph[] = strtolower(trim($filter_data['updated_by']));
            $query .= ' AND (lower(z.first_name) LIKE ? OR lower(z.last_name) LIKE ? ) ';
        }
        $query .= '
						AND ( a.deleted = 0 )
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        Debug::Text('Query: ' . $query, __FILE__, __LINE__, __METHOD__, 10);
        if ($limit == NULL) {
            $this->rs = $this->db->Execute($query, $ph);
        } else {
            $this->rs = $this->db->PageExecute($query, $limit, $page, $ph);
        }
        return $this;
    }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        $additional_order_fields = array('pay_stub_entry_name', 'user_status_id', 'last_name', 'first_name', 'default_branch', 'default_department', 'user_group', 'title');
        $sort_column_aliases = array('user_status' => 'user_status_id', 'status' => 'status_id', 'type' => 'type_id');
        $order = $this->getColumnsFromAliases($order, $sort_column_aliases);
        if ($order == NULL) {
            $order = array('effective_date' => 'desc', 'last_name' => 'asc');
            $strict = FALSE;
        } else {
            //Always sort by effective_date,last name after other columns
            if (!isset($order['effective_date'])) {
                $order['effective_date'] = 'desc';
            }
            if (!isset($order['last_name'])) {
                $order['last_name'] = 'asc';
            }
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        if (strncmp($this->db->databaseType, 'mysql', 5) == 0) {
            $to_timestamp_sql = 'from_unixtime(a.effective_date)';
        } else {
            $to_timestamp_sql = 'to_timestamp(a.effective_date)';
        }
        $uf = new UserFactory();
        $bf = new BranchFactory();
        $df = new DepartmentFactory();
        $ugf = new UserGroupFactory();
        $utf = new UserTitleFactory();
        $pseaf = new PayStubEntryAccountFactory();
        $ppf = new PayPeriodFactory();
        $ppsf = new PayPeriodScheduleFactory();
        $ppsuf = new PayPeriodScheduleUserFactory();
        $ph = array('company_id' => $company_id);
        $query = '
					select 	a.*,
							b.first_name as first_name,
							b.last_name as last_name,
							b.status_id as user_status_id,

							b.default_branch_id as default_branch_id,
							bf.name as default_branch,
							b.default_department_id as default_department_id,
							df.name as default_department,
							b.group_id as group_id,
							ugf.name as user_group,
							b.title_id as title_id,
							utf.name as title,

							pseaf.name as pay_stub_entry_name,

							y.first_name as created_by_first_name,
							y.middle_name as created_by_middle_name,
							y.last_name as created_by_last_name,
							z.first_name as updated_by_first_name,
							z.middle_name as updated_by_middle_name,
							z.last_name as updated_by_last_name
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $uf->getTable() . ' as b ON ( a.user_id = b.id AND b.deleted = 0 )
						LEFT JOIN ' . $bf->getTable() . ' as bf ON ( b.default_branch_id = bf.id AND bf.deleted = 0)
						LEFT JOIN ' . $df->getTable() . ' as df ON ( b.default_department_id = df.id AND df.deleted = 0)
						LEFT JOIN ' . $ugf->getTable() . ' as ugf ON ( b.group_id = ugf.id AND ugf.deleted = 0 )
						LEFT JOIN ' . $utf->getTable() . ' as utf ON ( b.title_id = utf.id AND utf.deleted = 0 )

						LEFT JOIN ' . $pseaf->getTable() . ' as pseaf ON ( a.pay_stub_entry_name_id = pseaf.id AND pseaf.deleted = 0 )
						LEFT JOIN ' . $ppsuf->getTable() . ' as ppsuf ON ( a.user_id = ppsuf.user_id )
						LEFT JOIN ' . $ppsf->getTable() . ' as ppsf ON ( ppsuf.pay_period_schedule_id = ppsf.id AND ppsf.deleted = 0 )
						LEFT JOIN ' . $ppf->getTable() . ' as ppf ON ( ppsuf.pay_period_schedule_id = ppf.pay_period_schedule_id AND ' . $to_timestamp_sql . ' >= ppf.start_date AND ' . $to_timestamp_sql . ' <= ppf.end_date AND ppf.deleted = 0 )

						LEFT JOIN ' . $uf->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
					where	b.company_id = ?
					';
        if (isset($filter_data['permission_children_ids']) and isset($filter_data['permission_children_ids'][0]) and !in_array(-1, (array) $filter_data['permission_children_ids'])) {
            $query .= ' AND b.id in (' . $this->getListSQL($filter_data['permission_children_ids'], $ph) . ') ';
        }
        if (isset($filter_data['user_id']) and isset($filter_data['user_id'][0]) and !in_array(-1, (array) $filter_data['user_id'])) {
            $query .= ' AND b.id in (' . $this->getListSQL($filter_data['user_id'], $ph) . ') ';
        }
        if (isset($filter_data['id']) and isset($filter_data['id'][0]) and !in_array(-1, (array) $filter_data['id'])) {
            $query .= ' AND a.id in (' . $this->getListSQL($filter_data['id'], $ph) . ') ';
        }
        if (isset($filter_data['exclude_id']) and isset($filter_data['exclude_id'][0]) and !in_array(-1, (array) $filter_data['exclude_id'])) {
            $query .= ' AND a.id not in (' . $this->getListSQL($filter_data['exclude_id'], $ph) . ') ';
        }
        if (isset($filter_data['user_id']) and isset($filter_data['user_id'][0]) and !in_array(-1, (array) $filter_data['user_id'])) {
            $query .= ' AND a.user_id in (' . $this->getListSQL($filter_data['user_id'], $ph) . ') ';
        }
        if (isset($filter_data['pay_period_id']) and isset($filter_data['pay_period_id'][0]) and !in_array(-1, (array) $filter_data['pay_period_id'])) {
            $query .= ' AND ppf.id in (' . $this->getListSQL($filter_data['pay_period_id'], $ph) . ') ';
        }
        if (isset($filter_data['group_id']) and isset($filter_data['group_id'][0]) and !in_array(-1, (array) $filter_data['group_id'])) {
            if (isset($filter_data['include_subgroups']) and (bool) $filter_data['include_subgroups'] == TRUE) {
                $uglf = new UserGroupListFactory();
                $filter_data['group_id'] = $uglf->getByCompanyIdAndGroupIdAndSubGroupsArray($company_id, $filter_data['group_id'], TRUE);
            }
            $query .= ' AND b.group_id in (' . $this->getListSQL($filter_data['group_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_branch_id']) and isset($filter_data['default_branch_id'][0]) and !in_array(-1, (array) $filter_data['default_branch_id'])) {
            $query .= ' AND b.default_branch_id in (' . $this->getListSQL($filter_data['default_branch_id'], $ph) . ') ';
        }
        if (isset($filter_data['default_department_id']) and isset($filter_data['default_department_id'][0]) and !in_array(-1, (array) $filter_data['default_department_id'])) {
            $query .= ' AND b.default_department_id in (' . $this->getListSQL($filter_data['default_department_id'], $ph) . ') ';
        }
        if (isset($filter_data['title_id']) and isset($filter_data['title_id'][0]) and !in_array(-1, (array) $filter_data['title_id'])) {
            $query .= ' AND b.title_id in (' . $this->getListSQL($filter_data['title_id'], $ph) . ') ';
        }
        if (isset($filter_data['recurring_ps_amendment_id']) and isset($filter_data['recurring_ps_amendment_id'][0]) and !in_array(-1, (array) $filter_data['recurring_ps_amendment_id'])) {
            $query .= ' AND a.recurring_ps_amendment_id in (' . $this->getListSQL($filter_data['recurring_ps_amendment_id'], $ph) . ') ';
        }
        if (isset($filter_data['start_date']) and trim($filter_data['start_date']) != '') {
            $ph[] = strtolower(trim($filter_data['start_date']));
            $query .= ' AND a.effective_date >= ?';
        }
        if (isset($filter_data['end_date']) and trim($filter_data['end_date']) != '') {
            $ph[] = strtolower(trim($filter_data['end_date']));
            $query .= ' AND a.effective_date <= ?';
        }
        if (isset($filter_data['effective_date']) and trim($filter_data['effective_date']) != '') {
            $ph[] = strtolower(trim($filter_data['effective_date']));
            $query .= ' AND a.effective_date = ?';
        }
        $query .= isset($filter_data['created_by']) ? $this->getWhereClauseSQL(array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph) : NULL;
        $query .= isset($filter_data['updated_by']) ? $this->getWhereClauseSQL(array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph) : NULL;
        //Need to account for employees being assigned to deleted pay period schedules.
        $query .= '
						AND ( ppsuf.id IS NULL OR ppsf.id IS NOT NULL )
						AND a.deleted = 0
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        //Debug::Arr($query,'Query: ', __FILE__, __LINE__, __METHOD__,10);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }
    function getByCompanyIdAndUserId($company_id, $user_ids, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if ($user_ids == '') {
            return FALSE;
        }
        /*
        		if ( $order == NULL ) {
        			$order = array( 'type_id' => 'asc' );
        			$strict = FALSE;
        		} else {
        			$strict = TRUE;
        		}
        */
        $ppsuf = new PayPeriodScheduleUserFactory();
        $ph = array('company_id' => $company_id);
        $query = '
					select 	a.*,
							b.user_id as user_id
					from	' . $this->getTable() . ' as a,
							' . $ppsuf->getTable() . ' as b
					where 	a.id = b.pay_period_schedule_id
						AND a.company_id = ? ';
        if (isset($user_ids) and ($user_ids != '' or is_array($user_ids) and isset($user_ids[0]))) {
            $query .= ' AND b.user_id in (' . $this->getListSQL($user_ids, $ph) . ') ';
        }
        $query .= '	AND a.deleted = 0';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order);
        $this->rs = $this->db->Execute($query, $ph);
    }
 function postSave()
 {
     $this->removeCache($this->getId());
     if ($this->getDeleted() == FALSE and $this->getPermissionControl() !== FALSE) {
         Debug::text('Permission Group is set...', __FILE__, __LINE__, __METHOD__, 10);
         $pclf = new PermissionControlListFactory();
         $pclf->getByCompanyIdAndUserID($this->getCompany(), $this->getId());
         if ($pclf->getRecordCount() > 0) {
             Debug::text('Already assigned to a Permission Group...', __FILE__, __LINE__, __METHOD__, 10);
             $pc_obj = $pclf->getCurrent();
             if ($pc_obj->getId() == $this->getPermissionControl()) {
                 $add_permission_control = FALSE;
             } else {
                 Debug::text('Permission Group has changed...', __FILE__, __LINE__, __METHOD__, 10);
                 //Remove user from current schedule.
                 $pulf = new PermissionUserListFactory();
                 $pulf->getByPermissionControlIdAndUserID($pc_obj->getId(), $this->getId());
                 Debug::text('Record Count: ' . $pulf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10);
                 if ($pulf->getRecordCount() > 0) {
                     foreach ($pulf as $pu_obj) {
                         Debug::text('Deleteing from Permission Group: ' . $pu_obj->getPermissionControl(), __FILE__, __LINE__, __METHOD__, 10);
                         $pu_obj->Delete();
                     }
                 }
                 $add_permission_control = TRUE;
             }
         } else {
             Debug::text('NOT Already assigned to a Permission Group...', __FILE__, __LINE__, __METHOD__, 10);
             $add_permission_control = TRUE;
         }
         if ($this->getPermissionControl() !== FALSE and $add_permission_control == TRUE) {
             Debug::text('Adding user to Permission Group...', __FILE__, __LINE__, __METHOD__, 10);
             //Add to new permission group
             $puf = new PermissionUserFactory();
             $puf->setPermissionControl($this->getPermissionControl());
             $puf->setUser($this->getID());
             if ($puf->isValid()) {
                 $puf->Save();
                 //Clear permission class for this employee.
                 $pf = new PermissionFactory();
                 $pf->clearCache($this->getID(), $this->getCompany());
             }
         }
         unset($add_permission_control);
     }
     if ($this->getDeleted() == FALSE and $this->getPayPeriodSchedule() !== FALSE) {
         Debug::text('Pay Period Schedule is set...', __FILE__, __LINE__, __METHOD__, 10);
         $ppslf = new PayPeriodScheduleListFactory();
         $ppslf->getByUserId($this->getId());
         if ($ppslf->getRecordCount() > 0) {
             $pps_obj = $ppslf->getCurrent();
             if ($this->getPayPeriodSchedule() == $pps_obj->getId()) {
                 Debug::text('Already assigned to this Pay Period Schedule...', __FILE__, __LINE__, __METHOD__, 10);
                 $add_pay_period_schedule = FALSE;
             } else {
                 Debug::text('Changing Pay Period Schedule...', __FILE__, __LINE__, __METHOD__, 10);
                 //Remove user from current schedule.
                 $ppsulf = new PayPeriodScheduleUserListFactory();
                 $ppsulf->getByPayPeriodScheduleIdAndUserID($pps_obj->getId(), $this->getId());
                 Debug::text('Record Count: ' . $ppsulf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10);
                 if ($ppsulf->getRecordCount() > 0) {
                     foreach ($ppsulf as $ppsu_obj) {
                         Debug::text('Deleteing from Pay Period Schedule: ' . $ppsu_obj->getPayPeriodSchedule(), __FILE__, __LINE__, __METHOD__, 10);
                         $ppsu_obj->Delete();
                     }
                 }
                 $add_pay_period_schedule = TRUE;
             }
         } else {
             Debug::text('Not assigned to ANY Pay Period Schedule...', __FILE__, __LINE__, __METHOD__, 10);
             $add_pay_period_schedule = TRUE;
         }
         if ($this->getPayPeriodSchedule() !== FALSE and $add_pay_period_schedule == TRUE) {
             //Add to new pay period schedule
             $ppsuf = new PayPeriodScheduleUserFactory();
             $ppsuf->setPayPeriodSchedule($this->getPayPeriodSchedule());
             $ppsuf->setUser($this->getID());
             if ($ppsuf->isValid()) {
                 $ppsuf->Save();
             }
         }
         unset($add_pay_period_schedule);
     }
     if ($this->getDeleted() == FALSE and $this->getPolicyGroup() !== FALSE) {
         Debug::text('Policy Group is set...', __FILE__, __LINE__, __METHOD__, 10);
         $pglf = new PolicyGroupListFactory();
         $pglf->getByUserIds($this->getId());
         if ($pglf->getRecordCount() > 0) {
             $pg_obj = $pglf->getCurrent();
             if ($this->getPolicyGroup() == $pg_obj->getId()) {
                 Debug::text('Already assigned to this Policy Group...', __FILE__, __LINE__, __METHOD__, 10);
                 $add_policy_group = FALSE;
             } else {
                 Debug::text('Changing Policy Group...', __FILE__, __LINE__, __METHOD__, 10);
                 //Remove user from current schedule.
                 $pgulf = new PolicyGroupUserListFactory();
                 $pgulf->getByPolicyGroupIdAndUserId($pg_obj->getId(), $this->getId());
                 Debug::text('Record Count: ' . $pgulf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10);
                 if ($pgulf->getRecordCount() > 0) {
                     foreach ($pgulf as $pgu_obj) {
                         Debug::text('Deleteing from Policy Group: ' . $pgu_obj->getPolicyGroup(), __FILE__, __LINE__, __METHOD__, 10);
                         $pgu_obj->Delete();
                     }
                 }
                 $add_policy_group = TRUE;
             }
         } else {
             Debug::text('Not assigned to ANY Policy Group...', __FILE__, __LINE__, __METHOD__, 10);
             $add_policy_group = TRUE;
         }
         if ($this->getPolicyGroup() !== FALSE and $add_policy_group == TRUE) {
             //Add to new policy group
             $pguf = new PolicyGroupUserFactory();
             $pguf->setPolicyGroup($this->getPolicyGroup());
             $pguf->setUser($this->getID());
             if ($pguf->isValid()) {
                 $pguf->Save();
             }
         }
         unset($add_policy_group);
     }
     if ($this->getDeleted() == FALSE and $this->getHierarchyControl() !== FALSE) {
         Debug::text('Hierarchies are set...', __FILE__, __LINE__, __METHOD__, 10);
         $hierarchy_control_data = array_unique(array_values((array) $this->getHierarchyControl()));
         //Debug::Arr($hierarchy_control_data, 'Setting hierarchy control data...', __FILE__, __LINE__, __METHOD__, 10);
         if (is_array($hierarchy_control_data)) {
             $hclf = new HierarchyControlListFactory();
             $hclf->getObjectTypeAppendedListByCompanyIDAndUserID($this->getCompany(), $this->getID());
             $existing_hierarchy_control_data = array_unique(array_values((array) $hclf->getArrayByListFactory($hclf, FALSE, TRUE, FALSE)));
             //Debug::Arr($existing_hierarchy_control_data, 'Existing hierarchy control data...', __FILE__, __LINE__, __METHOD__, 10);
             $hierarchy_control_delete_diff = array_diff($existing_hierarchy_control_data, $hierarchy_control_data);
             //Debug::Arr($hierarchy_control_delete_diff, 'Hierarchy control delete diff: ', __FILE__, __LINE__, __METHOD__, 10);
             //Remove user from existing hierarchy control
             if (is_array($hierarchy_control_delete_diff)) {
                 foreach ($hierarchy_control_delete_diff as $hierarchy_control_id) {
                     if ($hierarchy_control_id != 0) {
                         $hulf = new HierarchyUserListFactory();
                         $hulf->getByHierarchyControlAndUserID($hierarchy_control_id, $this->getID());
                         if ($hulf->getRecordCount() > 0) {
                             Debug::text('Deleting user from hierarchy control ID: ' . $hierarchy_control_id, __FILE__, __LINE__, __METHOD__, 10);
                             $hulf->getCurrent()->Delete();
                         }
                     }
                 }
             }
             unset($hierarchy_control_delete_diff, $hulf, $hclf, $hierarchy_control_id);
             $hierarchy_control_add_diff = array_diff($hierarchy_control_data, $existing_hierarchy_control_data);
             //Debug::Arr($hierarchy_control_add_diff, 'Hierarchy control add diff: ', __FILE__, __LINE__, __METHOD__, 10);
             if (is_array($hierarchy_control_add_diff)) {
                 foreach ($hierarchy_control_add_diff as $hierarchy_control_id) {
                     Debug::text('Hierarchy data changed...', __FILE__, __LINE__, __METHOD__, 10);
                     if ($hierarchy_control_id != 0) {
                         $huf = new HierarchyUserFactory();
                         $huf->setHierarchyControl($hierarchy_control_id);
                         $huf->setUser($this->getId());
                         if ($huf->isValid()) {
                             Debug::text('Adding user to hierarchy control ID: ' . $hierarchy_control_id, __FILE__, __LINE__, __METHOD__, 10);
                             $huf->Save();
                         }
                     }
                 }
             }
             unset($hierarchy_control_add, $huf, $hierarchy_control_id);
         }
     }
     if (isset($this->is_new) and $this->is_new == TRUE) {
         $udlf = new UserDefaultListFactory();
         $udlf->getByCompanyId($this->getCompany());
         if ($udlf->getRecordCount() > 0) {
             Debug::Text('Using User Defaults', __FILE__, __LINE__, __METHOD__, 10);
             $udf_obj = $udlf->getCurrent();
             Debug::text('Inserting Default Deductions...', __FILE__, __LINE__, __METHOD__, 10);
             $company_deduction_ids = $udf_obj->getCompanyDeduction();
             if (is_array($company_deduction_ids) and count($company_deduction_ids) > 0) {
                 foreach ($company_deduction_ids as $company_deduction_id) {
                     $udf = new UserDeductionFactory();
                     $udf->setUser($this->getId());
                     $udf->setCompanyDeduction($company_deduction_id);
                     if ($udf->isValid()) {
                         $udf->Save();
                     }
                 }
             }
             unset($company_deduction_ids, $company_deduction_id, $udf);
             Debug::text('Inserting Default Prefs...', __FILE__, __LINE__, __METHOD__, 10);
             $upf = new UserPreferenceFactory();
             $upf->setUser($this->getId());
             $upf->setLanguage($udf_obj->getLanguage());
             $upf->setDateFormat($udf_obj->getDateFormat());
             $upf->setTimeFormat($udf_obj->getTimeFormat());
             $upf->setTimeUnitFormat($udf_obj->getTimeUnitFormat());
             $upf->setTimeZone($udf_obj->getTimeZone());
             $upf->setItemsPerPage($udf_obj->getItemsPerPage());
             $upf->setStartWeekDay($udf_obj->getStartWeekDay());
             $upf->setEnableEmailNotificationException($udf_obj->getEnableEmailNotificationException());
             $upf->setEnableEmailNotificationMessage($udf_obj->getEnableEmailNotificationMessage());
             $upf->setEnableEmailNotificationHome($udf_obj->getEnableEmailNotificationHome());
             if ($upf->isValid()) {
                 $upf->Save();
             }
         }
     }
     if ($this->getDeleted() == TRUE) {
         //Remove them from the authorization hierarchy, policy group, and pay period schedule.
         //Delete any accruals for them as well.
         //Pay Period Schedule
         $ppslf = new PayPeriodScheduleListFactory();
         $ppslf->getByUserId($this->getId());
         if ($ppslf->getRecordCount() > 0) {
             $pps_obj = $ppslf->getCurrent();
             //Remove user from current schedule.
             $ppsulf = new PayPeriodScheduleUserListFactory();
             $ppsulf->getByPayPeriodScheduleIdAndUserID($pps_obj->getId(), $this->getId());
             Debug::text('Record Count: ' . $ppsulf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10);
             if ($ppsulf->getRecordCount() > 0) {
                 foreach ($ppsulf as $ppsu_obj) {
                     Debug::text('Deleteing from Pay Period Schedule: ' . $ppsu_obj->getPayPeriodSchedule(), __FILE__, __LINE__, __METHOD__, 10);
                     $ppsu_obj->Delete();
                 }
             }
         }
         //Policy Group
         $pglf = new PolicyGroupListFactory();
         $pglf->getByUserIds($this->getId());
         if ($pglf->getRecordCount() > 0) {
             $pg_obj = $pglf->getCurrent();
             $pgulf = new PolicyGroupUserListFactory();
             $pgulf->getByPolicyGroupIdAndUserId($pg_obj->getId(), $this->getId());
             Debug::text('Record Count: ' . $pgulf->getRecordCount(), __FILE__, __LINE__, __METHOD__, 10);
             if ($pgulf->getRecordCount() > 0) {
                 foreach ($pgulf as $pgu_obj) {
                     Debug::text('Deleteing from Policy Group: ' . $pgu_obj->getPolicyGroup(), __FILE__, __LINE__, __METHOD__, 10);
                     $pgu_obj->Delete();
                 }
             }
         }
         //Hierarchy
         $hclf = new HierarchyControlListFactory();
         $hclf->getByCompanyId($this->getCompany());
         if ($hclf->getRecordCount() > 0) {
             foreach ($hclf as $hc_obj) {
                 $hf = new HierarchyListFactory();
                 $hf->setUser($this->getID());
                 $hf->setHierarchyControl($hc_obj->getId());
                 $hf->Delete();
             }
             $hf->removeCache(NULL, $hf->getTable(TRUE));
             //On delete we have to delete the entire group.
             unset($hf);
         }
         //Accrual balances
         $alf = new AccrualListFactory();
         $alf->getByUserIdAndCompanyId($this->getId(), $this->getCompany());
         if ($alf->getRecordCount() > 0) {
             foreach ($alf as $a_obj) {
                 $a_obj->setDeleted(TRUE);
                 if ($a_obj->isValid()) {
                     $a_obj->Save();
                 }
             }
         }
     }
     return TRUE;
 }
    function getAPISearchByCompanyIdAndArrayCriteria($company_id, $filter_data, $limit = NULL, $page = NULL, $where = NULL, $order = NULL)
    {
        if ($company_id == '') {
            return FALSE;
        }
        if (!is_array($order)) {
            //Use Filter Data ordering if its set.
            if (isset($filter_data['sort_column']) and $filter_data['sort_order']) {
                $order = array(Misc::trimSortPrefix($filter_data['sort_column']) => $filter_data['sort_order']);
            }
        }
        $additional_order_fields = array('total_users');
        if ($order == NULL) {
            $order = array('name' => 'asc');
            $strict = FALSE;
        } else {
            //Always sort by last name,first name after other columns
            if (!isset($order['name'])) {
                $order['name'] = 'asc';
            }
            $strict = TRUE;
        }
        //Debug::Arr($order,'Order Data:', __FILE__, __LINE__, __METHOD__,10);
        //Debug::Arr($filter_data,'Filter Data:', __FILE__, __LINE__, __METHOD__,10);
        $uf = new UserFactory();
        $ppsuf = new PayPeriodScheduleUserFactory();
        $ph = array('company_id' => $company_id);
        $query = '
					select
							_ADODB_COUNT
							a.*,
							(select count(*) from ' . $ppsuf->getTable() . ' as ppsuf_tmp where ppsuf_tmp.pay_period_schedule_id = a.id ) as total_users,
							y.first_name as created_by_first_name,
							y.middle_name as created_by_middle_name,
							y.last_name as created_by_last_name,
							z.first_name as updated_by_first_name,
							z.middle_name as updated_by_middle_name,
							z.last_name as updated_by_last_name
							_ADODB_COUNT
					from 	' . $this->getTable() . ' as a
						LEFT JOIN ' . $uf->getTable() . ' as y ON ( a.created_by = y.id AND y.deleted = 0 )
						LEFT JOIN ' . $uf->getTable() . ' as z ON ( a.updated_by = z.id AND z.deleted = 0 )
					where	a.company_id = ?
					';
        $query .= isset($filter_data['permission_children_ids']) ? $this->getWhereClauseSQL('a.created_by', $filter_data['permission_children_ids'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['id']) ? $this->getWhereClauseSQL('a.id', $filter_data['id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['exclude_id']) ? $this->getWhereClauseSQL('a.id', $filter_data['exclude_id'], 'not_numeric_list', $ph) : NULL;
        if (isset($filter_data['type']) and trim($filter_data['type']) != '' and !isset($filter_data['type_id'])) {
            $filter_data['type_id'] = Option::getByFuzzyValue($filter_data['type'], $this->getOptions('type'));
        }
        $query .= isset($filter_data['type_id']) ? $this->getWhereClauseSQL('a.type_id', $filter_data['type_id'], 'numeric_list', $ph) : NULL;
        $query .= isset($filter_data['name']) ? $this->getWhereClauseSQL('a.name', $filter_data['name'], 'text', $ph) : NULL;
        $query .= isset($filter_data['description']) ? $this->getWhereClauseSQL('a.description', $filter_data['description'], 'text', $ph) : NULL;
        $query .= isset($filter_data['created_by']) ? $this->getWhereClauseSQL(array('a.created_by', 'y.first_name', 'y.last_name'), $filter_data['created_by'], 'user_id_or_name', $ph) : NULL;
        $query .= isset($filter_data['updated_by']) ? $this->getWhereClauseSQL(array('a.updated_by', 'z.first_name', 'z.last_name'), $filter_data['updated_by'], 'user_id_or_name', $ph) : NULL;
        $query .= '
						AND a.deleted = 0
					';
        $query .= $this->getWhereSQL($where);
        $query .= $this->getSortSQL($order, $strict, $additional_order_fields);
        $this->ExecuteSQL($query, $ph, $limit, $page);
        return $this;
    }