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

class Eventslogapi extends Cf_REST_Controller
{
    public $username = '';

    public function __construct()
    {
        parent::__construct();

        $this->load->model('eventslog_model');
        $this->username = $this->session->userdata('username');
        $this->load->library('ion_auth');
    }

    public function events_post()
    {
        $data = json_decode($this->request->body, true);

        $filter = [];

        if ($userFilter = $this->getUsrnameFilterForCommonEvents()) {
            $filter[] = $userFilter;
        }

        $limit = intval($data['limit']) ?? 100;
        $offset = intval($data['offset']) ?? 0;
        $dateFrom = $data['dateFilter']['dtFrm'] ? intval($data['dateFilter']['dtFrm']) : null;
        $dateTo = $data['dateFilter']['dtTo'] ? intval($data['dateFilter']['dtTo']) : null;

        if (!empty($data['eventFilter'])) {
            $filter[] = 'item_name  ILIKE ' . '\'%' . $this->db->escape_str($data['eventFilter']) . '%\'';
        }

        if (!empty($data['type']) && $data['type'] != 'all') {
            $filter[] = 'item_type ILIKE ' . '\'%' . $this->db->escape_str($data['type']) . '%\'';
        }

        if (!empty($dateFrom)) {
            $filter[] = 'extract(epoch from "time") >= \'' . $this->db->escape_str($dateFrom) . '\'';
        }

        if (!empty($dateTo)) {
            $filter[] = 'extract(epoch from "time") <= \'' . $this->db->escape_str($dateTo) . '\'';
        }

        $filter = implode(' AND ', $filter);

        $order = ['id' => 'desc'];

        try {
            $totalCount = $this->eventslog_model->get_events_count($filter);
            $result = $this->eventslog_model->get_all_events($filter, $offset, $limit, $order);
            $returnData = ['totalCount' => $totalCount, 'data' => $result];
            $json = json_encode($returnData);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Failed retrieving events, error: ' . $message);
            respond_internal_error($message);
        }
    }

    public function eventTypes_get()
    {
        $filter = isActionAllowed('events.viewAllEvents')
            ? 'item_type IS NOT NULL'
            : 'item_type IS NOT NULL AND username IS NOT NULL';
        $result = $this->eventslog_model->getEventTypes($filter);
        $json = json_encode($result);
        respond_ok($json);
    }

    /**
     * Return all checks for item, for example for check
     *
     * @param type $id
     */
    public function geteventsforitembyid_post($id)
    {
        $data = json_decode($this->request->body, true);
        $load_limit = $data['load_limit'];
        $order = ['extract(epoch from "time")' => 'desc'];

        $filter = [];
        $filter['username'] = $this->session->userdata('username');
        $filter['item_id'] = urldecode($id);
        try {
            $result = $this->eventslog_model->get_all_events($filter, 0, $load_limit, $order);
            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Failed retrieving events, error: ' . $message);
            respond_internal_error($message);
        }
    }

    /**
     * Return all checks for group of items item, for example for check
     *
     * array of ids
     */
    public function dashevents_post()
    {
        $data = json_decode($this->request->body, true);
        $load_limit = $data['limit'];
        $order = ['extract(epoch from "time")' => 'desc'];

        $filter = [];
        if ($userFilter = $this->getUsrnameFilterForCommonEvents()) {
            $filter[] = $userFilter;
        }

        if (count($data['alerts'])) {
            $data['alerts'] = array_map(function ($item) {
                return "'" . $this->db->escape_str($item) . "'";
            }, $data['alerts']);
            $filter[] = 'item_id IN (' . implode(',', $data['alerts']) . ')';
        }

        if (!empty($filter)) {
            $filter = implode(' AND ', $filter);
        }

        try {
            $result = $this->eventslog_model->get_selected_events($filter, 0, $load_limit, $order);
            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Failed retrieving events, error: ' . $message);
            respond_internal_error($message);
        }
    }

    /**
     * @rbacName View whole system events
     * @rbacDescription otherwise user will be able to see only their events
     * @rbacGroup Events
     * @rbacAlias events.viewAllEvents
     *
     * @return string
     */
    private function getUsrnameFilterForCommonEvents()
    {
        $filter = null;
        if (!isActionAllowed('events.viewAllEvents')) {
            $filter = 'username LIKE ' . "'" . $this->db->escape_str($this->session->userdata('username')) . "'";
        }
        return $filter;
    }
}
