<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';

apply_cors();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    send_error('Method not allowed.', 405);
}

$input = get_json_input();
require_fields($input, ['email', 'otp']);

$email = strtolower(clean_str($input['email']));
$otp = clean_str($input['otp']);

// Dev-mode bypass (see config/constants.php) - lets the fixed test code
// through. This still writes a used email_otps row (rather than just
// returning success), because register.php independently re-checks the
// database for a verified OTP - a bypass that skipped the DB write would
// pass verify_otp.php but then fail at the register step regardless.
if (DEV_MODE_OTP_ENABLED && $otp === DEV_MODE_OTP_CODE) {
    $pdo = getDbConnection();
    $stmt = $pdo->prepare(
        'INSERT INTO email_otps (email, otp, expires_at, is_used) VALUES (:email, :otp, :expires_at, 1)'
    );
    $stmt->execute([':email' => $email, ':otp' => DEV_MODE_OTP_CODE, ':expires_at' => date('Y-m-d H:i:s', time() + 600)]);
    send_success(null, 'Email verified (dev mode).');
}

$pdo = getDbConnection();

$stmt = $pdo->prepare(
    'SELECT id, attempts FROM email_otps
     WHERE email = :email AND is_used = 0 AND expires_at > NOW()
     ORDER BY id DESC LIMIT 1'
);
$stmt->execute([':email' => $email]);
$row = $stmt->fetch();

if (!$row) {
    send_error('OTP expired or not found. Please request a new one.', 410);
}

if ((int) $row['attempts'] >= 5) {
    send_error('Too many incorrect attempts. Please request a new OTP.', 429);
}

$check = $pdo->prepare('SELECT id FROM email_otps WHERE id = :id AND otp = :otp');
$check->execute([':id' => $row['id'], ':otp' => $otp]);

if (!$check->fetch()) {
    $inc = $pdo->prepare('UPDATE email_otps SET attempts = attempts + 1 WHERE id = :id');
    $inc->execute([':id' => $row['id']]);
    send_error('Incorrect OTP.', 401);
}

$mark = $pdo->prepare('UPDATE email_otps SET is_used = 1 WHERE id = :id');
$mark->execute([':id' => $row['id']]);

send_success(null, 'Email verified.');
