<?php
// Enable error reporting for debugging
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;
}

// Check if MySQLi extension is available
if (!function_exists('mysqli_connect')) {
    echo json_encode([
        "success" => false, 
        "message" => "MySQLi extension is not available on this server. Please contact system administrator.",
        "error_details" => "MySQLi extension is required for database operations."
    ]);
    exit;
}

include('unified_config.php'); // Unified configuration with mail system

// Check if database connection is successful
if (!isset($conn) || !$conn) {
    echo json_encode([
        "success" => false, 
        "message" => "Database connection failed. Please contact system administrator.",
        "error_details" => "Unable to establish database connection."
    ]);
    exit;
}

// 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'] ?? '';

// ------------------
// Referral ID logic
// ------------------
// Priority: URL referral > POST referral
if (isset($_GET['referral']) && !empty($_GET['referral'])) {
    $referralId = $_GET['referral'];
} else {
    $referralId = $data['referral'] ?? '';
}

// ------------------
// Validate required fields
// ------------------
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 (!$checkEmail) {
    echo json_encode([
        "success" => false, 
        "message" => "Database query failed",
        "error_details" => mysqli_error($conn)
    ]);
    exit;
}

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'");
    if (!$checkStmt) {
        echo json_encode([
            "success" => false, 
            "message" => "Database query failed",
            "error_details" => mysqli_error($conn)
        ]);
        exit;
    }
} 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'

// ------------------
// Set referral chain if referral ID exists
// ------------------
if ($referralId) {
    $referrerQuery = mysqli_query($conn, "SELECT * FROM loginusers WHERE referalId='$referralId'");
    if (!$referrerQuery) {
        echo json_encode([
            "success" => false, 
            "message" => "Database query failed",
            "error_details" => mysqli_error($conn)
        ]);
        exit;
    }
    
    if (mysqli_num_rows($referrerQuery) > 0) {
        $ref = mysqli_fetch_assoc($referrerQuery);
        $ibChain[1] = $ref['email'];   // direct referrer
        $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", 
        "error_details" => mysqli_error($conn)
    ]);
    exit;
}

// ✅ Get auto-generated user ID AFTER INSERT
$userId = mysqli_insert_id($conn);

// ------------------
// 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())");

if (!$insertIB1) {
    echo json_encode([
        "success" => false, 
        "message" => "Failed to create IB record", 
        "error_details" => mysqli_error($conn)
    ]);
    // Note: We don't exit here because the main registration was successful
}

// ------------------
// Send registration verification email
// ------------------
$emailSent = false;
if (EMAIL_AUTOMATION_ENABLED) {
    try {
        $mailSystem = getMailSystem();
        $emailResult = $mailSystem->sendRegisterVerification($email, $fullName, $emailToken);
        $emailSent = $emailResult['success'];
        
        // Log email result
        if (!$emailResult['success']) {
            error_log("Failed to send registration email to $email: " . $emailResult['message']);
        }
    } catch (Exception $e) {
        error_log("Exception while sending registration email to $email: " . $e->getMessage());
    }
}

// ------------------
// Send referral notification email if applicable
// ------------------
$referralEmailSent = false;
if ($referralId && isset($ref) && EMAIL_AUTOMATION_ENABLED) {
    try {
        $mailSystem = getMailSystem();
        $referrerEmailResult = $mailSystem->sendReferralRegistration(
            $ref['email'], 
            $ref['first_name'] . ' ' . $ref['last_name'], 
            $fullName, 
            IB_COMMISSION_RATE
        );
        $referralEmailSent = $referrerEmailResult['success'];
        
        // Log referral email result
        if (!$referrerEmailResult['success']) {
            error_log("Failed to send referral notification to {$ref['email']}: " . $referrerEmailResult['message']);
        }
    } catch (Exception $e) {
        error_log("Exception while sending referral notification to {$ref['email']}: " . $e->getMessage());
    }
}

// ------------------
// Return success response with more details
// ------------------
echo json_encode([
    "success" => true,
    "message" => "User registered successfully. Please check your email for verification.",
    "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,
        "emailToken" => $emailToken,
        "registration_date" => date("Y-m-d H:i:s")
    ],
    "email_sent" => $emailSent,
    "referral_email_sent" => $referralEmailSent
]);
?>