<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\View;

class AdminAuthController
{
    // GET /admin/login
    public function login(): void
    {
        if (Auth::estaLogado()) { header('Location: /'); exit; }
        if (!Auth::temSenhaCadastrada()) { header('Location: /admin/setup'); exit; }

        $redirect = $_GET['redirect'] ?? '/';
        View::render('admin/login', [
            'titulo'   => 'Acesso Restrito — Premium Express Gestão',
            'redirect' => $redirect,
            'erro'     => '',
            'ano'      => date('Y'),
        ], '');
    }

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

        if (!Auth::temSenhaCadastrada()) {
            header('Location: /admin/setup');
            exit;
        }

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

        View::render('admin/login', [
            'titulo'   => 'Acesso Restrito — Premium Express Gestão',
            'redirect' => $redirect,
            'erro'     => 'Senha incorreta. Tente novamente.',
            'ano'      => date('Y'),
        ], '');
    }

    // GET /admin/setup — define senha pela primeira vez
    public function setup(): void
    {
        // Só acessível se ainda não há senha cadastrada
        if (Auth::temSenhaCadastrada()) {
            header('Location: /admin/login');
            exit;
        }

        View::render('admin/setup', [
            'titulo' => 'Definir Senha de Administrador — Premium Express Gestão',
            'erro'   => '',
            'ano'    => date('Y'),
        ], '');
    }

    // POST /admin/setup/salvar
    public function salvarSetup(): void
    {
        if (Auth::temSenhaCadastrada()) {
            header('Location: /admin/login');
            exit;
        }

        $senha   = $_POST['senha']   ?? '';
        $confirm = $_POST['confirma'] ?? '';
        $redirect = $_POST['redirect'] ?? '/configurar';
        if (!str_starts_with($redirect, '/')) $redirect = '/configurar';

        $erro = '';
        if (strlen($senha) < 4) {
            $erro = 'A senha deve ter pelo menos 4 caracteres.';
        } elseif ($senha !== $confirm) {
            $erro = 'As senhas não coincidem.';
        }

        if ($erro) {
            View::render('admin/setup', [
                'titulo' => 'Definir Senha de Administrador — Premium Express Gestão',
                'erro'   => $erro,
                'ano'    => date('Y'),
            ], '');
            return;
        }

        try {
            Auth::salvarSenha($senha); // já faz login automático
            header('Location: ' . $redirect);
            exit;
        } catch (\Throwable $e) {
            View::render('admin/setup', [
                'titulo' => 'Definir Senha de Administrador — Premium Express Gestão',
                'erro'   => $e->getMessage(),
                'ano'    => date('Y'),
            ], '');
        }
    }

    // GET /admin/senha — alterar senha (exige login)
    public function senha(): void
    {
        if (!Auth::estaLogado()) {
            header('Location: /admin/login?redirect=/admin/senha');
            exit;
        }

        View::render('admin/senha', [
            'titulo' => 'Alterar Senha — Premium Express Gestão',
            'erro'   => '',
            'ok'     => '',
        ]);
    }

    // POST /admin/senha/alterar
    public function alterarSenha(): void
    {
        if (!Auth::estaLogado()) {
            header('Location: /admin/login');
            exit;
        }

        $senhaAtual = $_POST['senha_atual']  ?? '';
        $novaSenha  = $_POST['nova_senha']   ?? '';
        $confirma   = $_POST['confirma']     ?? '';

        $erro = '';

        // Valida senha atual
        $hash = Auth::hashSalvo();
        if (!$hash || !password_verify($senhaAtual, $hash)) {
            $erro = 'Senha atual incorreta.';
        } elseif (strlen($novaSenha) < 4) {
            $erro = 'A nova senha deve ter pelo menos 4 caracteres.';
        } elseif ($novaSenha !== $confirma) {
            $erro = 'A confirmação não confere com a nova senha.';
        }

        if ($erro) {
            View::render('admin/senha', [
                'titulo' => 'Alterar Senha — Premium Express Gestão',
                'erro'   => $erro,
                'ok'     => '',
            ]);
            return;
        }

        try {
            Auth::salvarSenha($novaSenha);
            View::render('admin/senha', [
                'titulo' => 'Alterar Senha — Premium Express Gestão',
                'erro'   => '',
                'ok'     => 'Senha alterada com sucesso!',
            ]);
        } catch (\Throwable $e) {
            View::render('admin/senha', [
                'titulo' => 'Alterar Senha — Premium Express Gestão',
                'erro'   => $e->getMessage(),
                'ok'     => '',
            ]);
        }
    }

    // GET /admin/reauth — pede senha antes de entrar nas Configurações
    public function reauth(): void
    {
        if (!Auth::estaLogado()) {
            header('Location: /admin/login?redirect=/configurar');
            exit;
        }

        $redirect = $_GET['redirect'] ?? '/configurar';
        if (!str_starts_with($redirect, '/')) $redirect = '/configurar';

        View::render('admin/reauth', [
            'titulo'   => 'Confirmar Acesso — Premium Express Gestão',
            'redirect' => $redirect,
            'erro'     => '',
        ], '');
    }

    // POST /admin/reauth/confirmar
    public function confirmarReauth(): void
    {
        if (!Auth::estaLogado()) {
            header('Location: /admin/login?redirect=/configurar');
            exit;
        }

        $senha    = $_POST['senha']    ?? '';
        $redirect = $_POST['redirect'] ?? '/configurar';
        if (!str_starts_with($redirect, '/')) $redirect = '/configurar';

        $hash = Auth::hashSalvo();
        if ($hash && password_verify($senha, $hash)) {
            Auth::marcarReauth();
            header('Location: ' . $redirect);
            exit;
        }

        View::render('admin/reauth', [
            'titulo'   => 'Confirmar Acesso — Premium Express Gestão',
            'redirect' => $redirect,
            'erro'     => 'Senha incorreta. Tente novamente.',
        ], '');
    }

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