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

class Auth extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->model('pengguna_model');
    }

    public function index()
    {
        if ($this->session->userdata('login')) {
            redirect('home');
        }
        $this->load->view('auth/login');
    }

    public function login()
    {
        $username = $this->input->post('username', TRUE);
        $password = $this->input->post('password', TRUE);

        $pengguna = $this->pengguna_model->get_by_username_admin($username);

        if (!empty($pengguna))
        {
            if (password_verify($password, $pengguna['password']))
            {
                $session_data = array(
                    'id_pengguna' => $pengguna['id_pengguna'],
                    'nama_lengkap' => $pengguna['nama_lengkap'],
                    'username' => $pengguna['username'],
                    'login' => TRUE
                );
                $this->session->set_userdata($session_data);

                redirect('home');
            }
            else
            {
                $this->session->set_flashdata('error', '<div class="alert alert-danger">Login gagal</div>');
                redirect('auth');
            }
        }
        else
        {
            $this->session->set_flashdata('error', '<div class="alert alert-danger">Login gagal</div>');
            redirect('auth');
        }
    }

    public function logout()
    {
        if (!$this->session->userdata('login'))
        {
            redirect('auth');
        }

        $this->session->sess_destroy();
        redirect('auth');
    }

    public function password()
    {
        if (!$this->session->userdata('login'))
        {
            redirect('auth');
        }

        $this->form_validation->set_rules('password_lama', 'Password Lama', 'required|callback_cek_password_lama', ['required' => '%s harus diisi']);
        $this->form_validation->set_rules('password_baru', 'Password Baru', 'required|matches[ulangi_password]', ['required' => '%s harus diisi', 'matches' => '%s harus sama']);
        $this->form_validation->set_rules('ulangi_password', 'Ulangi Password', 'required|matches[password_baru]', ['required' => '%s harus diisi', 'matches' => '%s harus sama']);

        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('auth/password');
        }
        else
        {
            $params = [
                'password' => password_hash($this->input->post('password_baru'), PASSWORD_DEFAULT),
            ];
            $this->pengguna_model->update_pengguna($this->session->userdata('id_pengguna'), $params);

            $this->session->set_flashdata('pesan', '<div class="alert alert-success" role="alert">Password berhasil diubah</div>');

            redirect('auth/password');
        }
    }

    public function cek_password_lama($password_lama)
    {
        $user = $this->pengguna_model->get_pengguna($this->session->userdata('id_pengguna'))->row_array();
        if (!password_verify($password_lama, $user['password']))
        {
            $this->form_validation->set_message('cek_password_lama', '{field} salah');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
    public function lupapassword()
    {
        if ($this->session->userdata('login'))
        {
            redirect('home');
        }

        $this->load->view('auth/lupapassword');
    }
    public function aksilupapassword()
    {
        $email = $this->input->post('email');
        $user = $this->db->get_where('pengguna', ['email' => $email])->row_array();

        if ($user)
        {
            $token = base64_encode(random_bytes(32));
            $user_token = [
                'email' => $email,
                'token' => $token,
                'date_created' => time()
            ];

            $this->db->insert('user_token', $user_token);
            $this->_sendEmail($token, 'forgot');

            $this->session->set_flashdata('pesan2', '<div class="alert alert-success" role="alert">Silahkan Cek Email Anda</div>');
            redirect('auth/lupapassword');
        }
        else
        {
            $this->session->set_flashdata('pesan2', '<div class="alert alert-danger" role="alert">Email Anda Belum Terdaftar</div>');
            redirect('auth/lupapassword');
        }
    }


    public function resetPassword()
    {
        $email = $this->input->get('email');
        $token = $this->input->get('token');

        $user = $this->db->get_where('pengguna', ['email' => $email])->row_array();

        if ($user)
        {
            $user_token = $this->db->get_where('user_token', ['token' => $token])->row_array();

            if ($user_token)
            {
                $this->session->set_userdata('reset_email', $email);
                $this->gantipassword();
            }
            else
            {
                $this->session->set_flashdata('pesan2', '<div class="alert alert-danger" role="alert">Token Anda Salah / kadaluarsa.</div>');
                redirect('auth');
            }
        }
        else
        {
            $this->session->set_flashdata('pesan2', '<div class="alert alert-danger" role="alert">Email Verifikasi Salah</div>');
            redirect('auth');
        }
    }
    public function gantipassword()
    {
        if (!$this->session->userdata('reset_email'))
        {
            redirect('auth');
        }
        $this->load->view('auth/ubahpassword');
    }
    public function aksigantipassword()
    {

        if ($this->input->post('password1') != $this->input->post('password2'))
        {
            $this->session->set_flashdata('pesan2', '<div class="alert alert-danger" role="alert">Password tidak sama.</div>');
            redirect('Auth/gantipassword');
        }
        else
        {

            $password = password_hash($this->input->post('password1'), PASSWORD_DEFAULT);
            $email = $this->session->userdata('reset_email');

            $this->db->set('password', $password);
            $this->db->where('email', $email);
            $this->db->update('pengguna');

            $this->session->unset_userdata('reset_email');

            $this->db->delete('user_token', ['email' => $email]);

            $this->session->set_flashdata('pesan2', '<div class="alert alert-success" role="alert">Berhasil ganti Password, silahkan login.</div>');
            redirect('auth');
        }
    }
    private function _sendEmail($token, $type)
    {
        $config = [
            'protocol'  => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_user' => 'ridhoriyadi335@gmail.com',
            'smtp_pass' => 'kmehfkecuzkknlhh',
            'smtp_port' => 465,
            'mailtype'  => 'html',
            'charset'   => 'utf-8',
            'newline'   => "\r\n"
        ];

        $this->email->initialize($config);
        $this->email->from('ridhoriyadi335@gmail.com', 'Reset Password');
        $this->email->to($this->input->post('email'));

        if ($type == 'verify')
        {
            $this->email->subject('Account Verification');
            $this->email->message('Click this link to verify you account : <a href="' . base_url() . 'auth/verify?email=' . $this->input->post('email') . '&token=' . urlencode($token) . '">Activate</a>');
        }

        else if ($type == 'forgot')
        {
            $this->email->subject('Reset Password');
            $this->email->message('Click this link to reset your password : <a href="' . base_url() . 'auth/resetpassword?email=' . $this->input->post('email') . '&token=' . urlencode($token) . '">Reset Password</a>');
        }

        if ($this->email->send())
        {
            return true;
        }
        
        else
        {
            echo $this->email->print_debugger();
            die;
        }
    }
}