<?php
require_once __DIR__ . '/../models/User.php';
class AuthController {
    public function login() {
        $error = '';
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!verify_csrf($_POST['csrf'] ?? '')) { $errors[] = 'Invalid CSRF token.'; }
            $userModel = new User();
            $user = $userModel->getByUsername(trim($_POST['username'] ?? ''));
            if ($user && password_verify($_POST['password'] ?? '', $user['password'])) {
                // set session user
                $_SESSION['user'] = ['id'=>$user['id'],'username'=>$user['username'],'fullname'=>$user['fullname'],'role'=>$user['role']];
                header('Location: index.php?controller=dashboard&action=index');
                exit;
            } else {
                $error = 'Invalid username or password.';
            }
        }
        include __DIR__ . '/../views/auth/login.php';
    }

    public function logout() {
        session_destroy();
        header('Location: index.php?controller=auth&action=login');
        exit;
    }
}
?>