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

class User extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        is_logedin();
        
        if (!is_admin()) {
            redirect('dashboard');
        }

        $this->load->model('Admin_model', 'admin');
        $this->load->library('form_validation');
    }

    public function index()
    {
        $data['title'] = "Mantenedor de Usuarios";
        $data['users'] = $this->admin->getUsers(userdata('id_user'));

        $data['entidades'] = $this->admin->get('tbl_entidades', null);

        $this->template->load('templates/dashboard', 'user_view/data', $data);
    }

    function funcValidarRutLocal($rut) 
    {
        return funcValidarRut($rut);
    }


    private function _validasi($mode)
    {
        $this->form_validation->set_rules('name', 'Nombre', 'required|trim');
        $this->form_validation->set_rules('no_telp', 'Teléfono', 'required|trim');
        $this->form_validation->set_rules('role', 'Role', 'required|trim');
        $this->form_validation->set_rules('id_entidad', 'Entidad', 'required|trim');

        if ($mode == 'add') {
            $this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[tbl_user.username]|alpha_numeric');
            $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email|is_unique[tbl_user.email]');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[3]|trim');
            $this->form_validation->set_rules('password2', 'Confirmación Password', 'matches[password]|trim');
            $this->form_validation->set_rules('name', 'Nombre', 'required|trim|is_unique[tbl_user.name]');
            $this->form_validation->set_rules('rut', 'RUT', 'required|trim|is_unique[tbl_user.rut]|callback_funcValidarRutLocal');
        } else {
            

            $db = $this->admin->get('tbl_user', ['id_user' => $this->input->post('id_user', true)]);

            $username = $this->input->post('username', true);
            $name = $this->input->post('name', true);
            $email = $this->input->post('email', true);
            $rut = $this->input->post('rut', true);

            if ( isset($db['username']) && isset($db['email']) && isset($db['name']) && isset($db['rut']) ) {
                
            } else {
                $db['username'] = '';
                $db['email'] = '';  
                $db['name'] = '';  
                $db['rut'] = '';  
            }            

            $uniq_username = $db['username'] == $username ? '' : '|is_unique[tbl_user.username]';
            $uniq_email = $db['email'] == $email ? '' : '|is_unique[tbl_user.email]';
            $uniq_name = $db['name'] == $name ? '' : '|is_unique[tbl_user.name]';
            $uniq_rut = $db['rut'] == $rut ? '' : '|is_unique[tbl_user.rut]';
            
            $this->form_validation->set_rules('username', 'Username', 'required|trim|alpha_numeric' . $uniq_username);
            $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email' . $uniq_email);
            $this->form_validation->set_rules('name', 'Nombre', 'required|trim' . $uniq_name);
            $this->form_validation->set_rules('rut', 'RUT', 'required|trim' . $uniq_rut ."|callback_funcValidarRutLocal");

        }
    }

    public function add()
    {
        $this->_validasi('add');


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

            $data['title'] = "Mantenedor de Usuarios";

            $data['entidades'] = $this->admin->get('tbl_entidades', null);

            $this->template->load('templates/dashboard', 'user_view/add', $data);

        } else {

            $username = userdata('username');
            
            $input = $this->input->post(null, true);

            if (isset($input['chk_finanzas'])){
                $chk_finanzas = $input['chk_finanzas'];
            }
            else {
                $chk_finanzas = "";
            }
                
            $input_data = [
                'name'          => $input['name'],
                'username'      => strtoupper( $input['username'] ),
                'email'         => $input['email'],
                'no_telp'       => $input['no_telp'],
                'role'          => $input['role'],
                'password'      => password_hash($input['password'], PASSWORD_DEFAULT),
                'created_at'    => date('Y-m-d H:i:s'),
                'foto'          => 'user.svg',
                'rut'           => $input['rut'],
                'id_entidad'    => $input['id_entidad'],
                'is_active'     => 0,
                'finanzas'      => $chk_finanzas == 'on' ? 1 :  0,
                'fecha_creacion'        => date('Y-m-d'),
                'hora_creacion'         => date('H:i:s'),
                'usuario_creacion'      => $username,
            ];

            if ($this->admin->insert('tbl_user', $input_data)) {
                set_pesan('Usuario Registrado Correctamente');
                redirect('user');
            } else {
                set_pesan('Something Went Wrong', false);
                redirect('user/add');
            }
        }
    }

    public function edit($getId)
    {
        $id = encode_php_tags($getId);
        $this->_validasi('edit');

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

            $data['title'] = "Mantenedor de Usuarios";

            $data['entidades'] = $this->admin->get('tbl_entidades', null);

            $data['user'] = $this->admin->get('tbl_user', ['id_user' => $id]);
            $this->template->load('templates/dashboard', 'user_view/edit', $data);
        } else {
            $input = $this->input->post(null, true);

            //log_message('error', 'input: ' . $input['chk_password']  );

            if (isset($input['chk_password'])){
                $chk_password = $input['chk_password'];
            }
            else {
                $chk_password = "";
            }

            if (isset($input['chk_finanzas'])){
                $chk_finanzas = $input['chk_finanzas'];
            }
            else {
                $chk_finanzas = "";
            }
            

            if ( $chk_password == 'on') {
                $input_data = [
                    //'name'          => $input['name'],
                    'username'      => $input['username'],
                    'email'         => $input['email'],
                    'no_telp'       => $input['no_telp'],
                    'role'          => $input['role'],
                    'rut'           => $input['rut'],
                    'id_entidad'    => $input['id_entidad'],
                    'password'      => password_hash($input['password'], PASSWORD_DEFAULT),
                    'finanzas'      => $chk_finanzas == 'on' ? 1 :  0
                ];    
            }
            else {
                $input_data = [
                    //'name'          => $input['name'],
                    'username'      => $input['username'],
                    'email'         => $input['email'],
                    'no_telp'       => $input['no_telp'],
                    'role'          => $input['role'],
                    'rut'           => $input['rut'],
                    'id_entidad'    => $input['id_entidad'],
                    'finanzas'      => $chk_finanzas == 'on' ? 1 :  0
                ];
            }

            
            if ($this->admin->update('tbl_user', 'id_user', $id, $input_data)) {
                set_pesan('Usuario Actualizado Correctamente');
                redirect('user');
            } else {
                set_pesan('Something went wrong', false);
                redirect('user/edit/' . $id);
            }
        }
    }

    public function delete($getId)
    {
        $id = encode_php_tags($getId);
        if ($this->admin->delete('tbl_user', 'id_user', $id)) {
            set_pesan('Usuario Eliminado Correctamente');
        } else {
            set_pesan('Something went wrong', false);
        }
        redirect('user');
    }

    public function toggle($getId)
    {
        $id = encode_php_tags($getId);
        $status = $this->admin->get('tbl_user', ['id_user' => $id])['is_active'];
        $toggle = $status ? 0 : 1; 
        $pesan = $toggle ? 'Usuario Habilitado' : 'Usuario Bloqueado';

        if ($this->admin->update('tbl_user', 'id_user', $id, ['is_active' => $toggle])) {
            set_pesan($pesan);
        }
        redirect('user');
    }
}
