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

/**
 * Class PolicyAPI
 */
class PolicyAPI extends Cf_REST_Controller
{
    /**
     * PolicyAPI constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->load->model('policy/policy_model');
        $this->policy_model->setUsername($this->session->userdata('username'));
        $this->policy_model->setRestClient($this->getRestClient());
        $this->load->library('ion_auth');
    }

    /**
     * Get policy data by file path
     */
    public function getPolicyInfoByFilePath_post()
    {
        $fileName = $this->input->post('relativeFilePath');
        $promise = $this->input->post('promiseOutcome');
        $hostkey = $this->input->post('hostkey');

        $json = json_encode($this->policy_model->getPolicyInfo($fileName, $promise, $hostkey));
        $this->respond_ok($json);
    }

    /**
     * Get file contents
     *
     * @throws Exception
     */
    public function getFile_post()
    {
        try {
            $fileName = $this->input->post('fileName');
            $content = $this->getRestClient()->get('/policy/contents?path=' . $fileName, [], false);
            $this->respond_ok($content);
        } catch (Exception $exception) {
            log_message('error', $exception->getTraceAsString());
            throw new Exception($exception->getMessage());
        }
    }

    /**
     * Get policy statistics
     */
    public function policyStatistic_get()
    {
        $inventoryFilter = isset($_REQUEST['inventoryFilter'])
            ? json_decode($_REQUEST['inventoryFilter'], JSON_OBJECT_AS_ARRAY)
            : false;

        $policies = $this->policy_model->getPolicyStatistics(
            $_REQUEST['promiseOutcome'],
            isset($_REQUEST['hostIncludes']) ? $_REQUEST['hostIncludes'] : [],
            isset($_REQUEST['hostExcludes']) ? $_REQUEST['hostExcludes'] : [],
            $inventoryFilter,
        );
        $policyMap = [];
        foreach ($policies as $policy) {
            $policyMap[$policy['policyfile']] = [
                'KEPT' => (int) $policy['kept_count'],
                'NOTKEPT' => (int) $policy['notkept_count'],
                'REPAIRED' => (int) $policy['repaired_count'],
            ];
        }
        $this->respond_ok(json_encode($policyMap));
    }

    /**
     * Create flag file to enable copying masterfiles
     *
     * @rbacName Enable policy analyzer
     * @rbacDescription allow copying masterfiles directory
     * @rbacGroup Policy analyzer
     * @rbacAlias analyzer.enableCopying_get
     */
    public function enableCopying_get()
    {
        $result = $this->policy_model->createFlagFile();
        $this->respond_ok($result);
    }

    /**
     * Get enabling status
     */
    public function enablingStatus_get()
    {
        $result = [
            'copying_request_sent' => $this->policy_model->isFlagFileCreated(),
            'policy_directory_exits' => $this->policy_model->isPolicyDirExists(),
        ];
        $this->respond_ok(json_encode($result));
    }

    /**
     * Get file tree
     */
    public function files_get()
    {
        try {
            $files = $this->policy_model->getPolicyFiles();
            $this->respond_ok($files);
        } catch (Exception $exception) {
            $result = [
                'copying_enabled' => $this->policy_model->isFlagFileCreated(),
            ];
            $this->respond_forbidden(json_encode($result));
        }
    }
}
