<?php

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

class HostComplianceList extends Cf_REST_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->username = $this->session->userdata('username');
        $this->load->model(['host_model']);
        $this->load->helper('elements_creator');
    }

    public function tablemetadata_get($colour)
    {
        $tableColsName = [];

        switch ($colour) {
            case 'red':
                $tableColsName = [
                    [
                        'sTitle' => "<input type='checkbox' id='check-all' name='check-all'>",
                        'sClass' => 'select-col',
                        'sWidth' => '15px',
                        'mRender' => 'checkbox_formatter',
                        'aTargets' => [0],
                    ],
                    ['sTitle' => 'Host', 'aTargets' => [1]],
                    ['sTitle' => 'IP', 'bSortable' => false, 'sWidth' => '20%', 'aTargets' => [2]],
                    ['sTitle' => ' ', 'bSortable' => false, 'sWidth' => '20%', 'aTargets' => [3]],
                ];
                break;
            case 'green':
                $tableColsName = [
                    [
                        'sTitle' => "<input type='checkbox' id='check-all' name='check-all'>",
                        'sClass' => 'select-col',
                        'sWidth' => '15px',
                        'mRender' => 'checkbox_formatter',
                        'aTargets' => [0],
                    ],
                    ['sTitle' => 'Host', 'aTargets' => [1]],
                ];
                break;
            case 'bb':
                $tableColsName = [
                    [
                        'sTitle' => " <input type='checkbox' id='check-all' name='check-all'>",
                        'sClass' => 'select-col',
                        'sWidth' => '15px',
                        'mRender' => 'checkbox_formatter',
                        'aTargets' => [0],
                    ],
                    ['sTitle' => 'Host', 'aTargets' => [1]],
                    ['sTitle' => 'Time', 'bSortable' => false, 'mRender' => 'timestamp_formatter', 'aTargets' => [2]],
                    ['sTitle' => 'Problem', 'bSortable' => false, 'sWidth' => '20%', 'aTargets' => [3]],
                ];
                break;
        }

        $output = ['aoColumnDefs' => $tableColsName];

        $this->respond_ok(json_encode($output));
    }

    public function tabledata_post()
    {
        $result = [];
        $getparams = $this->uri->uri_to_assoc(4);
        $rows = intval($this->param('iDisplayLength'));
        $echo = intval($this->param('sEcho'));

        $displayStarts = intval($this->param('iDisplayStart'));

        $page_number = intval(ceil($displayStarts / $rows), 10) + 1;
        $includes = $this->param_includes();
        $excludes = $this->param_excludes();
        $colour = $this->param('colour', true);

        $datarows = [];

        switch ($colour) {
            case 'red':
                $result = $this->host_model->getHostByColorFromPromiseStatus(
                    'red',
                    $this->username,
                    $includes,
                    $excludes,
                    $rows,
                    $page_number,
                );
                foreach ($result['rows'] as $index => $r) {
                    $r[1] = create_host_link_element($r[0], $r[1]);
                    $rowValues = array_values($r);
                    $hostKey = $r[0];
                    $rowValues[] = $this->_makePromiseNotKeptLink($hostKey, 'notkept');
                    $rowValues['DT_RowId'] = $hostKey;
                    $datarows[] = $rowValues;
                }
                break;
            case 'green':
                $result = $this->host_model->getHostByColorFromPromiseStatus(
                    'green',
                    $this->username,
                    $includes,
                    $excludes,
                    $rows,
                    $page_number,
                );
                foreach ($result['rows'] as $index => $r) {
                    $r[1] = create_host_link_element($r[0], $r[1]);
                    $rowValues = array_values($r);
                    $hostKey = $r[0];
                    $rowValues['DT_RowId'] = $hostKey;
                    $datarows[] = $rowValues;
                }
                break;
            case 'bb':
                $blue = $this->host_model->getHostByColorFromPromiseStatus(
                    'blue',
                    $this->username,
                    $includes,
                    $excludes,
                    $rows,
                    $page_number,
                );
                $black = $this->host_model->getHostByColorFromPromiseStatus(
                    'black',
                    $this->username,
                    $includes,
                    $excludes,
                    $rows,
                    $page_number,
                );
                $result = [];
                $result['rows'] = array_merge($blue['rows'], $black['rows']);
                $result['rowCount'] = $blue['rowCount'] + $black['rowCount'];
                foreach ($blue['rows'] as $index => $r) {
                    $rowValues = array_values($r);
                    $hostKey = $r[0];
                    $rowValues[] = 'Connection error';
                    $rowValues['DT_RowId'] = $hostKey;
                    $datarows[] = $rowValues;
                }

                foreach ($black['rows'] as $index => $r) {
                    $rowValues = array_values($r);
                    $hostKey = $r[0];
                    $rowValues[] = 'Agent not executed';
                    $rowValues['DT_RowId'] = $hostKey;
                    $datarows[] = $rowValues;
                }
        }

        $jsonObj = new stdClass();
        $jsonObj->page = $page_number;

        $totalPageNumber = ceil($result['rowCount'] / $rows);
        $jsonObj->iTotalRecords = $totalPageNumber;
        $jsonObj->iTotalDisplayRecords = $result['rowCount'];
        $jsonObj->sEcho = $echo;

        $paginationData = paging($page_number, $rows, $result['rowCount'], 5);
        $jsonObj->userdata = $paginationData;

        $jsonObj->aaData = $datarows;

        $this->respond_ok(json_encode($jsonObj));
    }

    public function _makePromiseNotKeptLink($data, $type)
    {
        $logType = $type;
        $title = [
            'notkept' => 'List promises not kept',
            'repaired' => 'List promises repaired',
        ];
        $url = site_url('advancedreports/external');
        $escapedData = $this->db->escape_str($data);
        $query = sprintf(
            'SELECT DISTINCT h.hostname AS "Host name",
                                 p.bundlename AS "Bundle name",
                                 p.promisehandle AS "Promise handle",
                                 p.promiser AS "Promiser",
                                 p.promiseoutcome AS "Promise outcome",
                                 p.changetimestamp AS "Change time",
                                 p.logmessages AS "Log messages"
                                FROM promiseexecutions p INNER JOIN hosts h ON h.hostkey = p.hostkey
                                WHERE p.HOSTKEY=\'%s\' AND p.promiseoutcome=\'NOTKEPT\' ORDER BY p.changetimestamp DESC',
            $escapedData,
        );
        $encoded = rawurlencode(base64_encode($query));

        $class = convertSHAToPK_SHA($data);
        $includes = rawurlencode(base64_encode($class));

        $link = $url . '/sql/' . $encoded . '/includes/' . $includes . '/title/Promise not kept report';
        return anchor($link, $title[$logType], 'onclick="event.stopPropagation();"');
    }
}
