<?php
// 🔹 Init function to enable error reporting
function init() {
    ini_set('display_errors', 1);   // Show errors in output
    ini_set('display_startup_errors', 1); 
    error_reporting(E_ALL);        // Report all types of errors
}
init();

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

require "config.php";

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

if (!$data || empty($data['email'])) {
    echo json_encode(["success" => false, "message" => "Email is required"]);
    exit;
}

$email = $data['email'];

// ✅ Use try/catch to catch DB errors
try {
    $stmt = $conn->prepare("SELECT referalId FROM loginusers WHERE email = ?");
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $conn->error);
    }

    $stmt->bind_param("s", $email);
    $stmt->execute();
    $stmt->bind_result($referralCode);
    $stmt->fetch();

    if ($referralCode) {
        echo json_encode(["success" => true, "email" => $email, "referralCode" => $referralCode]);
    } else {
        echo json_encode(["success" => false, "message" => "User not found or referral code not set"]);
    }

    $stmt->close();
    $conn->close();
} catch (Exception $e) {
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
?>
