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

require_once APPPATH . 'modules/dashboard/models/entities/CF_Dashboard.php';

class Dashboardsapi extends Cf_REST_Controller
{
    public $username = '';
    private $roles = null;
    private $rest = null;

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

        $this->load->model('dashboard_model');
        $this->rest = Cf_RestInstance::getRestClient();
        $this->username = $this->session->userdata('username');
    }

    public function dashboards_get($dashboardId = '')
    {
        $this->load->model('Authentication_model');
        $filter = [];
        $filter['username'] = $this->session->userdata('username');

        if (!empty($dashboardId)) {
            $filter['id'] = intval($dashboardId);
        }

        try {
            $filter['roles'] = $this->authentication_model->getRolesForUser($filter['username']);
            $result = $this->dashboard_model->get_user_allowed_dashboards($filter);
            if (empty($result)) {
                $message = $this->lang->line('dashboard_not_exist');
                log_message('debug', 'Failed retrieving dashboards, error: ' . $message);
                respond_internal_error($message);
                return;
            }

            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Failed retrieving dashboards, error: ' . $message);
            respond_internal_error($message);
        }
    }

    public function userselected_get()
    {
        $filter = [];
        $filter['username'] = $this->session->userdata('username');

        try {
            $result = $this->dashboard_model->get_user_selection($filter);
            if (empty($result)) {
                log_message('debug', 'Failed retrieving user selection, error: ' . $message);
                respond_internal_error($message);
                return;
            }

            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Failed retrieving users, error: ' . $message);
            respond_internal_error($message);
        }
    }

    public function selecteduser_post($id = '')
    {
        $filter = [];
        $filter['username'] = $this->session->userdata('username');

        if (!empty($id)) {
            $filter['id'] = intval($id);
        }

        try {
            $obj = $this->dashboard_model->set_user_selection($filter);
        } catch (Exception $e) {
            respond_internal_error($e->getMessage());
        }

        if (!$obj) {
            //not able to get inserted dash
            $errors = $this->dashboard_model->getErrors();
            $data = json_encode($errors);
            respond_internal_error($data);
            return;
        } else {
            $json = json_encode($obj);
            respond_ok($json);
            /*
            $data = array();
            $data[0] = array('dashboardId' => $obj->id, 'text' => $this->lang->line('dashboard_save_success'), 'errorCode' => 200);
            respond_ok(json_encode($data));
            return;*/
        }
    }

    public function resetselected_post($id = '')
    {
        $filter = [];
        if (!empty($id)) {
            $filter['dashboard'] = intval($id);
        }

        try {
            $result = $this->dashboard_model->reset_user_selection($filter);
            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Unable to reset dashboard. Error: ' . $message);
            respond_internal_error($e->getMessage());
        }
    }

    public function savedashboard_post($id = '')
    {
        $data = json_decode($this->request->body, true);
        $data['username'] = $this->session->userdata('username');

        $overwrite = false;
        if (!empty($id)) {
            $overwrite = true;
        }

        try {
            $obj = $this->dashboard_model->save_dashboard($data, $overwrite);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Unable to save dashboard. Error: ' . $message);
            respond_internal_error($message);
            return;
        }

        if (!isset($obj)) {
            //not able to get inserted dash
            $errors = $this->dashboard_model->getErrors();
            $data = json_encode($errors);
            respond_internal_error($data);
            return;
        } else {
            $data = [];
            $data[0] = [
                'dashboardId' => $obj->id,
                'text' => $this->lang->line('dashboard_save_success'),
                'errorCode' => 200,
            ];
            respond_ok(json_encode($data));
            return;
        }
    }

    public function cloneDashboard_post($id)
    {
        $id = (int) $id;
        $data = json_decode($this->request->body, true);
        $data['username'] = $this->session->userdata('username');
        $newID = $this->dashboard_model->clone_dashboard($data, $id);
        respond_ok($newID);
    }

    public function removedashboard_post($id = '')
    {
        $filter = [];
        $filter['username'] = $this->session->userdata('username');

        if (!empty($id)) {
            $filter['id'] = intval($id);
        }

        try {
            $result = $this->dashboard_model->remove_dashboard($filter);
            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Unable to delete dashboard. Error: ' . $message);
            respond_internal_error($message);
        }
    }

    public function addwidget_post($id = '')
    {
        $data = [];
        $data['username'] = $this->session->userdata('username');

        if (!empty($id)) {
            $data['id'] = intval($id);
        }

        try {
            $result = $this->dashboard_model->add_widget($data);
            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Unable to add widget to dashboard. Error: ' . $message);
            respond_internal_error($message);
        }
    }

    public function deletewidget_post($id = '')
    {
        $data = [];
        $data['username'] = $this->session->userdata('username');

        $data['id'] = intval($id);

        try {
            $result = $this->dashboard_model->delete_widget($data);
            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Unable to delete widget from dashboards. Error: ' . $message);
            respond_internal_error($message);
        }
    }

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

        $filter = [];
        $filter['username'] = $this->session->userdata('username');

        if (!empty($id)) {
            $filter['id'] = intval($id);
        }

        try {
            $result = $this->dashboard_model->reorder_widgets($filter, $data);
            $json = json_encode($result);
            respond_ok($json);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('debug', 'Unable to update dashboard. Error: ' . $message);
            respond_internal_error($message);
        }
    }

    public function users_get()
    {
        $this->load->model('Authentication_model');
        $users = $this->authentication_model->getAllUsers(1, 10000);
        //remove useless fields
        array_walk($users, function (&$user) {
            $user = ['id' => $user['id']];
        });
        respond_ok(json_encode($users));
    }

    public function roles_get()
    {
        $this->load->model('Authentication_model');
        respond_ok(json_encode($this->authentication_model->getAllRoles()));
    }

    public function user_roles_get()
    {
        $this->load->model('Authentication_model');
        respond_ok(json_encode($this->authentication_model->getRolesForUser($this->username)));
    }
}
