<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');

// Get POST data
$data = json_decode(file_get_contents('php://input'), true);
$email = $data['email'] ?? '';

if (empty($email)) {
    echo json_encode(['success' => false, 'error' => 'No email provided']);
    exit;
}

// Generate OTP
$otp = sprintf("%06d", mt_rand(100000, 999999));

// Email Configuration
$subject = "Your Secure OTP Code - Dream.ZONE";
$from = "dream.zone@pcrr-jwt.eu";

// Highly Optimized Headers to fight Spam filters
$headers  = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8\r\n";
$headers .= "From: Dream.ZONE Security <" . $from . ">\r\n";
$headers .= "Reply-To: " . $from . "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();

// HTML Body (Looks professional, less likely to be flagged as spam)
$body = "
    <div style='font-family: Arial, sans-serif; padding: 25px; border: 1px solid #10b981; border-radius: 8px; max-width: 500px; background-color: #0f172a; color: #f8fafc;'>
        <h2 style='color: #10b981; margin-top: 0;'>Dream.ZONE Login Verification</h2>
        <p style='color: #cbd5e1;'>Hello,</p>
        <p style='color: #cbd5e1;'>Your secure OTP code to access the portal is:</p>
        <div style='background: #1e293b; padding: 15px; border-radius: 6px; text-align: center; margin: 20px 0;'>
            <span style='color: #10b981; font-size: 32px; letter-spacing: 8px; font-weight: bold;'>{$otp}</span>
        </div>
        <p style='font-size: 11px; color: #64748b;'>If you did not request this code, please ignore this email. This is an automated security message.</p>
    </div>
";

// SEND AND CHECK RESULT
// The "-f" parameter tells Hostinger to set the correct Return-Path. This is critical for avoiding spam!
$mailResult = mail($email, $subject, $body, $headers, "-f$from");

if ($mailResult) {
    echo json_encode([
        'success' => true,
        'otp' => $otp
    ]);
} else {
    echo json_encode([
        'success' => false, 
        'error' => 'Hostinger blocked the mail function.'
    ]);
}
?>