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

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

        if ($this->session->userdata('is_logged_in')) {
            redirect('dashboard');
        }
    }

    public function index()
    {
        $this->form_validation->set_rules('username', 'Username', 'required|trim|max_length[50]');
        $this->form_validation->set_rules('password', 'Password', 'required');

        if ($this->form_validation->run() === FALSE) {
            $this->load->view('template/login', ['title' => 'Login | ' . app_name()]);
            return;
        }

        $username   = strtolower(trim((string) $this->input->post('username', TRUE)));
        $password   = (string) $this->input->post('password');
        $ip_address = $this->input->ip_address();

        // Cek lockout
        if ($this->User_model->is_locked_out($username, $ip_address)) {
            $this->session->set_flashdata('login_error',
                'Terlalu banyak percobaan login. Silakan tunggu ' .
                User_model::LOCKOUT_WINDOW_MINUTES . ' menit sebelum mencoba lagi.');
            $this->session->set_flashdata('old_username', $username);
            redirect('login');
            return;
        }

        $user = $this->User_model->get_by_username($username);

        if (!$user || !password_verify($password, $user->password_hash)) {
            $this->User_model->record_attempt($username, $ip_address);
            $attempts_left = User_model::MAX_ATTEMPTS -
                $this->User_model->count_recent_attempts($username, $ip_address);

            $msg = 'Username atau password tidak sesuai.';
            if ($attempts_left > 0 && $attempts_left <= 2) {
                $msg .= " Sisa percobaan: <strong>{$attempts_left}</strong>.";
            }

            $this->session->set_flashdata('login_error', $msg);
            $this->session->set_flashdata('old_username', $username);
            redirect('login');
            return;
        }

        // Login sukses
        $this->User_model->clear_attempts($username);
        $this->User_model->update_last_login($user->id_user);

        $this->session->set_userdata([
            'is_logged_in' => TRUE,
            'id_user'      => $user->id_user,
            'username'     => $user->username,
            'full_name'    => $user->nama_lengkap,
            'role'         => $user->role,
        ]);

        redirect('dashboard');
    }
}

