<?php
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/mail.php'; // ✅ Your working mail configuration

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

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

    if (empty($email)) {
        echo json_encode(['status' => 'error', 'message' => 'Email not provided.']);
        exit;
    }

    // ✅ Check if user exists
    $stmt = $pdo->prepare("SELECT fullname, verification_code, is_verified FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        echo json_encode(['status' => 'error', 'message' => 'Account not found.']);
        exit;
    }

    if ($user['is_verified']) {
        echo json_encode(['status' => 'info', 'message' => 'This account is already verified.']);
        exit;
    }

    $fullname = $user['fullname'];
    $verify_code = $user['verification_code'];

    // ✅ Generate verification URL
    $verify_url = "https://intlbmellon.com/verify?code={$verify_code}";

    // ✅ Prepare email
    $subject = "Verify Your Bmellonglobal Account";
    $message = "
        Hello {$fullname},<br><br>
        Please verify your account by clicking the link below:<br>
        <a href='{$verify_url}'>{$verify_url}</a><br><br>
        If you did not request this email, please ignore it.<br><br>
        Regards,<br>
        <b>Bmellonglobal Team</b>
    ";

    // ✅ Send email
    $mail_sent = sendMail($email, $subject, $message);

    if ($mail_sent) {
        echo json_encode([
            'status' => 'success',
            'message' => "Verification email has been resent to <b>{$email}</b>."
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Email sending failed. Please check your mail configuration or internet connection.'
        ]);
    }

} catch (Throwable $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Server error: ' . $e->getMessage()
    ]);
}
