<?php 
defined('BASEPATH') or exit ('Ação não permitida');

class Users extends CI_Controller{

    public function __construct(){
        parent::__construct();
        $this->load->model('Email_model', 'email_model');

        //Valid session?
        if (!$this->ion_auth->is_admin()) {
            redirect('restricted/auth');
        }
    }

    public function index(){
        // Get the user id through session
        $user_id = $this->session->user_id;

        $data = array(
            'title' => 'Usuários cadastrados',
            'users' => $this->ion_auth->users()->result(), // get all users
            'styles'  =>  array(
                'css/custom.css',
                'vendor/datatables/dataTables.bootstrap4.min.css',
            ),
            'scripts' => array(
                'js/mask/jquery.mask.min.js',
                'js/mask/custom-mask.js',
                'vendor/datatables/jquery.dataTables.min.js',
                'vendor/datatables/dataTables.bootstrap4.min.js',
            ),
            'messages'                      => $this->core_model->get_all('messages', array('comment_destination' => $user_id)),
            'unread_messages'               => count($this->core_model->get_all('messages', array('comment_destination' => $user_id, 'was_read' => 0))),
            'alerts'                        => $this->core_model->get_all('alerts', array('user_id' => $user_id)),
            'unread_alerts'                 => count($this->core_model->get_all('alerts', array('user_id' => $user_id, 'was_read' => 0))),
        );

        // echo "<pre>";
        // var_dump($data);

        $this->load->view('restricted/layout/header', $data);
        $this->load->view('restricted/admin/users/index');
        $this->load->view('restricted/layout/footer');

    }

    public function core($id = NULL){
        // Get the user id through session
        $user_id = $this->session->user_id;
        
        if(!$id){
            //If not exist add new user
            //Add user
            $id = (int) $id;
            $this->form_validation->set_rules('first_name', 'Nome', 'trim|required|min_length[2]|max_length[45]');
            $this->form_validation->set_rules('last_name', 'Sobrenome', 'trim|required|min_length[2]|max_length[45]');
            $this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[4]|max_length[200]|valid_email|callback_valid_email');
            $this->form_validation->set_rules('phone', 'Telefone', 'trim|min_length[4]|max_length[30]');
            $this->form_validation->set_rules('password', 'Senha', 'trim|required|min_length[4]|max_length[200]');
            $this->form_validation->set_rules('confirm_password', 'Confirme a senha', 'required|min_length[4]|max_length[200]|matches[password]');

            if($this->form_validation->run()){

                $username = '';
                $password = $this->input->post('password');
                $email = $this->input->post('email');
                $additional_data = array(
                    'first_name' => $this->input->post('first_name'),
                    'last_name' => $this->input->post('last_name'),
                    'phone' => $this->input->post('phone'),
                );
                $group = array($this->input->post('group'));
            
                if($this->ion_auth->register($username, $password, $email, $additional_data, $group)){
                    $this->session->set_flashdata('success_message', 'Usuário inserido com sucesso!');
                    $email_params = $this->input->post('first_name') . ' ' . $this->input->post('last_name');
                    $this->email_model->send_email_welcome($email, $email_params);
                } else {
                    $this->session->set_flashdata('error_message', $this->ion_auth->erros());
                }
                redirect('restricted/admin/users');

            } else {
                //Validation error
                $data = array(
                    'title' => "Cadastrar usuário",
                    'groups' => $this->ion_auth->groups()->result(),
                    'scripts' => array(
                        'js/mask/jquery.mask.min.js',
                        'js/mask/custom-mask.js',
                    ),
                    'messages'                      => $this->core_model->get_all('messages', array('comment_destination' => $user_id)),
                    'unread_messages'               => count($this->core_model->get_all('messages', array('comment_destination' => $user_id, 'was_read' => 0))),
                    'alerts'                        => $this->core_model->get_all('alerts', array('user_id' => $user_id)),
                    'unread_alerts'                 => count($this->core_model->get_all('alerts', array('user_id' => $user_id, 'was_read' => 0))),
                );
                $this->load->view('restricted/layout/header', $data);
                $this->load->view('restricted/admin/users/core');
                $this->load->view('restricted/layout/footer');
            }

        } else {
            //Edit user
            //Check if user id exists
            if(!$user = $this->ion_auth->user($id)->row()){
                $this->session->set_flashdata('error_message', 'Usuário não encontrado');
                redirect('restricted/admin/users');
            } else {
                $this->form_validation->set_rules('first_name', 'Nome', 'trim|required|min_length[2]|max_length[45]');
                $this->form_validation->set_rules('last_name', 'Sobrenome', 'trim|required|min_length[2]|max_length[45]');
                $this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[4]|max_length[200]|valid_email|callback_valid_email');
                $this->form_validation->set_rules('phone', 'Telefone', 'trim|min_length[4]|max_length[30]');
                $this->form_validation->set_rules('password', 'Senha', 'trim|min_length[4]|max_length[200]');
                $this->form_validation->set_rules('confirm_password', 'Confirme a senha', 'min_length[4]|max_length[200]|matches[password]');
                
                if($this->form_validation->run()){

                    $data = elements(
                        array(
                            'first_name',
                            'last_name',
                            'email',
                            'phone',
                            'password',
                        ), $this->input->post()
                    );
                    $password = $this->input->post('password');
                    //Don't update the password if it was not edited
                    if(!$password){
                        unset($data['password']);
                    }

                    //Sanitize data
                    $data = html_escape($data);

                    if($this->ion_auth->update($id, $data)){
                        $profile = (int) $this->input->post('group');
                        if($profile){
                            $this->ion_auth->remove_from_group(NULL, $id);
                            $this->ion_auth->add_to_group($profile, $id);
                        }
                        $this->session->set_flashdata('success_message', 'Dados atualizados com sucesso!');
                    } else {
                        $this->session->set_flashdata('error_message', $this->ion_auth->erros());
                    }
                    redirect('restricted/admin/users');

                } else {
                    //Validation error
                    $data = array(
                        'title' => "Editar usuário",
                        'user' => $user,
                        'profile' =>  $this->ion_auth->get_users_groups($user->id)->row(),
                        'groups' => $this->ion_auth->groups()->result(),
                        'scripts' => array(
                            'js/mask/jquery.mask.min.js',
                            'js/mask/custom-mask.js',
                        ),
                        'messages'                      => $this->core_model->get_all('messages', array('comment_destination' => $user_id)),
                        'unread_messages'               => count($this->core_model->get_all('messages', array('comment_destination' => $user_id, 'was_read' => 0))),
                        'alerts'                        => $this->core_model->get_all('alerts', array('user_id' => $user_id)),
                        'unread_alerts'                 => count($this->core_model->get_all('alerts', array('user_id' => $user_id, 'was_read' => 0))),
                    );
                    $this->load->view('restricted/layout/header', $data);
                    $this->load->view('restricted/admin/users/core');
                    $this->load->view('restricted/layout/footer');
                }


            }
        }
    }

    public function valid_email($email){
        $user_id = $this->input->post('user_id');

        if(!$user_id){
            //Add
            if($this->core_model->get_by_id('users', array('email' => $email))){
                $this->form_validation->set_message('valid_email', 'Esse email já existe.');
                return false;
            } else {
                return true;
            }
        } else {
            //Edit
            if($this->core_model->get_by_id('users', array('email' => $email, 'id !=' => $user_id))){
                $this->form_validation->set_message('valid_email', 'Esse email já existe.');
                return false;
            } else {
                return true;
            }
        }
    }

    public function valid_user($username){
        $user_id = $this->input->post('user_id');

        if(!$user_id){
            //Add
            if($this->core_model->get_by_id('users', array('username' => $username))){
                $this->form_validation->set_message('valid_user', 'Esse usuário já existe.');
                return false;
            } else {
                return true;
            }
        } else {
            //Edit
            if($this->core_model->get_by_id('users', array('username' => $username, 'id !=' => $user_id))){
                $this->form_validation->set_message('valid_user', 'Esse usuário já existe.');
                return false;
            } else {
                return true;
            }
        }
    }

    public function delete($user_id = NULL){
        $user_id = (int) $user_id;

        if(!$user_id || !$this->ion_auth->user($user_id)->row()){
            $this->session->set_flashdata('error_message', 'Usuário não encontrado.');
            redirect('restricted/admin/users');
        } else {
            if($this->ion_auth->is_admin($user_id)){
                $this->session->set_flashdata('error_message', 'Esse usuário não pode ser excluído.');
                redirect('restricted/admin/users');
            } 

            if($this->ion_auth->delete_user($user_id)){
                $this->session->set_flashdata('success_message', 'Registro deletado com sucesso!');
                redirect('restricted/admin/users');
            } else {
                $this->session->set_flashdata('error_message', $this->ion_auth->erros());
                redirect('restricted/admin/users');
            }
            
            redirect('restricted/users');
        }
    }

    public function assign_user_view(){
        // Get the user id through session
        $user_id = $this->session->user_id;
                
        $data = array(
            'title' => 'Designar usuário',
            'scripts' => array(
                'js/select2.js'
            ),
            'messages'                      => $this->core_model->get_all('messages', array('comment_destination' => $user_id)),
            'unread_messages'               => count($this->core_model->get_all('messages', array('comment_destination' => $user_id, 'was_read' => 0))),
            'alerts'                        => $this->core_model->get_all('alerts', array('user_id' => $user_id)),
            'unread_alerts'                 => count($this->core_model->get_all('alerts', array('user_id' => $user_id, 'was_read' => 0))),
            'chapters'                      => $this->core_model->get_all('chapters'),
            'users'                         => $this->ion_auth->users()->result(), // get all users
        );

        $this->load->view('restricted/layout/header', $data);
        $this->load->view('restricted/admin/users/assign_user');
        $this->load->view('restricted/layout/footer');
    }

    public function assign_user(){

        if($_POST != '' OR $_POST != NULL){
            $user_id      = $this->input->post('user_id');
            $chapter_id  = $this->input->post('chapter_id');
            $role_id      = $this->input->post('role_id');
            $data = $this->core_model->get_by_id('chapters', array('id' => $chapter_id));

            if($role_id == '1'){
                $this->core_model->update('chapters', array('editor_id' => $user_id), array('id' => $chapter_id));
                // Send email to assigned editor
                $email_params = array(
                    'chapter_title'        => $data->title,
                    'chapter_code'         => $data->unique_code,
                );
                $this->email_model->send_email('assigned_editor', $user_id, $email_params);
            } else {
                $this->core_model->update('chapters', array('reviewer_id' => $user_id), array('id' => $chapter_id));
                // Send email to assigned reviewer
                $email_params = array(
                    'chapter_title'        => $data->title,
                    'chapter_code'         => $data->unique_code,
                );
                $this->email_model->send_email('assigned_reviewer', $user_id, $email_params);
            }

            redirect('restricted/admin/users/assign_user_view');

        } else {
            $this->session->set_flashdata('error_message', 'Dados inválidos. Tente novamente!');
            redirect('restricted/admin/users/assign_user_view');
        }
    }

}

?>