<?php

use app\libraries\Userstamp;

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

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

class User extends MY_BackendController {
//    protected $authorizedRoutes = [];
//    protected $authorizedAdmin = ['index', 'add', 'edit'];
    protected $requiredRights = [
        'isAdmin' => true,
        'isSuperAdmin' => false,
        'isSiteAdmin' => false
    ];
    private $_permissions;

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

    /*
     * Listing of users
     */

    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('user/index?');
        $config['total_rows'] = $this->Rbac_user_model->get_all_users_count();
        $this->pagination->initialize($config);

        $data['users'] = $this->Rbac_user_model->get_all_users($params);
        

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

    /*
     * Adding a new backend/user
     */

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

        $this->form_validation->set_rules('firstname', 'First Name', 'required');
        $this->form_validation->set_rules('lastname', 'Last Name', 'required');

        if ($this->form_validation->run()) {
            $params = array(
                'status' => $this->input->post('status'),
                'eng_firstname' => $this->input->post('firstname'),
                'eng_lastname' => $this->input->post('lastname'),
                'username' => $this->input->post('username'),
                'password' => sha1($this->input->post('password')),
//                'createdate' => date(DATETIME_FORMAT),
//                'updatedate' => date(DATETIME_FORMAT),
            );

            $user_id = $this->Rbac_user_model->add_user($params);
            $roles = $this->input->post('roles');
            if (isset($roles)) {
                $data = array();
                foreach ($roles as $k => $v) {
                    $data[] = array('user_id' => $user_id, 'role_id' => $v);
                }

                $this->Rbac_user_role_model->add_users_role_batch($data);
            }
            redirect('user');
        } else {
            $template = 'backend/user/add';
            $data['roles'] = $this->Rbac_role_model->get_all_roles();
            $data['permissions'] = $this->_permissions;
            $this->view($template, $data);
        }
    }

    /*
     * Editing a user
     */

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

            $this->form_validation->set_rules('firstname', 'First Name', 'required');
            $this->form_validation->set_rules('lastname', 'Last Name', 'required');

            if ($this->form_validation->run()) {
                $params = array(
                    'status' => $this->input->post('status'),
                    'eng_firstname' => $this->input->post('firstname'),
                    'eng_lastname' => $this->input->post('lastname'),
                    'username' => $this->input->post('username'),
//                    'updatedate' => date(DATETIME_FORMAT),
                );

                $password = $this->input->post('password');
                if (isset($password) && !empty($password)) {
                    $params = array_merge($params, array('password' => sha1($this->input->post('password'))));
                }

                $this->Rbac_user_model->update_user($id, $params);
                $roles = $this->input->post('roles');
                if (isset($roles) && !empty($roles)) {
                    unset($params);
                    //delete current records first:
                    $this->Rbac_user_role_model->delete_users_role_by_user($id);
                    foreach ($roles as $k => $v) {
                        $params[] = array('user_id' => $id, 'role_id' => $v);
                    }
                    $this->Rbac_user_role_model->add_users_role_batch($params);
                }
                redirect('user');
            } else {
                $allroles = $this->Rbac_role_model->get_all_roles();
                $userroles = $this->Rbac_user_model->roles($id);
                if (count($userroles) > 0) {
                    foreach ($allroles as $k => $v) {
                        $allroles[$k]['checked'] = in_array($v['id'], $userroles['roles']);
                    }
                }
//                $userroles = $this->db->query('select ur.user_id,ur.role_id from users u left join users_roles ur on u.id = ur.user_id where u.id=?', $id)->result_array();
//                if (isset($userroles) && !empty($userroles)) {
//                    foreach ($allroles as $k => $v) {
//                        $checked = array('checked' => 0);
//                        foreach ($userroles as $k1 => $v1) {
//                            if ($v['id'] == $v1['role_id']) {
//                                $checked = array('checked' => 1);
//                            }
//                        }
//                        $allroles[$k] = array_merge($allroles[$k], $checked);
//                    }
//                }
                $data['roles'] = $allroles;
                $data['permissions'] = $this->_permissions;
                $template = 'backend/user/edit';
                $this->view($template, $data);
            }
        } else
            show_error('The user you are trying to edit does not exist.');
    }

}
