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

class SettingsApi extends Cf_REST_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('vcsSettingsModel');
        $this->load->model('llmConfigModel');
        $this->load->model('settings_rest_model');
        $this->settings_rest_model->setRestClient($this->getRestClient());
    }

    public function clearVCS_post()
    {
        try {
            $this->vcsSettingsModel->deleteSettings();
            $this->respond(204);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('error', $message);
            $this->respond(500, $message);
        }
    }

    public function LLMConfig_post()
    {
        $data = json_decode($this->request->body, true);
        $this->llmConfigModel->createConfig($data);
        $this->respond(201);
    }

    public function LLMConfig_put($id)
    {
        $data = json_decode($this->_put_args, true);
        $this->llmConfigModel->updateConfig($id, $data);
        $this->respond(201);
    }

    public function LLMConfig_get()
    {
        $config = $this->llmConfigModel->getFirstConfig();
        if (isset($config['token']) && !empty($config['token'])) {
            $config['token'] = '';
            $config['isTokenSet'] = true;
        }
        $this->respond(200, json_encode($config));
    }

    public function LLMConfig_delete($id)
    {
        $this->llmConfigModel->deleteConfig($id);
        $this->respond(204);
    }

    public function preferences_put()
    {
        $data = json_decode($this->_put_args, true);
        $result = $this->settings_rest_model->updateData($data);

        if (isset($result['success']) && $result['success'] === false) {
            $this->respond(422, json_encode($result));
            return;
        }

        $this->respond(204);
    }

    public function preferences_get()
    {
        $preferences = $this->settings_rest_model->get_app_settings();
        $this->respond(200, json_encode($preferences));
    }

    public function HostIdentifier_get()
    {
        $this->load->config('hostidentifier');
        $this->load->model('advancedreports_model');
        $this->advancedreports_model->setRestClient($this->getRestClient());

        $options = config_item('host-identifier');
        if (empty($options)) {
            $options = ['sys.fqhost' => 'Fully qualified domain name'];
        }

        $variableNames = [];
        foreach (array_keys($options) as $key) {
            $parts = explode('.', $key);
            if (isset($parts[1])) {
                $variableNames[] = $parts[1];
            }
        }
        $escapedVariableNames = escapeArrayValues($variableNames);
        $in = "'" . implode("','", $escapedVariableNames) . "'";

        $examples = [];
        try {
            $username = $this->session->userdata('username');
            $query =
                'SELECT DISTINCT Bundle, VariableName, VariableValue FROM Variables' .
                " WHERE VariableName IN ($in) AND hostkey in (SELECT hostkey from contexts where ContextName = 'policy_server') ORDER BY VariableName";
            $reported = $this->advancedreports_model->runQuery($username, $query);
            foreach ((array) $reported['rows'] as $row) {
                $examples[$row[0] . '.' . $row[1]] = $row[2];
            }
        } catch (Exception $e) {
            log_message(
                log_level_for_exception($e),
                'Error getting variables for host identifier: ' . $e->getMessage(),
            );
        }

        $current = $this->settings_rest_model->app_settings_get_item('hostIdentifier');
        if (empty($current)) {
            $current = 'default.sys.fqhost';
        }

        $payload = [];
        foreach ($options as $key => $label) {
            $parts = explode('.', $key);
            $payload[] = [
                'scope' => $parts[0],
                'name' => isset($parts[1]) ? $parts[1] : '',
                'label' => $label,
                'example' => isset($examples[$key]) ? trim($examples[$key]) : null,
            ];
        }

        $this->respond(
            200,
            json_encode([
                'current' => $current,
                'options' => $payload,
            ]),
        );
    }
}
