<?php

namespace App\Controllers\Auth;

use App\Controllers\BaseController;
use App\Models\ActivityLogModel;

class LoginController extends BaseController
{
    public function loginView()
    {
        if (auth()->loggedIn()) {
            return $this->redirectAfterLogin();
        }
        return view('auth/login', ['title' => 'Masuk']);
    }

    public function loginAction()
    {
        $identity = trim($this->request->getPost('identity') ?? '');
        $password = $this->request->getPost('password') ?? '';
        $remember = (bool) $this->request->getPost('remember');

        if (empty($identity) || empty($password)) {
            return redirect()->back()->withInput()
                ->with('error', 'Email/NIM dan kata sandi wajib diisi.');
        }

        $isEmail     = str_contains($identity, '@');
        $credentials = [
            ($isEmail ? 'email' : 'username') => $identity,
            'password'                         => $password,
        ];

        $result = auth()->attempt($credentials, $remember);

        if (! $result->isOK()) {
            model(ActivityLogModel::class)->record('login_failed');
            return redirect()->back()->withInput()
                ->with('error', 'Email/NIM atau kata sandi salah.');
        }

        $user    = auth()->user();
        $profile = model('UserProfileModel')->findByUserId($user->id);

        if ($profile && $profile['status'] === 'inactive') {
            auth()->logout();
            return redirect()->to('/login')
                ->with('error', 'Akun Anda tidak aktif. Hubungi administrator.');
        }

        model(ActivityLogModel::class)->record('login', $user->id);

        return $this->redirectAfterLogin();
    }

    public function logoutAction()
    {
        if (auth()->loggedIn()) {
            model(ActivityLogModel::class)->record('logout', auth()->user()->id);
            auth()->logout();
        }
        return redirect()->to('/login')->with('success', 'Anda telah keluar.');
    }

    private function redirectAfterLogin()
    {
        $user = auth()->user();

        if ($user->inGroup('super_admin') || $user->inGroup('admin')) {
            return redirect()->to('/admin');
        }

        return redirect()->to(session()->getTempdata('beforeLoginUrl') ?? '/');
    }
}
