<?php
// Enable error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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_once __DIR__ . '/../unified_config.php';


if (!$conn) {
    echo json_encode(["success" => false, "message" => "Database connection failed"]);
    exit;
}

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

// Get required fields
$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'] ?? ''; // optional

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

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

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

// Generate unique fields
$uid            = uniqid('user_');
$emailToken     = bin2hex(random_bytes(16));
$wallet_address = "WAL" . rand(100000, 999999);

// Default IB chain
$ibChain = array_fill(1, 10, 'noIB');

// If referral provided, set IB chain
if ($referralId) {
    $refQuery = mysqli_query($conn, "SELECT * FROM loginusers WHERE referalId='$referralId'");
    if (mysqli_num_rows($refQuery) > 0) {
        $ref = mysqli_fetch_assoc($refQuery);
        $ibChain[1] = $ref['email'];
        for ($i = 2; $i <= 10; $i++) {
            $prev = 'ib' . ($i - 1);
            $ibChain[$i] = $ref[$prev] ?? 'noIB';
        }
    } else {
        echo json_encode(["success" => false, "message" => "Invalid referral ID"]);
        exit;
    }
}

// Insert into loginusers table
$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", "error" => mysqli_error($conn)]);
    exit;
}

$userId = mysqli_insert_id($conn);
$fullName = $first_name . ' ' . $last_name;

// Insert into IB1 table (optional for tracking)
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())");

// Return response
echo json_encode([
    "success" => true,
    "message" => "User registered successfully by admin.",
    "registered_by" => "admin",
    "uid" => $uid,
    "referralId" => $newReferralId,
    "ibChain" => $ibChain,
    "user" => [
        "id" => $userId,
        "first_name" => $first_name,
        "last_name" => $last_name,
        "full_name" => $fullName,
        "country" => $country,
        "phone" => $phone,
        "dob" => $dob,
        "email" => $email,
        "wallet_address" => $wallet_address,
        "referral" => $referralId ?: 'none',
        "created_at" => date("Y-m-d H:i:s")
    ]
]);
?>
