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

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

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

// Validate registration data exists
if (empty($_SESSION['reg_email']) || $_SESSION['reg_email'] !== $email) {
    header('Location: register.php');
    exit;
}

// Validate email
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = 'Invalid email address';
} else {
    $firstname = $_SESSION['reg_firstname'] ?? '';
    $lastname = $_SESSION['reg_lastname'] ?? '';
    
    if (empty($firstname) || empty($lastname)) {
        header('Location: register.php');
        exit;
    }
    
    // Generate new OTP
    $otp = generateOTP();
    
    // Store OTP in database
    $storeResult = storeOTP($conn, $email, $otp);
    
    if ($storeResult['success']) {
        // Send OTP via email
        $userName = trim($firstname . ' ' . $lastname);
        $sendResult = sendOTPEmail($email, $otp, $userName);
        
        if ($sendResult['success']) {
            header('Location: verify-registration-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-registration-otp.php?email=' . urlencode($email) . '&error=' . urlencode($error));
exit;
?>
