<?php

/**
 * Class Compliance_category
 */
class Compliance_category extends Cf_Model
{
    /**
     * @var string[]
     */
    protected $preDefinedCategories = [
        'Cloud',
        'Containers',
        'Hardware',
        'Infrastructure',
        'Operating System',
        'Security',
        'Other',
    ];

    /**
     * @param string $search
     * @return array
     */
    public function searchCategory(string $search): array
    {
        if (!empty($search)) {
            // get categories from existing conditions
            $categoriesFromDB = array_map(function ($item) {
                return ucfirst($item['category']);
            }, $this->db
                ->from('dashboard_rules')
                ->distinct()
                ->select('category')
                ->like('LOWER(category)', strtolower($search))
                ->get()
                ->result_array());

            // get categories from predefined values
            $predefined = array_filter($this->preDefinedCategories, function ($item) use ($search) {
                return stristr($item, $search);
            });

            // merge categories from db and pre-defined then get unique values and reset indexes by array_values
            // to avoid an object as the json_encode result instead of array
            $result = array_values(array_unique(array_merge($categoriesFromDB, $predefined)));
        } else {
            // if $search therm is empty than return pre-defined categories list
            $result = $this->preDefinedCategories;
        }

        return $result;
    }
}
