<?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');
        $this->load->library('session');
        $this->load->helper('url');

        if ($this->router->fetch_class() != 'auth') {
            // Cek sudah login?
            if (!$this->session->userdata('logged_in')) {
                redirect('auth');
            }

            // Cek timeout 1 jam (3600 detik)
            if (time() - $this->session->userdata('last_activity') > 3600) {
                $this->session->sess_destroy();
                $this->session->set_flashdata('error', 'Sesi Anda sudah habis, silakan login kembali.');
                redirect('auth');
            } else {
                // Update aktivitas terakhir
                $this->session->set_userdata('last_activity', time());
            }
        }
    }

    public function index() {
        // Kalau sudah login, langsung redirect sesuai role
        if ($this->session->userdata('logged_in')) {
    if ($this->session->userdata('role') == 'admin') {
        redirect('dashboard');
    } else {
        redirect('dashboard/user');
    }
}
        $this->load->view('Auth/Login');
    }

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

        $user = $this->User_model->login($username, $password);

        // setelah user berhasil login
        if ($user) {
            $this->session->set_userdata([
                'user_id'      => $user->id,
                'nama_lengkap' => $user->nama_lengkap,
                'username'     => $user->username,
                'email'        => $user->email,
                'job'          => $user->job,
                'role'         => $user->role,
                'dob'          => $user->dob,
                'created_at'   => $user->created_at,
                'foto'         => $user->foto,
                'logged_in'    => true
            ]);

            // Redirect sesuai role
            if ($user->role === 'admin') {
                redirect('dashboard');
            } elseif ($user->role === 'user') {
                redirect('dashboard/user');
            }

        } else {
            $this->session->set_flashdata('error', 'Username atau password salah!');
            redirect('auth');
        }
    }

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