<?php
// app/controllers/AuthController.php

class AuthController extends Controller {

    public function showLogin(): void {
        Auth::redirectIfLoggedIn();
        $this->view('auth.login', ['title' => 'Login - SINERGI'], null);
    }

    public function doLogin(): void {
        if (!$this->verifyCsrf()) {
            $this->flash('error', 'Token tidak valid.');
            $this->redirect(APP_URL . '/login');
        }

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

        if (empty($username) || empty($password)) {
            $this->flash('error', 'Username dan password wajib diisi.');
            $this->redirect(APP_URL . '/login');
        }

        if (Auth::attempt($username, $password)) {
            $this->redirect(Auth::getDashboardUrl());
        } else {
            $this->flash('error', 'Username atau password salah.');
            $this->redirect(APP_URL . '/login');
        }
    }

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

    public function forbidden(): void {
        http_response_code(403);
        $this->view('public.403', ['title' => 'Akses Ditolak'], null);
    }
}
