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

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        $this->load->model('User_model');
        $this->load->helper(['url', 'form']);
    }

    public function login() {
        // Sudah login → redirect
        if ($this->session->userdata('user_id')) {
            redirect('receipt');
            return;
        }

        if ($this->input->post()) {
            $username = trim($this->input->post('username'));
            $password = $this->input->post('password');
            $user     = $this->User_model->get_by_username($username);

            if ($user && password_verify($password, $user->password)) {
                $this->session->set_userdata([
                    'user_id'   => $user->id,
                    'user_name' => $user->name,     // dipakai main.php
                    'username'  => $user->username,
                    'role'      => $user->role,      // dipakai main.php
                ]);
                $this->User_model->update_last_login($user->id);
                redirect('receipt');
            } else {
                $this->session->set_flashdata('error', 'Username atau password salah.');
                redirect('auth/login');
            }
            return;
        }

        $this->load->view('auth/login');
    }

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