<?php

/**
 * i-doit Report View which shows all CMDB-Status changes of all objects
 *
 * @package     i-doit
 * @subpackage  Reports
 * @author      Oscar Pohl <opohl@i-doit.com>
 * @copyright   synetics GmbH
 * @license     http://www.i-doit.com/license
 */
class isys_report_view_logbook extends isys_report_view
{
    /**
     * @return string
     */
    public static function name()
    {
        return 'LC__REPORT__VIEW__LOGBOOK__TITLE';
    }

    /**
     * @return string
     */
    public static function description()
    {
        return 'LC__REPORT__VIEW__LOGBOOK__DESCRIPTION';
    }

    /**
     * @return string
     */
    public function template()
    {
        return isys_module_report::getPath() . 'templates/view_logbook.tpl';
    }

    /**
     * @return string
     */
    public static function viewtype()
    {
        return 'LC__CMDB__CATG__LOGBOOK';
    }

    /**
     *
     */
    public function start()
    {
        $this->template->activate_editmode()
            ->assign('page_limit', isys_glob_get_pagelimit())
            ->assign('ajax_url', isys_glob_add_to_query('ajax', 1));
    }

    /**
     * @throws \idoit\Exception\JsonException
     */
    public function ajax_request()
    {
        global $g_dirs;

        $dao = isys_cmdb_dao::instance($this->database);
        $objtypes = [];
        $categories = [];
        $return = [
            'data'    => [],
            'success' => false
        ];

        // Get all object types
        $resObjtypes = $dao->get_object_types();
        while ($rowObjtypes = $resObjtypes->get_row()) {
            $objtypes[$rowObjtypes['isys_obj_type__title']] = $this->language->get($rowObjtypes['isys_obj_type__title']);
        }
        // Fetching some translations that will be used a few times.
        $lcTitle = $this->language->get('LC__UNIVERSAL__TITLE_LINK');
        $lcObjectType = $this->language->get('LC__CMDB__OBJTYPE');
        $lcCategory = $this->language->get('LC_UNIVERSAL__CATEGORY');
        $lcDate = $this->language->get('LC_UNIVERSAL__DATE');
        $lcUser = $this->language->get('LC__CMDB__LOGBOOK__SOURCE__USER');
        $lcEvent = $this->language->get('LC__UNIVERSAL__EVENT');
        $lcBefore = $this->language->get('LC__REPORT__VIEW__LOGBOOK__BEFORE');
        $lcAfter = $this->language->get('LC__REPORT__VIEW__LOGBOOK__AFTER');

        $periodFrom = $_POST['C__LOGBOOK__PERIOD_FROM__HIDDEN'];
        $periodTo = $_POST['C__LOGBOOK__PERIOD_TO__HIDDEN'];
        $object = $_POST['C__LOGBOOK__OBJECTS__HIDDEN'];

        // Query
        $sql = "SELECT isys_obj__id, isys_obj__title, isys_logbook__obj_type_static, isys_logbook__category_static, isys_logbook__date, isys_logbook__user_name_static,
       isys_logbook__changes, isys_logbook__event_static, isys_logbook__obj_name_static, isys_logbook__entry_identifier_static, isys_logbook__changecount
       FROM isys_catg_logb_list
       INNER JOIN isys_logbook ON isys_logbook__id = isys_catg_logb_list__isys_logbook__id
       INNER JOIN isys_obj ON isys_obj__id = isys_catg_logb_list__isys_obj__id";

        // From date
        if ($periodFrom != '') {
            $sql .= ' AND isys_logbook__date > ' . $dao->convert_sql_datetime($periodFrom . ' 00:00:00');
        }

        // To date
        if ($periodTo != '') {
            $sql .= ' AND isys_logbook__date <= ' . $dao->convert_sql_datetime($periodTo . ' 23:59:59');
        }

        // objects
        if (is_string($object) && isys_format_json::is_json_array($object)) {
            $object = isys_format_json::decode($object);

            if (count($object) > 1) {
                $sql .= ' AND isys_obj__id IN (' . implode(',', $object) . ') ';
            } else {
                $sql .= ' AND isys_obj__id = ' . $dao->convert_sql_id($object[0]);
            }
        }

        $res = $this->database->query($sql . ';');

        if ($this->database->num_rows($res) > 0) {
            while ($row = $this->database->fetch_row_assoc($res)) {
                // Create object link
                $urlink = isys_helper_link::create_url([C__CMDB__GET__OBJECT => $row['isys_obj__id']]);

                // Build necessary categories
                if (!array_key_exists($row['isys_logbook__category_static'], $categories)) {
                    $categories[$row['isys_logbook__category_static']] = $this->language->get($row['isys_logbook__category_static']);
                }
                // Build basic event data
                $data = [
                    $lcTitle =>  "<a href='" . $urlink . "'>" . $row['isys_obj__title'] . "</a>",
                    $lcObjectType => $objtypes[$row['isys_logbook__obj_type_static']],
                    $lcCategory => $categories[$row['isys_logbook__category_static']],
                    $lcDate => $row['isys_logbook__date'],
                    $lcUser => $row['isys_logbook__user_name_static'],
                    $lcEvent => isys_event_manager::getInstance()
                        ->translateEvent(
                            $row["isys_logbook__event_static"],
                            $row["isys_logbook__obj_name_static"],
                            $row["isys_logbook__category_static"],
                            $row["isys_logbook__obj_type_static"],
                            $row["isys_logbook__entry_identifier_static"],
                            $row["isys_logbook__changecount"]
                        ),
                    $lcBefore => null,
                    $lcAfter => null
                ];

                // Build changes
                $changes = unserialize($row['isys_logbook__changes']);
                if (empty($changes)) {
                    $return['data'][] = $data;
                }
                foreach ($changes as $change) {
                    $data[$lcBefore] = $change['from'] ?: isys_tenantsettings::get('gui.empty_value', '-');
                    $data[$lcAfter] = $change['to'] ?: isys_tenantsettings::get('gui.empty_value', '-');
                    $return['data'][] = $data;
                    $data = [
                        $lcTitle => null,
                        $lcObjectType => null,
                        $lcCategory => null,
                        $lcDate => null,
                        $lcUser => null,
                        $lcEvent => null
                    ];
                }
            }

            $return['success'] = true;
        } else {
            $return['data'] = '<p class="pb10 pl10"><img src="' . $g_dirs['images'] . 'icons/infobox/blue.png" class="vam" /> ' .
                $this->language->get('LC__CMDB__FILTER__NOTHING_FOUND_STD') . '</p>';
        }

        header('Content-Type: application/json');
        echo isys_format_json::encode($return);

        die;
    }
}
