<?php

namespace App\Controllers;

use App\Core\FbAuth;
use App\Core\View;

class LoginController
{
    // GET /login
    public function index(): void
    {
        if (FbAuth::estaLogado()) {
            header('Location: /');
            exit;
        }

        $config   = $this->config();
        $redirect = $_GET['redirect'] ?? '/';

        View::render('login/index', [
            'titulo'   => 'Acesso — ' . ($config['empresa'] ?? 'Premium Express Gestão'),
            'empresa'  => $config['empresa'] ?? 'Premium Express Gestão',
            'tema'     => $config['tema']    ?? 'azul',
            'redirect' => $redirect,
            'erro'     => '',
        ], '');
    }

    // POST /autenticar
    public function autenticar(): void
    {
        $usuario  = strtoupper(trim($_POST['usuario']  ?? ''));
        $senha    = $_POST['senha']    ?? '';
        $redirect = $_POST['redirect'] ?? '/';
        if (!str_starts_with($redirect, '/')) $redirect = '/';

        if ($usuario === '' || $senha === '') {
            $this->renderLogin($redirect, 'Preencha usuario e senha.');
            return;
        }

        if (FbAuth::login($usuario, $senha)) {
            header('Location: ' . $redirect);
            exit;
        }

        // Se a falha foi de CONEXÃO/driver (comum em instalação nova), mostra a causa real
        // em vez do genérico "usuário/senha inválidos".
        $erroConn = FbAuth::erroConexao();
        $this->renderLogin($redirect, $erroConn ?: 'Usuario ou senha invalidos. Verifique e tente novamente.');
    }

    // GET /logout
    public function logout(): void
    {
        FbAuth::logout();
        header('Location: /login');
        exit;
    }

    // GET /sem-permissao
    public function semPermissao(): void
    {
        $config = $this->config();
        View::render('login/sem-permissao', [
            'titulo'  => 'Acesso Negado — Premium Express Gestão',
            'usuario' => FbAuth::usuario(),
            'empresa' => $config['empresa'] ?? 'Premium Express Gestão',
        ]);
    }

    private function renderLogin(string $redirect, string $erro): void
    {
        $config = $this->config();
        View::render('login/index', [
            'titulo'   => 'Acesso — ' . ($config['empresa'] ?? 'Premium Express Gestão'),
            'empresa'  => $config['empresa'] ?? 'Premium Express Gestão',
            'tema'     => $config['tema']    ?? 'azul',
            'redirect' => $redirect,
            'erro'     => $erro,
        ], '');
    }

    private function config(): array
    {
        $path = dirname(__DIR__, 2) . '/config/database.php';
        return file_exists($path) ? (require $path) : [];
    }
}
