<?php
require_once '../includes/config.php';
require_once 'helpers.php'; // jsAlert()
require_once 'smtp_mail.php';

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

if ($email === '') {
    jsAlert(
        'Invalid Request',
        'Email address is missing.',
        'error',
        '../sign-up.php'
    );
}

// Check user
$stmt = $conn->prepare("
    SELECT id, name, email_verified
    FROM users
    WHERE email = ?
");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

if (!$user) {
    jsAlert(
        'User Not Found',
        'No account is associated with this email address.',
        'error',
        '../sign-up.php'
    );
}

// Already verified
if ((int)$user['email_verified'] === 1) {
    jsAlert(
        'Already Verified',
        'This email address has already been verified. You can proceed to login.',
        'info',
        '../login.php'
    );
}

// Generate new OTP
$newOtp  = random_int(100000, 999999);
$expiry  = date("Y-m-d H:i:s", strtotime("+10 minutes"));

// Reset OTP and attempts
$stmt = $conn->prepare("
    UPDATE users
    SET email_otp = ?, 
        otp_expires = ?, 
        otp_attempts = 0
    WHERE email = ?
");
$stmt->bind_param("sss", $newOtp, $expiry, $email);
$stmt->execute();

// Send email
if (!sendOTPEmail($email, $user['name'], $newOtp)) {
    jsAlert(
        'Email Error',
        'Unable to send OTP at the moment. Please try again later.',
        'error'
    );
}

// Success
jsAlert(
    'OTP Sent',
    'A new verification code has been sent to your email address.',
    'success',
    "verify-email.php?email=" . urlencode($email)
);
