<?php
/**
 * POST /api/auth/verify_email.php
 * Body (JSON): { token }
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';

only_post_allowed();

$input = get_json_input();
$token = trim($input['token'] ?? '');
if ($token === '') {
    send_error('A verification token is required.', 422);
}

$tokenHash = hash('sha256', $token);
$pdo = Database::connect();

$stmt = $pdo->prepare(
    'SELECT id, user_id FROM email_verifications WHERE token_hash = ? AND expires_at > NOW() LIMIT 1'
);
$stmt->execute([$tokenHash]);
$verification = $stmt->fetch();

if (!$verification) {
    send_error('This verification link is invalid or has expired. Request a new one below.', 400);
}

$pdo->beginTransaction();
try {
    $stmt = $pdo->prepare('UPDATE users SET email_verified_at = NOW() WHERE id = ?');
    $stmt->execute([$verification['user_id']]);

    // Token is single-use - clear any outstanding verification rows for this user.
    $stmt = $pdo->prepare('DELETE FROM email_verifications WHERE user_id = ?');
    $stmt->execute([$verification['user_id']]);

    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    send_error('Could not verify your email. Please try again.', 500);
}

send_json(true, 'Email verified! You can now log in.');
