<?php
session_start();

// Load existing user data
$usersFile = "../data/users.json";
$users = file_exists($usersFile) ? json_decode(file_get_contents($usersFile), true) : ["users" => []];

// Generate unique user ID
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = "usr" . rand(10000, 99999);
}
$userID = $_SESSION['user_id'];

// Get submitted data
$data = json_decode(file_get_contents("php://input"), true);
$step = $data['step'];
$referralID = $data['referralID'];

// Store referral ID under user
if (!isset($users['users'][$userID])) {
    $users['users'][$userID] = ["referral_ids" => []];
}
$users['users'][$userID]['referral_ids'][$step] = $referralID;

// Save back to JSON file
file_put_contents($usersFile, json_encode($users, JSON_PRETTY_PRINT));

echo json_encode(["success" => true, "user_id" => $userID]);
