<?php

//class autocomplete extends Cf_Controller

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

class autocomplete extends Cf_REST_Controller
{
    protected $username = '';

    public function __construct()
    {
        parent::__construct();
        $this->load->model(['advancedreports_model', 'autocomplete_model']);
        $this->advancedreports_model->setRestClient($this->getRestClient());
        $this->username = $this->session->userdata('username');
    }

    public 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
     */
    public 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.');
        }
    }

    public function classes_get()
    {
        try {
            $query = $_REQUEST['query'] ?? '';
            $classes = $this->autocomplete_model->getClasses($query);
            $this->respond(200, json_encode($classes));
            return;
        } catch (Exception $exception) {
            log_message('error', 'Unable to get autocomplete classes. Error: ' . $exception->getMessage());
            throw $exception;
        }
    }

    public function variables_get()
    {
        try {
            $query = $_REQUEST['query'] ?? '';
            $variables = $this->autocomplete_model->getVariables($query);
            $this->respond(200, json_encode($variables));
            return;
        } catch (Exception $exception) {
            log_message('error', 'Unable to get autocomplete variables. Error: ' . $exception->getMessage());
            throw $exception;
        }
    }

    public function inventory_get()
    {
        try {
            $query = $_REQUEST['query'] ?? '';
            $inventory = $this->autocomplete_model->getInventory($query);
            $this->respond(200, json_encode($inventory));
            return;
        } catch (Exception $exception) {
            log_message('error', 'Unable to get autocomplete inventory. Error: ' . $exception->getMessage());
            throw $exception;
        }
    }
}
