<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

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

$first_name = $data['first_name'] ?? '';
$last_name = $data['last_name'] ?? '';
$country = $data['country'] ?? '';
$phone = $data['phone'] ?? '';
$dob = $data['dob'] ?? '';
$email = $data['email'] ?? '';
$password = $data['password'] ?? '';
$referralId = $data['referral'] ?? ''; // referral ID of the referrer

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

// Check if email exists
$checkEmail = mysqli_query($conn, "SELECT * FROM loginusers WHERE email='$email'");
if (mysqli_num_rows($checkEmail) > 0) {
    echo json_encode(["success" => false, "message" => "Email already exists"]);
    exit;
}

// Generate unique 5-digit referral ID for this user
do {
    $newReferralId = mt_rand(10000, 99999);
    $checkStmt = mysqli_query($conn, "SELECT id FROM loginusers WHERE referalId='$newReferralId'");
} while (mysqli_num_rows($checkStmt) > 0);

// Generate UID and email token
$uid = uniqid('user_');
$emailToken = bin2hex(random_bytes(16));
$wallet_address = "WAL" . rand(100000, 999999);

// Initialize IB chain
$ibChain = array_fill(1, 10, 'noIB'); // ib1 → ib10 default 'noIB'

if ($referralId) {
    // Fetch referrer using referral ID
    $referrerQuery = mysqli_query($conn, "SELECT * FROM loginusers WHERE referalId='$referralId'");
    if (mysqli_num_rows($referrerQuery) > 0) {
        $ref = mysqli_fetch_assoc($referrerQuery);
        // Set IB chain for new user
        $ibChain[1] = $ref['email'];   // ib1 = direct referrer email
        $ibChain[2] = $ref['ib1'] ?? 'noIB';
        $ibChain[3] = $ref['ib2'] ?? 'noIB';
        $ibChain[4] = $ref['ib3'] ?? 'noIB';
        $ibChain[5] = $ref['ib4'] ?? 'noIB';
        $ibChain[6] = $ref['ib5'] ?? 'noIB';
        $ibChain[7] = $ref['ib6'] ?? 'noIB';
        $ibChain[8] = $ref['ib7'] ?? 'noIB';
        $ibChain[9] = $ref['ib8'] ?? 'noIB';
        $ibChain[10] = $ref['ib9'] ?? 'noIB';
    } else {
        echo json_encode(["success" => false, "message" => "Invalid referral ID"]);
        exit;
    }
}

// Insert user into loginusers
$insertUser = mysqli_query($conn, "INSERT INTO loginusers 
    (first_name, last_name, country, phone, dob, email, password, uid, emailToken, wallet_address, referalId,
     ib1, ib2, ib3, ib4, ib5, ib6, ib7, ib8, ib9, ib10)
    VALUES
    ('$first_name', '$last_name', '$country', '$phone', '$dob', '$email', '$password', '$uid', '$emailToken', '$wallet_address', '$newReferralId',
     '{$ibChain[1]}', '{$ibChain[2]}', '{$ibChain[3]}', '{$ibChain[4]}', '{$ibChain[5]}', '{$ibChain[6]}', '{$ibChain[7]}', '{$ibChain[8]}', '{$ibChain[9]}', '{$ibChain[10]}')");

if (!$insertUser) {
    echo json_encode(["success" => false, "message" => "User registration failed"]);
    exit;
}

// Insert into ib1 table
$fullName = $first_name . ' ' . $last_name;
$insertIB1 = mysqli_query($conn, "INSERT INTO ib1 
    (uid, name, email, number, username, date, country, password, reg_date) VALUES 
    ('$uid', '$fullName', '$email', '$phone', '{$first_name}{$last_name}', NOW(), '$country', '$password', NOW())");

echo json_encode([
    "success" => true,
    "message" => "User registered successfully",
    "uid" => $uid,
    "referralId" => $newReferralId,
    "ibChain" => $ibChain
]);
?>
