<?php

//class autocomplete extends Cf_Controller

require_once APPPATH . '/libraries/Cf_REST_Controller.php';

class autocomplete extends Cf_REST_Controller
{

    protected $username = '';

    function __construct()
    {
        parent::__construct();
        $this->load->model(array('advancedreports_model'));
        $this->advancedreports_model->setRestClient($this->getRestClient());
        $this->username = $this->session->userdata('username');
    }

    function index()
    {
        $this->respond_forbidden();
    }

    /**
     * Return field data for autocomplete list
     *
     * Request body contain:
     *  $fieldName - type of variable - package name, version number...
     *  $value - value from input field
     *  $parentFieldName  - type(sqlfield name) of parent element - 'patchname'
     *  $parentValue - value of parent element - in case list depends on parent value, for example - package version depends on package name
     */
    function load_post()
    {
        $data = json_decode($this->request->body, true);

        $fieldName = $data['type'];
        $value     = $data['value'];

        $parentFieldName = isset($data['parentType'])  ?  $data['parentType']  : '';
        $parentValue     = isset($data['parentValue']) ?  $data['parentValue'] : '';

        try {
            $result = $this->advancedreports_model->getAutocompleteFieldData($this->username, $fieldName, $value, $parentFieldName, $parentValue);
        }
        catch(Exception $e)
        {
            $message = $e->getMessage();
            log_message('error', 'load_get(): Unable to get autocomplete list for '. $fieldName .', error: ' . $message);
            respond_internal_error($message);
            return;
        }

        respond_ok(json_encode($result));
    }

    public function hosts_filter_get()
    {
        $this->load->model(['host_model', 'class_model']);
        $this->load->library('Cf_api_formatter');

        $query = $this->param('query', true);
        if (!isset($query) && empty($query)) {
            $this->respond_internal_error('`query` param cannot be empty');
        }

        $hostsData = $this->host_model->searchHost($this->username, $query);
        $classes = array_map(function ($item) {
            return $item[0];
        }, $this->class_model->getAllClasses($this->username, $query, [], [], 7));

        return respond_ok(json_encode([
            'hosts' => $this->cf_api_formatter->merge_columns_with_rows($hostsData['header'], $hostsData['rows']),
            'classes' => $classes,
        ]));

    }

    public function condition_categories_get()
    {
        try {
            $this->load->model('compliance_category');
            $text = $this->param('text', true);
            $cats = $this->compliance_category->searchCategory($text);
            respond_ok(json_encode($cats));
        } catch (Exception $exception) {
            log_message(
                'error',
                'Failed to retrieve autocomplete suggestions, error: ' . $exception->getTraceAsString()
            );
            respond_internal_error('Failed to retrieve autocomplete suggestions.');
        }

    }
}
