<?php
require APPPATH . '/libraries/REST_Controller.php';

use Restserver\Libraries\REST_Controller;

class MY_Controller extends REST_Controller {

//    public $status_active;
//    public $status_inactive;
    protected $requiredRights = [
        'isAdmin' => false,
        'isSuperAdmin' => false,
        'isSiteAdmin' => false,
    ];

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

        $this->load->library('user_agent');
//        log_message('debug','browser?'. $this->agent->is_browser().';mobile?'.$this->agent->is_mobile());

        if ($this->agent->is_browser()) {
            $this->checkIfAuthenticated();
            $this->load->helper('url');

            $this->load->model('Menu_model');
            $this->load->model('Rbac_permission_model');

            $this->authorizeRoutes();
        }
    }

    protected function view($template, $data, $toString = false) {
        $this->_data['_controller'] = $this->router->fetch_class();
        $this->_data['_view'] = $template;
        $this->_data['_title'] = 'Praise Education Centre';
        $this->_data['_description'] = 'Praise Education Centre';
        return $this->load->view('backend/layouts/main', array_merge($this->_data, $data), $toString);
    }

    private function checkIfAuthenticated() {
        if (!$this->session->userdata('validated')) {
            redirect('login');
        }
    }

    private function authorizeRoutes() {
        if ($this->router->fetch_class() == "errors") {
            echo $this->view('backend/errors/error_404', [], true);
            exit();
        }
        if ($this->requiredRights['isAdmin']) {
            if (!$this->hasAdminRight()) {
                echo $this->view('backend/errors/error_403', [], true);
                exit();
            }
        }
        if ($this->requiredRights['isSuperAdmin']) {
            if (!$this->isSuperAdmin() && !$this->isSiteAdmin()) {
                echo $this->view('backend/errors/error_403', [], true);
                exit();
            }
        }
        if ($this->requiredRights['isSiteAdmin']) {
            if (!$this->isSiteAdmin()) {
                echo $this->view('backend/errors/error_403', [], true);
                exit();
            }
        }
        if (!$this->Rbac_permission_model->check_permission($this->router->fetch_class(), $this->router->fetch_method())) {
            echo $this->view('backend/errors/error_403', [], true);
            exit();
        }
        //        if (!empty($this->authorizedRoutes) && in_array($this->router->fetch_method(), $this->authorizedRoutes)) {
        //            $userId = $this->session->userdata('userid');
        //            $controller = $this->router->fetch_class();
        //            $method = $this->router->fetch_method();
        //            
        //            $qt = $this->input->get('t');
        //            if (isset($qt) && $method === 'index') {
        //                $url = $controller . '?t=' . $qt;
        //            } else if (!isset($qt) && $method === 'index') {
        //                $url = $controller;
        //            } else if (!isset($qt) && $method !== 'index') {
        //                $url = $controller . '/' . $method;
        //            }
        //            $numrows = $this->db->query('select * from roles_tasks main inner join roletasks t on main.task_id=t.id inner join rbac_users_roles ur on main.role_id=ur.role_id where t.url = ? and ur.user_id=?', array($url, $userId))->num_rows();
        //
        //            $result = $numrows >= 1;
        //            if (!$result) {
        //                echo $this->view('backend/errors/error_403', [], true);
        //                exit();
        //            }
        //        }
    }

    //    private function authorizeAdmin()
    //    {
    //        if (!empty($this->authorizedAdmin) && in_array($this->router->fetch_method(), $this->authorizedAdmin)) {
    //            if (!(in_array(Primaryroles::Admin, $this->session->userdata['primaryroles']) || in_array(Primaryroles::SuperAdmin, $this->session->userdata['primaryroles']))) {
    //                echo $this->view('backend/errors/error_403', [], true);
    //                exit();
    //            }
    //        }
    //    }
    //
    //    private function authorizeSuperAdmin()
    //    {
    //        if (!empty($this->authorizedSuperAdmin) && in_array($this->router->fetch_method(), $this->authorizedSuperAdmin)) {
    //            if (!(in_array(Primaryroles::SuperAdmin, $this->session->userdata['primaryroles']))) {
    //                echo $this->view('backend/errors/error_403', [], true);
    //                exit();
    //            }
    //        }
    //    }
    //
    //    private function issueAdminPrivileges()
    //    {
    //
    //        $primaryroles = $this->session->userdata('primaryroles');
    //        $isadmin = in_array(Primaryroles::Admin, $primaryroles);
    //        $issuperadmin = in_array(Primaryroles::SuperAdmin, $primaryroles);
    //        $this->_data['isadmin'] = $isadmin;
    //        $this->_data['issuperadmin'] = $issuperadmin;
    //    }

    public function isAdmin() {
        if ($this->session->userdata('isAdmin') && !$this->session->userdata('isSuperAdmin') && !$this->session->userdata('isSiteAdmin')) {
            return true;
        }
        return false;
    }

    public function isSuperAdmin() {
        if ($this->session->userdata('isSuperAdmin') && !$this->session->userdata('isSiteAdmin')) {
            return true;
        }
        return false;
    }

    public function isSiteAdmin() {
        if ($this->session->userdata('isSiteAdmin')) {
            return true;
        }
        return false;
    }

    public function hasAdminRight() {
        if ($this->session->userdata('isAdmin') || $this->session->userdata('isSuperAdmin') || $this->session->userdata('isSiteAdmin')) {
            return true;
        }
        return false;
    }

    public function getUserId() {
        return $this->session->userdata('userid');
    }

    public function exception_dataNotFound() {
        log_message('error', static::class . ' data not found.');

        echo $this->view('backend/errors/error_400', [], true);
        die();
    }

    public function startsWith($haystack, $needle) {
        $length = strlen($needle);
        return substr($haystack, 0, $length) === $needle;
    }

    public function endsWith($haystack, $needle) {
        $length = strlen($needle);
        if (!$length) {
            return true;
        }
        return substr($haystack, -$length) === $needle;
    }

}
