<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

$method = strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET'));
if (!in_array($method, ['GET', 'POST'], true)) {
    golder_json_error(405, 'METHOD_NOT_ALLOWED', 'Method not allowed.');
}

$master = golder_master_pdo();
golder_sales_rate_limit($master, 'portal_verify_email', 30, 300);

$token = '';
if ($method === 'POST') {
    $input = golder_portal_api_payload();
    $token = trim((string)($input['token'] ?? ''));
} else {
    $token = trim((string)($_GET['token'] ?? ''));
}

$res = golder_portal_verify_email($master, $token);
if (empty($res['ok'])) {
    golder_json_error(400, 'INVALID_REQUEST', (string)($res['message'] ?? 'Verification failed.'));
}

$user = is_array($res['user'] ?? null) ? $res['user'] : null;
if ($user) {
    golder_portal_login_user($user);
}

golder_json_response([
    'status' => 'ok',
    'message' => 'Email verified.',
    'user' => $user,
]);


