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

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

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

// Validate email
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'Invalid email address';
} else {
    // Check if user exists
    $user = getUserByEmail($conn, $email);
    
    if (!$user) {
        // For security, don't reveal if email exists or not
        header('Location: verify-otp.php?email=' . urlencode($email) . '&info=' . urlencode('If an account exists with this email, a new code has been sent'));
        exit;
    } else {
        // Generate new OTP
        $otp = generateOTP();
        
        // Store OTP in database
        $storeResult = storeOTP($conn, $email, $otp);
        
        if ($storeResult['success']) {
            // Send OTP via email
            $userName = trim($user['firstname'] . ' ' . $user['lastname']);
            $sendResult = sendOTPEmail($email, $otp, $userName);
            
            if ($sendResult['success']) {
                header('Location: verify-otp.php?email=' . urlencode($email) . '&info=' . urlencode('New OTP has been sent to your email'));
                exit;
            } else {
                $error = 'Unable to send OTP. Please try again later.';
            }
        } else {
            $error = 'An error occurred. Please try again later.';
        }
    }
}

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