<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header("Access-Control-Allow-Methods: POST");
header("Allow: POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Origin");

require_once 'Mailer.php';
require_once '../database.php'; // Adjust if needed

$data = json_decode(file_get_contents("php://input"), true);

if (!isset($data['email'])) {
    echo json_encode(['status' => 'error', 'message' => 'Missing email']);
    exit;
}

$email = trim($data['email']);
$otp = rand(1000, 9999); // Max is 9999, fits in SMALLINT
$subject = "Your OTP Code";
$message = "<p>Your verification code is <strong>$otp</strong>.</p>";

$mailer = new Mailer();
$response = $mailer->send($email, $subject, $message);

if ($response['status'] === 'success') {
    // Always send OTP first, then check if email exists
    $checkStmt = $conn->prepare("SELECT * FROM subscribers WHERE sEmail = :email");
    $checkStmt->execute(['email' => $email]);

    if ($checkStmt->rowCount() > 0) {
        // Email exists - Update the vercode
        $updateStmt = $conn->prepare("UPDATE subscribers SET sVerCode = :code WHERE sEmail = :email");
        $updateStmt->execute([
            'code' => $otp,
            'email' => $email
        ]);
        
        echo json_encode([
            'status' => 'success',
            'message' => 'OTP sent successfully',
            'id' => $email,
            'vercode' => $otp,
            'type' => 'existing'
        ]);
    } else {
        // Email doesn't exist - Still return success since OTP was sent
        echo json_encode([
            'status' => 'success',
            'message' => 'OTP sent successfully',
            'id' => $email,
            'vercode' => $otp,
            'type' => 'new'
        ]);
    }
} else {
    // If mail sending failed
    echo json_encode($response);
}
?>