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


class Usuarios extends MY_Controller
{
    private $dir = 'usuarios';
    private $nom = 'Usuarios';
    private $dir1 = 'Nuevo usuario';
    private $dir2 = 'Editar usuario';

    private $user_reg = '';

    function __construct()
    {
        parent::__construct();
        if ($this->session->userdata('ubicacion') != $this->dir) {
            $array_items = array('per_page' => NULL, 'sort_order' => NULL, 'sort_by' => NULL,);
            $this->session->unset_userdata($array_items);
            $this->session->set_userdata('ubicacion', $this->dir);
        }

        $this->user_reg = $this->session->userdata('user_reg');
        $this->load->model($this->dir . '_model', 'modelo', TRUE);

        $this->data['dir'] = $this->dir;
        $this->data['dir1'] = $this->dir1;
        $this->data['dir2'] = $this->dir2;
        $this->data['nom'] = $this->nom;
    }


    function index($sort_by = 'username', $sort_order = 'asc', $offset = 0)
    {
        $this->load->helper('text');
        $this->load->library('pagination');
        $this->load->library('table');

        $this->data['fields'] = $this->modelo->getCampos();

        //- search -
        if ($this->get_search($this->dir) != '') $sql['search'] = $this->get_search($this->dir);
        //--
        //- limit -
        $sql['limit'] = $this->get_limit($this->dir);
        //--
        //- sort_order -
        $sql['sort_order'] = $this->get_sort_order($this->dir, $sort_order);
        //--
        //- sort_by -

        $sql['sort_by'] = $this->get_sort_by($this->dir, $sort_by);
        //--
        $sql['offset'] = ($offset > 1) ? $offset : NULL;
        /* - Empresa y Sucursal - */
        if($this->user_reg['group']['name'] != 'admin') {
            $sql['empresa'] = $this->user_reg['company'];
            if($this->user_reg['sucursal'] != 0) {
                $sql['sucursal'] = $this->user_reg['sucursal'];
            }
        }
        /* - Active 1 - Activo | 0 - Eliminado */
        $sql['active'] = 1;

        //var_dump($sql);
        $results = $this->modelo->getAll($sql);

        $this->data['rows'] = $results['rows'];
        $this->data['num_results'] = $results['num_rows'];

        $config = array();
        $config['base_url'] = site_url("admin/" . $this->dir . "/index/$sort_by/$sort_order");
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->data['num_results'];
        $config['per_page'] = $sql['limit'];

        if ($this->session->flashdata('template_msg'))
            $this->data['message'] = $this->session->flashdata('template_msg');

        $this->pagination->initialize($config);

        $this->data['pagination'] = $this->pagination->create_links();
        $this->data['cur_page'] = $this->pagination->cur_page;
        $this->data['pagination_tot'] = ceil(($config['total_rows'] / $this->pagination->per_page));
        $this->data['action'] = site_url('admin/' . $this->dir . '/index');
        $this->data['search'] = $this->session->userdata($this->dir . '_search');
        //print_r($this->session);

        $this->data['onlyAdmin'] = $this->user_reg['group']['name'];
        $this->data['master'] = $this->user_reg['sucursal'];
        $this->template->title($this->data['nombre'], 'Administración');
        $this->template->build('admin/' . $this->dir . '/list', $this->data);
    }

    function restaurar($sort_by = 'username', $sort_order = 'asc', $offset = 0)
    {
        $this->load->helper('text');
        $this->load->library('pagination');
        $this->load->library('table');

        $this->data['fields'] = $this->modelo->getCampos();

        //- search -
        if ($this->get_search($this->dir) != '') $sql['search'] = $this->get_search($this->dir);
        //--
        //- limit -
        $sql['limit'] = $this->get_limit($this->dir);
        //--
        //- sort_order -
        $sql['sort_order'] = $this->get_sort_order($this->dir, $sort_order);
        //--
        //- sort_by -

        $sql['sort_by'] = $this->get_sort_by($this->dir, $sort_by);
        //--
        $sql['offset'] = ($offset > 1) ? $offset : NULL;
        /* - Empresa y Sucursal - */
        if($this->user_reg['group']['name'] != 'admin') {
            $sql['empresa'] = $this->user_reg['company'];
            if($this->user_reg['sucursal'] != 0) {
                $sql['sucursal'] = $this->user_reg['sucursal'];
            }
        }
        /* - Active 1 - Activo | 0 - Eliminado */
        $sql['active'] = 0;

        //var_dump($sql);
        $results = $this->modelo->getAll($sql);

        $this->data['rows'] = $results['rows'];
        $this->data['num_results'] = $results['num_rows'];

        $config = array();
        $config['base_url'] = site_url("admin/" . $this->dir . "/index/$sort_by/$sort_order");
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->data['num_results'];
        $config['per_page'] = $sql['limit'];

        if ($this->session->flashdata('template_msg'))
            $this->data['message'] = $this->session->flashdata('template_msg');

        $this->pagination->initialize($config);

        $this->data['pagination'] = $this->pagination->create_links();
        $this->data['cur_page'] = $this->pagination->cur_page;
        $this->data['pagination_tot'] = ceil(($config['total_rows'] / $this->pagination->per_page));
        $this->data['action'] = site_url('admin/' . $this->dir . '/index');
        $this->data['search'] = $this->session->userdata($this->dir . '_search');
        //print_r($this->session);

        $this->data['onlyAdmin'] = $this->user_reg['group']['name'];
        $this->data['master'] = $this->user_reg['sucursal'];
        $this->template->title($this->data['nombre'], 'Administración');
        $this->template->build('admin/' . $this->dir . '/restaurar', $this->data);
    }

    function edit($id)
    {
        $this->data['ubicacion'] = 'usuarios';
        $this->data['id'] = $id;

        $this->load->model('admin/empresas_model', '', TRUE);
        $sql['habilitado'] = 1;
        $sql['sort_order'] =  'asc';
        $sql['sort_by'] = 'nombre';
        if($this->user_reg['sucursal'] == 'Master' && $id == 0):
            $sql['empresa'] = $this->user_reg['company'];
            $sucursales = $this->empresas_model->getAllList($sql);
            $this->data['sucursales'] = $sucursales['rows'];
        endif;
        $empresas = $this->empresas_model->getAll($sql);
        $this->data['empresas'] = $empresas['rows'];

        $this->data['onlyAdmin'] = $this->user_reg['group']['name'];
        $this->data['master'] = $this->user_reg['sucursal'];

        if ($id != 0) {
            $sql['id'] = $id;
            $results = $this->modelo->getAll($sql);
            $this->data['row'] = $results['rows'][0];
            $this->data['num_results'] = $results['num_rows'];

            $this->session->set_userdata('ubicacion', 'modificar_password');
            $this->data['ubicacion'] = 'modificar_password';

            $sqlSucursales['empresa'] = $results['rows'][0]->company;
            $sqlSucursales['habilitado'] = '1';
            $sucursales = $this->empresas_model->getAllList($sqlSucursales);
            $this->data['sucursales'] = $sucursales['rows'];
        }

        $this->data['action'] = site_url('admin/' . $this->dir . '/update');
        $this->template->title($this->data['nombre'] . ' :: Administración');
        $this->template->build('admin/' . $this->dir . '/edit', $this->data);
    }

    function update()
    {
        $id = $this->input->post('id');

        if ($id == 0):
            $this->form_validation->set_rules('username', 'Usuario', 'required|is_unique[users.username]');
            $this->form_validation->set_message('is_unique', 'El %s ya está ocupado.');
            $this->form_validation->set_rules('password', 'Contraseña', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
            $this->form_validation->set_rules('password_confirm', 'confirme Contraseñaa', 'required');
        else:
            $this->form_validation->set_rules('username', 'Usuario', 'required');
            
            if ( NULL != $this->input->post('password') && !empty($this->input->post('password')) )
            {
				$this->form_validation->set_rules('password', 'Contraseña', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[password_confirm]');
				$this->form_validation->set_rules('password_confirm', 'confirme Contraseñaa', 'required');
			}
        endif;

        if ($this->form_validation->run() == FALSE):
            $this->data['action'] = site_url('admin/' . $this->dir . '/update');
            $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Errores !</h4>" . validation_errors() . "</div>";
            $this->template->title($this->data['nombre'] . ' :: Administración');

            $this->load->model('admin/empresas_model', '', TRUE);
            $sql['habilitado'] = 1;
            $empresas = $this->empresas_model->getAll($sql);
            $this->data['empresas'] = $empresas['rows'];

            $this->data['onlyAdmin'] = $this->user_reg['group']['name'];
            $this->data['master'] = $this->user_reg['sucursal'];
            $this->data['id'] = $id;


            $this->template->build('admin/' . $this->dir . '/edit', $this->data);
        else:
            if ($id == 0):
                $username = strtolower($this->input->post('username'));
                $email = $username.'@'.$username.'.com';
                $password = $this->input->post('password');
                $group = array('2');

                if($this->user_reg['sucursal'] != 'Master'):
                    $additional_data = array(
                        'first_name' => $username,
                        'company' => $this->input->post('company'),
                        'sucursal' => $this->input->post('sucursal'),
                        'active' => $this->input->post('active')
                    );
                else:
                    $additional_data = array(
                        'first_name' => $username,
                        'company' => $this->user_reg['company'],
                        'sucursal' => $this->input->post('sucursal'),
                        'active' => $this->input->post('active')
                    );
                endif;

                if ($this->ion_auth->register($username, $password, $email, $additional_data, $group)):
                    $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Usuario Guardado</div>";
                    $this->session->set_flashdata('template_msg', $this->data['message']);
                else:
                    $error = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
                    if ($error != ""):
                        $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Usuario Guardado: " . $error . "</div>";
                        $this->session->set_flashdata('template_msg', $this->data['message']);
                    endif;
                endif;
                redirect('admin/' . $this->dir . '/index', 'refresh');
            else:
                $user = $this->ion_auth->user($id)->row();

                if($this->user_reg['sucursal'] != 'Master') {
                    if ($this->input->post('username')) $objeto['username'] = $this->input->post('username');
                    if ($this->input->post('company')) $objeto['company'] = $this->input->post('company');
                    if ($this->input->post('sucursal')) $objeto['sucursal'] = $this->input->post('sucursal');
                    $objeto['active'] = $this->input->post('active');
                    if ($this->input->post('password')) $objeto['password'] = $this->input->post('password');
                } else {
                    if ($this->input->post('username')) $objeto['username'] = $this->input->post('username');
                    if ($this->input->post('company')) $objeto['company'] = $this->user_reg['company'];
                    if ($this->input->post('sucursal')) $objeto['sucursal'] = $this->input->post('sucursal');
                    $objeto['active'] = $this->input->post('active');
                    if ($this->input->post('password')) $objeto['password'] = $this->input->post('password');
                }

                $this->ion_auth->update($user->id, $objeto);
                //echo $this->db->last_query();
                $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Modificado</div>";
                $this->session->set_flashdata('template_msg', $this->data['message']);
                redirect('admin/' . $this->dir . '/index', 'refresh');
            endif;
        endif;
    }

    function change_password()
    {
        $this->form_validation->set_rules('password', 'New Password', 'required|min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']|matches[c_password]');
        $this->form_validation->set_rules('c_password', 'Confirm New Password', 'required');

        if ($this->form_validation->run() == false)
        {
            echo "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Error !</h4>".validation_errors()."</div>";
        }
        else
        {
            $id = $this->input->post('id');
            $password = $this->input->post('password');
            $salt       = $this->ion_auth->salt();
            $objeto['password']   = $this->ion_auth->hash_password($password, $salt);
            $this->modelo->update($id,$objeto);
            echo "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Contraseña actualizada</div>";
        }
    }

    function delete()
    {
        $this->modelo->delete($this->input->post('ele'));
        $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Eliminado</div>";
        $this->session->set_flashdata('template_msg', $this->data['message']);
        /*
        $ids = $this->input->post('ele');
        foreach ($ids as $id):
            if ($this->ion_auth->delete_user($id)):
                $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Usuario Eliminado</div>";
                $this->session->set_flashdata('template_msg', $this->data['message']);
            else:
                $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Error !</h4>Al Eliminar Usuario</div>";
                $this->session->set_flashdata('template_msg', $this->data['message']);
            endif;
        endforeach;
        */
        redirect('admin/' . $this->dir . '/index', 'refresh');
    }

    function restore()
    {
        $this->modelo->restore($this->input->post('ele'));
        $this->data['message'] = "<div class='alert alert-block'><a class='close' data-dismiss='alert' href='#'>&times;</a><h4 class='alert-heading'>Info !</h4>Registro Restaurado</div>";
        $this->session->set_flashdata('template_msg', $this->data['message']);
        redirect('admin/' . $this->dir . '/index', 'refresh');
    }

    public function sucursales($empresa)
    {
        $this->load->model('admin/empresas_model', '', TRUE);

        $sql['empresa'] = $empresa;
        $sql['habilitado'] = '1';

        $sucursales = $this->empresas_model->getAllList($sql);
        $this->data['sucursales'] = $sucursales['rows'];

        $this->load->view('admin/usuarios/sucursales', $this->data);
    }
}