<?php
include 'config.php';

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    session_start(); // 🟢 শুরুতেই session_start()

    $email = $_POST["email"];
    $otp = rand(1000, 9999); // 4-digit OTP
    $session_id = uniqid("session_", true); // Custom Session ID (not PHP's)

    $subject = "Your OTP Code - Khelo buzz";

    $message = '
    <html>
    <head><meta charset="UTF-8"></head>
    <body>
        <div style="font-family:sans-serif;background:#f5f5f5;padding:30px">
            <div style="max-width:500px;margin:auto;background:#fff;padding:20px;border-radius:8px;box-shadow:0 0 10px rgba(0,0,0,0.1)">
                <h2 style="text-align:center;color:#333">OTP Verification</h2>
                <p style="font-size:16px;color:#555">
                    Your one-time password (OTP) is:
                </p>
                <div style="font-size:28px;font-weight:bold;color:#007BFF;text-align:center;padding:10px 0">
                    ' . $otp . '
                </div>
                <p style="font-size:14px;color:#777;text-align:center">
                    Do not share this OTP with anyone.
                </p>
                <hr style="margin:20px 0">
                <p style="font-size:12px;color:#999;text-align:center">
                    If you did not request this OTP, you can safely ignore this message.<br>
                    - Khelo buzz Team
                </p>
            </div>
        </div>
    </body>
    </html>';

    $from_email = "norereplay@khelobuzz.live";

    $headers  = "From:  Khelo buzz<" . $from_email . ">\r\n";
    $headers .= "Reply-To: " . $from_email . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=UTF-8\r\n";

    // 🔐 Session variables সেভ করো
    $_SESSION['otp'] = $otp;
    $_SESSION['email'] = $email;
    $_SESSION['session_id'] = $session_id;

    if (mail($email, $subject, $message, $headers)) {
        echo json_encode([
            "status" => "success",
            "session_id" => $session_id,
            "php_session_id" => session_id() // 🟢 PHP এর আসল session_id ক্লায়েন্টকে পাঠাও
        ]);
    } else {
        echo json_encode([
            "status" => "fail",
            "message" => "email_error"
        ]);
    }
}
?>