<?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';

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

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

$otp = rand(10000, 99999);
$subject = "Your OTP Code";
$message = "<p>Your verification code is <strong>$otp</strong>.</p>";

$mailer = new Mailer();
$response = $mailer->send($data['to'], $subject, $message);

if ($response['status'] === 'success') {
    echo json_encode(['status' => 'success', 'otp' => $otp]);
} else {
    echo json_encode($response);
}
