<?php

class DashboardsExporter extends BaseDataExporter
{
    public function isOnlyForAdmin(): bool
    {
        return false;
    }

    public function getData(): array
    {
        $this->addScriptsToArchive();
        $result = [];

        $this->db->reset_query();
        if ($this->exportOnlyUserItems || !$this->isAdmin) {
            $userFilter = ['username' => $this->username];
            $result['dashboard_dashboards'] = $this->db->get_where('dashboard_dashboards', $userFilter)->result_array();
            $result['dashboard_widgets'] = $this->db->get_where('dashboard_widgets', $userFilter)->result_array();
            $result['dashboard_alerts'] = $this->db->get_where('dashboard_alerts', $userFilter)->result_array();
            $ruleIds = array_map(function ($alert) {
                return $alert['ruleid'];
            }, $result['dashboard_alerts']);
            // rules are shared with all users by default, and some alerts created by others, for this reason
            // we need to get not only users' rules but also rules that belong to its alerts
            $result['dashboard_rules'] = $this->db
                ->where($userFilter)
                ->or_where_in('id', $ruleIds)
                ->get('dashboard_rules')
                ->result_array();
            $result['dashboard_scripts'] = $this->db->get('dashboard_scripts')->result_array();
            $result['dashboard_alerts_script'] = $this->db->get('dashboard_alerts_script')->result_array();
        } else {
            $result['dashboard_dashboards'] = $this->db->get('dashboard_dashboards')->result_array();
            $result['dashboard_widgets'] = $this->db->get('dashboard_widgets')->result_array();
            $result['dashboard_alerts'] = $this->db->get('dashboard_alerts ')->result_array();
            $result['dashboard_rules'] = $this->db->get('dashboard_rules')->result_array();
            $result['dashboard_scripts'] = $this->db->get('dashboard_scripts')->result_array();
            $result['dashboard_alerts_script'] = $this->db->get('dashboard_alerts_script')->result_array();
        }

        return [
            'data' => json_encode($result),
            'info' => sprintf(
                '%s, Widgets: %s , Alerts: %s, Rules: %s',
                sizeof($result['dashboard_dashboards']),
                sizeof($result['dashboard_widgets']),
                sizeof($result['dashboard_alerts']),
                sizeof($result['dashboard_rules']),
            ),
        ];
    }
}
