<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

/*
 * Generated by CRUDigniter v3.2 
 * www.crudigniter.com
 */

class Role extends MY_BackendController {

    protected $requiredRights = [
        'isAdmin' => true,
        'isSuperAdmin' => false,
        'isSiteAdmin' => false
    ];
    private $_permissions;
//    protected $authorizedRoutes = [];
//    protected $authorizedAdmin = ['index', 'edit'];
//    protected $authorizedSuperAdmin = ['add'];

//    public $datetimeformat = '';

    public function __construct() {
        parent::__construct();
        $this->load->model('Rbac_role_model');
        $this->load->model('Rbac_permission_model');
        $this->load->model('Menu_model');
        foreach ($this->config->item('available_actions') as $action) {
            $this->_permissions[$action] = $this->Rbac_permission_model->check_permission($this->router->fetch_class(), $action);
        }
//        DATETIME_FORMAT = $this->config->item('datetimeformat');
    }

    /*
     * Listing of roles
     */

    public function index() {
        $params['limit'] = RECORDS_PER_PAGE;
        $params['offset'] = ($this->input->get('per_page')) ? $this->input->get('per_page') : 0;

        $config = $this->config->item('pagination');
        $config['base_url'] = site_url('role/index?');
        $config['total_rows'] = $this->Rbac_role_model->get_all_roles_count();
        $this->pagination->initialize($config);

        $data['roles'] = $this->Rbac_role_model->get_all_roles($params);

        $template = 'backend/role/index';
        $data['permissions'] = $this->_permissions;
        $this->view($template, $data);
    }

    /*
     * Adding a new role
     */

    public function add() {
        $this->load->library('form_validation');

        $this->form_validation->set_rules('name', 'Name', 'required');

        if ($this->form_validation->run()) {
            $posts = $this->input->post();
            $params = array(
//                'status' => $this->input->post('status'),
                'name' => $posts['name'],
                'isAdmin' => array_key_exists('isAdmin', $posts) ? $posts['isAdmin'] : 0,
                'isTenant' => array_key_exists('isTenant', $posts) ? $posts['isTenant'] : 0,
                'permissions' => $posts['tasks'],
//                'createdate' => date(DATETIME_FORMAT),
//                'updatedate' => date(DATETIME_FORMAT),
            );

            $role_id = $this->Rbac_role_model->add_role($params);
//            $tasks = $this->input->post('tasks');
//            if (isset($tasks)) {
//                $data = array();
//                foreach ($tasks as $k => $v) {
//                    $data[] = array('task_id' => $v, 'role_id' => $role_id);
//                }
//                $this->db->insert_batch('roles_tasks', $data);
//            }
            redirect('role');
        } else {
            $template = 'backend/role/add';
//            $data['tasks'] = $this->Roletask_model->get_all_roletasks();
            $data['tasks'] = $this->Menu_model->get_all_menu_list();
            $data['perm'] = $this->Rbac_permission_model->get_all_permissions();
            $data['isAdmin'] = $this->session->userdata('isAdmin');
            $data['isSuperAdmin'] = $this->session->userdata('isSuperAdmin');
            $data['isSiteAdmin'] = $this->session->userdata('isSiteAdmin');
            $data['permissions'] = $this->_permissions;
            $this->view($template, $data);
        }
    }

    /*
     * Editing a role
     */

    public function edit($id) {
        // check if the role exists before trying to edit it
        $data['role'] = $this->Rbac_role_model->get_role($id);
        if (isset($data['role']['id'])) {
            $this->load->library('form_validation');

            $this->form_validation->set_rules('name', 'Name', 'required');

            if ($this->form_validation->run()) {
                $posts = $this->input->post();
                $params = array(
                    'status' => $posts['status'],
                    'name' => $posts['name'],
                    'isAdmin' => array_key_exists('isAdmin', $posts) ? $posts['isAdmin'] : 0,
                    'isTenant' => array_key_exists('isTenant', $posts) ? $posts['isTenant'] : 0,
                    'permissions' => $posts['tasks'],
//                    'updatedate' => date(DATETIME_FORMAT),
                );

                $this->Rbac_role_model->update_role($params, $id);

//                $tasks = $this->input->post('tasks');
//                if (isset($tasks) && !empty($tasks)) {
//                    unset($params);
//                    //delete current records first:
//                    $this->Roles_task_model->delete_roles_task_by_role($id);
//                    foreach ($tasks as $k => $v) {
//                        $params[] = array('role_id' => $id, 'task_id' => $v);
//                    }
//                    $this->Roles_task_model->add_roles_task_batch($params);
//                }
                redirect('role');
            } else {
//                $roletasks = $this->db->query('select rt.role_id,rt.task_id from roles r left join roles_tasks rt on r.id = rt.role_id where r.id=?', $id)->result_array();
//                if (isset($roletasks) && !empty($roletasks)) {
//                    foreach ($alltasks as $k => $v) {
//                        $checked = array('checked' => 0);
//                        foreach ($roletasks as $k1 => $v1) {
//                            if ($v['id'] == $v1['task_id']) {
//                                $checked = array('checked' => 1);
//                            }
//                        }
//                        $alltasks[$k] = array_merge($alltasks[$k], $checked);
//                    }
//                }
//                $data['tasks'] = $alltasks;
//                $alltasks = $this->Roletask_model->get_all_roletasks();
                $data['tasks'] = $this->Menu_model->get_all_menu_list();
                $data['perm'] = $this->Rbac_permission_model->get_all_permissions();
                $data['isAdmin'] = $this->session->userdata('isAdmin');
                $data['isSuperAdmin'] = $this->session->userdata('isSuperAdmin');
                $data['isSiteAdmin'] = $this->session->userdata('isSiteAdmin');
                $template = 'backend/role/edit';
//                $data['backendroleids'] = $this->config->item('backendroleids');
                $data['selected'] = $this->Rbac_role_model->permissions(array($id));
                $data['permissions'] = $this->_permissions;
                $this->view($template, $data);
            }
        } else
            show_error('The role you are trying to edit does not exist.');
    }

}
