<?php
// verify-otp.php — Verifies a 6-digit OTP for Dabil
//
// Expects POST: email (required), otp_code (required),
// purpose (optional: 'signup' | 'login' | 'password_reset', default 'signup')
//
// Returns JSON: { success: bool, message: string }

header('Content-Type: application/json');

// Needed so a successful 'signup' verification can be carried into
// profile-setup.php / complete-profile.php via $_SESSION['signup_email'].
session_start();

require_once 'config/db.php';

const OTP_MAX_ATTEMPTS = 5;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
    exit;
}

$email   = trim($_POST['email'] ?? '');
$otpCode = trim($_POST['otp_code'] ?? '');
$purpose = trim($_POST['purpose'] ?? 'signup');

$allowedPurposes = ['signup', 'login', 'password_reset'];
if (!in_array($purpose, $allowedPurposes, true)) {
    $purpose = 'signup';
}

if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(422);
    echo json_encode(['success' => false, 'message' => 'A valid email address is required.']);
    exit;
}

if (!preg_match('/^\d{6}$/', $otpCode)) {
    http_response_code(422);
    echo json_encode(['success' => false, 'message' => 'Enter the 6-digit code sent to your email.']);
    exit;
}

try {
    // Fetch the most recent, unused code for this email/purpose.
    $stmt = $pdo->prepare(
        'SELECT id, otp_code, attempts, expires_at, is_used
         FROM otp_codes
         WHERE email = :email AND purpose = :purpose
         ORDER BY created_at DESC LIMIT 1'
    );
    $stmt->execute(['email' => $email, 'purpose' => $purpose]);
    $row = $stmt->fetch();

    if (!$row) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'No verification code found for this email. Please request a new one.']);
        exit;
    }

    if ((int) $row['is_used'] === 1) {
        http_response_code(410);
        echo json_encode(['success' => false, 'message' => 'This code has already been used. Please request a new one.']);
        exit;
    }

    if (strtotime($row['expires_at']) < time()) {
        http_response_code(410);
        echo json_encode(['success' => false, 'message' => 'This code has expired. Please request a new one.']);
        exit;
    }

    if ((int) $row['attempts'] >= OTP_MAX_ATTEMPTS) {
        http_response_code(429);
        echo json_encode(['success' => false, 'message' => 'Too many incorrect attempts. Please request a new code.']);
        exit;
    }

    if (!hash_equals($row['otp_code'], $otpCode)) {
        $stmt = $pdo->prepare('UPDATE otp_codes SET attempts = attempts + 1 WHERE id = :id');
        $stmt->execute(['id' => $row['id']]);

        $remaining = OTP_MAX_ATTEMPTS - ((int) $row['attempts'] + 1);
        http_response_code(401);
        echo json_encode([
            'success' => false,
            'message' => 'Incorrect code. ' . max($remaining, 0) . ' attempt(s) remaining.',
        ]);
        exit;
    }

    // Success — mark the code as used so it can't be replayed.
    $stmt = $pdo->prepare('UPDATE otp_codes SET is_used = 1 WHERE id = :id');
    $stmt->execute(['id' => $row['id']]);

    // Carry the verified email into the next step depending on purpose.
    if ($purpose === 'signup') {
        $_SESSION['signup_email']           = $email;
        $_SESSION['signup_email_verified']  = true;
    } elseif ($purpose === 'password_reset') {
        $_SESSION['reset_email']            = $email;
        $_SESSION['reset_email_verified']   = true;
    }

    echo json_encode([
        'success' => true,
        'message' => 'Email verified successfully.',
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Something went wrong. Please try again.']);
}
