<?php
/**
 * AuthController - Login e logout admin
 * Localização: /app/controllers/AuthController.php
 */

class AuthController extends Controller
{
    public function loginForm(): void
    {
        if (!empty($_SESSION['admin_id'])) {
            $this->redirect(admin_url('dashboard'));
            return;
        }
        $this->view('admin/login', [
            'pageTitle' => 'Login - OFFICE Admin',
        ], 'raw');
    }

    public function login(): void
    {
        $this->validateCsrf();
        $email = trim($this->input('email',''));
        $senha = $this->input('senha','');

        $userModel = $this->model('Usuario');
        $user = $userModel->autenticar($email, $senha);

        if (!$user) {
            $this->setFlash('error', 'Credenciais inválidas');
            $this->redirect(admin_url('login'));
            return;
        }

        $_SESSION['admin_id']    = $user['id'];
        $_SESSION['admin_nome']  = $user['nome'];
        $_SESSION['admin_email'] = $user['email'];
        $_SESSION['admin_perfil']= $user['perfil'];

        $this->redirect(admin_url('dashboard'));
    }

    public function logout(): void
    {
        unset($_SESSION['admin_id'], $_SESSION['admin_nome'], $_SESSION['admin_email'], $_SESSION['admin_perfil']);
        $this->redirect(admin_url('login'));
    }
}
