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

class Auth extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('User_model', 'users');
	}

	public function login()
	{
		if ($this->session->userdata('user')) {
			redirect('dashboard');
		}

		if ($this->input->method(TRUE) === 'POST') {
			$this->form_validation->set_rules('username', 'Username', 'trim|required');
			$this->form_validation->set_rules('password', 'Password', 'required');

			if ($this->form_validation->run()) {
				$username = $this->input->post('username', TRUE);
				$password = (string) $this->input->post('password', FALSE);

				$user = $this->users->find_by_username($username);
				if ($user && password_verify($password, $user->password_hash)) {
					$this->session->set_userdata('user', array(
						'id' => (int) $user->id,
						'username' => $user->username,
						'name' => $user->name,
					));
					redirect('admin');
				}

				$this->session->set_flashdata('error', 'Username atau password salah.');
				redirect('login');
			}
		}

		$this->load->view('auth/login', array(
			'title' => 'Login',
		));
	}

	public function logout()
	{
		$this->session->sess_destroy();
		redirect('login');
	}
}
