<?php

namespace App\Controllers\Admin;

use App\Core\Auth;
use App\Core\Controller;
use App\Core\Csrf;
use App\Models\AdminUserModel;

class AuthController extends Controller
{
    public function loginForm(): void
    {
        // Kalau sudah login, langsung lempar ke dashboard
        if (Auth::check()) {
            $this->redirect('admin');
            return;
        }

        $this->view('admin/auth/login', [
            'error' => $_SESSION['flash']['message'] ?? null,
        ]);
        unset($_SESSION['flash']);
    }

    public function login(): void
    {
        $this->verifyCsrf();

        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

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

        if (!$user || !password_verify($password, $user['password'])) {
            $this->setFlash('error', 'Username atau password salah.');
            $this->redirect('admin/login');
            return;
        }

        Auth::login($user);
        $userModel->updateLastLogin((int) $user['id']);

        $this->redirect('admin');
    }

    public function logout(): void
    {
        Auth::logout();
        $this->redirect('admin/login');
    }
}
