<?php

namespace App\Controllers;

use App\Models\UserModel;

class Auth extends BaseController
{
    public function login(): string|\CodeIgniter\HTTP\RedirectResponse
    {
        if (session()->has('user_id')) {
            return redirect()->to('/dashboard');
        }
        return view('auth/login', [
            'app_name' => $this->getAppName(),
            'error'    => session()->getFlashdata('error'),
        ]);
    }

    public function doLogin(): \CodeIgniter\HTTP\RedirectResponse
    {
        $username = trim($this->request->getPost('username') ?? '');
        $password = $this->request->getPost('password') ?? '';

        if ($username === '' || $password === '') {
            return redirect()->back()->with('error', 'Username dan password wajib diisi.');
        }

        $userModel = new UserModel();
        $user      = $userModel->findByUsername($username);

        if (! $user || ! password_verify($password, $user['password'])) {
            return redirect()->back()->with('error', 'Username atau password salah.');
        }

        if (! $user['is_active']) {
            return redirect()->back()->with('error', 'Akun Anda tidak aktif. Hubungi administrator.');
        }

        session()->set([
            'user_id'  => $user['id'],
            'username' => $user['username'],
            'nama'     => $user['nama'],
            'role'     => $user['role'],
        ]);

        $this->logActivity('login', "User {$user['username']} berhasil login.");

        return redirect()->to('/dashboard');
    }

    public function logout(): \CodeIgniter\HTTP\RedirectResponse
    {
        $this->logActivity('logout', 'User ' . session('username') . ' logout.');
        session()->destroy();
        return redirect()->to('/login')->with('success', 'Anda telah logout.');
    }
}
