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

class Profile extends CI_Controller
{
    protected $user;

    public function __construct()
    {
        parent::__construct();
        is_logedin();

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

        $userId = $this->session->userdata('login_session')['user'];
        $this->user = $this->admin->get('tbl_user', ['id_user' => $userId]);
    }

    public function index()
    {
        $data['title'] = "Perfil";
        $data['user'] = $this->user;
        $this->template->load('templates/dashboard', 'profile_view/user', $data);
    }

    private function _validasi()
    {
        $db = $this->admin->get('tbl_user', ['id_user' => $this->input->post('id_user', true)]);
        $username = $this->input->post('username', true);
        $email = $this->input->post('email', true);


        if (!isset($db['username'])) {
            $db['username'] = "";
        }

        if (!isset($db['email'])) {
            $db['email'] = "";
        }


        $uniq_username = $db['username'] == $username ? '' : '|is_unique[tbl_user.username]';
        $uniq_email = $db['email'] == $email ? '' : '|is_unique[tbl_user.email]';

        $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');
        $this->form_validation->set_rules('no_telp', 'Teléfono', 'required|trim|numeric');
    }

    private function _config()
    {
        $config['upload_path']      = "./assets/img/avatar";
        $config['allowed_types']    = 'gif|jpg|jpeg|png';
        $config['encrypt_name']     = TRUE;
        $config['max_size']         = '2048';

        $this->load->library('upload', $config);
    }

    public function setting()
    {
        $this->_validasi();
        $this->_config();

        if ($this->form_validation->run() == false) {
            $data['title'] = "Perfil";
            $data['user'] = $this->user;
            $this->template->load('templates/dashboard', 'profile_view/setting', $data);
        } else {
            $input = $this->input->post(null, true);
            if (empty($_FILES['foto']['name'])) {
                $insert = $this->admin->update('tbl_user', 'id_user', $input['id_user'], $input);
                if ($insert) {
                    set_pesan('Datos modificados correctamente');
                } else {
                    set_pesan('Failed to save your changes');
                }
                redirect('profile/setting');
            } else {
                if ($this->upload->do_upload('foto') == false) {
                    echo $this->upload->display_errors();
                    die;
                } else {
                    if (userdata('foto') != 'user.svg') {
                        $old_image = FCPATH . 'assets/img/avatar/' . userdata('foto');
                        if (!unlink($old_image)) {
                            set_pesan('Error al procesar la imagen.');
                            redirect('profile/setting');
                        }
                    }

                    $input['foto'] = $this->upload->data('file_name');
                    $update = $this->admin->update('tbl_user', 'id_user', $input['id_user'], $input);
                    if ($update) {
                        set_pesan('Datos modificados correctamente.');
                    } else {
                        set_pesan('Failed to save your changes.');
                    }
                    redirect('profile/setting');
                }
            }
        }
    }

    public function password()
    {
        $this->form_validation->set_rules('password_lama', 'Password', 'required|trim');
        $this->form_validation->set_rules('password_baru', 'Password', 'required|trim|min_length[3]|differs[password_lama]');
        $this->form_validation->set_rules('konfirmasi_password', 'Repetir Password', 'matches[password_baru]');

        if ($this->form_validation->run() == false) {
            $data['title'] = "Cambio de Password";
            $this->template->load('templates/dashboard', 'profile_view/password', $data);
        } else {
            $input = $this->input->post(null, true);
            if (password_verify($input['password_lama'], userdata('password'))) {
                $new_pass = ['password' => password_hash($input['password_baru'], PASSWORD_DEFAULT)];
                $query = $this->admin->update('tbl_user', 'id_user', userdata('id_user'), $new_pass);

                if ($query) {
                    set_pesan('Password modificada correctamente.');
                } else {
                    set_pesan('Failed to save your changes.', false);
                }
            } else {
                set_pesan('Password actual incorrecta.', false);
            }
            redirect('profile/password');
        }
    }
}
