<?php
session_start(); // start session
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Headers: Content-Type");

include('config.php'); // DB connection

// ------------------
// Check if user is logged in
// ------------------
if (!isset($_SESSION['clogin']) || empty($_SESSION['clogin'])) {
    echo json_encode([
        "success" => false,
        "message" => "User not logged in"
    ]);
    exit;
}

// Assume $_SESSION['clogin'] stores the email of logged-in user
$loggedInEmail = $_SESSION['clogin'];

// Fetch the user's referral ID from DB
$query = mysqli_query($conn, "SELECT referalId FROM loginusers WHERE email='$loggedInEmail'");
if (mysqli_num_rows($query) == 0) {
    echo json_encode([
        "success" => false,
        "message" => "User not found"
    ]);
    exit;
}

$user = mysqli_fetch_assoc($query);
$referalId = $user['referalId'];

// Build referral link
$baseUrl = "http://localhost/Zforex/Zforex_Backend/register.php";
$referralLink = $baseUrl . "?referral=" . $referalId;

// Return JSON response 
echo json_encode([
    "success" => true,
    "message" => "Referral link generated successfully",
    "referralLink" => $referralLink
]);
?>
