<?php
require __DIR__ . '/bootstrap.php';

$token = (string)($_GET['token'] ?? '');
$secret = (string)config_value('sso_secret', '');
$parts = explode('.', $token, 2);
if (count($parts) !== 2 || $secret === '') {
    http_response_code(403); exit('Acesso unificado inválido.');
}
$payload = json_decode(base64_decode(strtr($parts[0], '-_', '+/')), true);
$sig = $parts[1];
$expected = hash_hmac('sha256', $parts[0], $secret);
if (!is_array($payload) || !hash_equals($expected, $sig) || (int)($payload['exp'] ?? 0) < time()) {
    http_response_code(403); exit('Link de acesso expirado ou inválido.');
}
$email = strtolower(trim((string)($payload['email'] ?? '')));
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { http_response_code(403); exit('Administrador inválido.'); }

$user = User::findByEmail($email);
if (!$user) {
    $name = trim((string)($payload['name'] ?? 'Administrador LinkExpress')) ?: 'Administrador LinkExpress';
    $password = bin2hex(random_bytes(24));
    $id = User::createAdmin($name, $email, $password);
    $user = User::find($id);
}
if (!$user || ($user['role'] ?? '') !== 'admin') {
    http_response_code(403); exit('A conta não possui permissão de administrador na Autoescola.');
}

session_regenerate_id(true);
$_SESSION['user_id'] = (int)$user['id'];
$_SESSION['role'] = 'admin';
header('Location: ' . url('admin/dashboard'), true, 303);
exit;
