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

class Auth extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }

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

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

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

        $user = $this->db->get_where('v_users', ['username' => $username])->row();

        if ($user && password_verify($password, $user->password)) {

            // Decode permissions
            $permissions = json_decode($user->permissions, true);
            if (!is_array($permissions)) {
                $permissions = [];
            }

            $session_data = [
                'user_id'       => $user->id,
                'nama'          => $user->nama,
                'username'      => $user->username,
                'role'          => $user->nama_role,
                'permissions'   => $permissions,
                'logged_in'     => TRUE
            ];

            $this->session->set_userdata($session_data);

            // 🔥 LOG LOGIN BERHASIL
            log_activity(
                'Auth',
                'login',
                'User '.$user->username.' berhasil login',
                'success'
            );

            redirect('dashboard');

        } else {

            // 🔥 LOG LOGIN GAGAL
            log_activity(
                'Auth',
                'login_failed',
                'Login gagal untuk username: '.$username,
                'failed'
            );

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

    public function logout()
    {
        $username = $this->session->userdata('username');

        // 🔥 LOG LOGOUT (SEBELUM DESTROY SESSION)
        log_activity(
            'Auth',
            'logout',
            'User '.$username.' logout',
            'success'
        );

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