<?php
/**
 * Process OTP Verification
 */
require_once 'config.php';
require_once 'auth-helpers.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: forgot-password.php');
    exit;
}

$email = trim($_POST['email'] ?? '');
$otp = trim($_POST['otp'] ?? '');
$error = '';

// Validate inputs
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'Invalid email address';
} elseif (empty($otp) || strlen($otp) !== 6 || !ctype_digit($otp)) {
    $error = 'Please enter a valid 6-digit OTP';
} else {
    // Verify OTP
    $verifyResult = verifyOTP($conn, $email, $otp);
    
    if ($verifyResult['success']) {
        // Store verification info in session
        $_SESSION['otp_verified'] = true;
        $_SESSION['verified_email'] = $email;
        $_SESSION['otp_id'] = $verifyResult['otp_id'];
        
        // Redirect to reset password page
        header('Location: reset-password.php?email=' . urlencode($email));
        exit;
    } else {
        $error = $verifyResult['message'];
    }
}

// Redirect back with error
header('Location: verify-otp.php?email=' . urlencode($email) . '&error=' . urlencode($error));
exit;
?>
