<?php
session_start();
include 'config.php';
include 'functions_mlm.php'; 

// Header untuk output HTML
echo '<!DOCTYPE html><html lang="id"><head><script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script></head><body style="background:#0f172a;">';

// Ambil Data dari Form
$full_name = $conn->real_escape_string($_POST['full_name']);
$email = $conn->real_escape_string($_POST['email']);
$phone = $conn->real_escape_string($_POST['phone']);
$username = $conn->real_escape_string($_POST['username']);
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);

$ref_code_input = $_POST['referral_code']; 
$placement_id = $_POST['placement_id']; 
$position = $_POST['position']; 

// 0. VALIDASI DUPLIKASI (Email & Phone)
$checkDup = $conn->query("SELECT id FROM users WHERE email = '$email' OR phone = '$phone' OR username = '$username'");
if ($checkDup->num_rows > 0) {
    echo "<script>
        Swal.fire({
            icon: 'error',
            title: 'Gagal Mendaftar',
            text: 'Username, Email, atau Nomor HP sudah terdaftar. Gunakan data lain.',
            confirmButtonColor: '#10b981'
        }).then(() => {
            window.history.back();
        });
    </script></body></html>";
    exit();
}

// Generate Kode Referral Unik
$my_new_ref_code = strtoupper(substr($username, 0, 3)) . rand(1000,9999);

// 1. CARI DATA SPONSOR
$qSpon = $conn->query("SELECT id FROM users WHERE referral_code = '$ref_code_input'");
$sponsor = $qSpon->fetch_assoc();

if (!$sponsor) {
    echo "<script>Swal.fire({icon: 'error', title: 'Error', text: 'Kode Referral Salah!'}).then(() => { window.history.back(); });</script></body></html>";
    exit();
}
$sponsor_id = $sponsor['id'];

// 2. TENTUKAN POSISI (AUTO PLACEMENT jika kosong)
if (empty($placement_id) || empty($position)) {
    $slot = findFirstAvailableSlot($sponsor_id, $conn);
    $binary_parent_id = $slot['parent_id'];
    $position = $slot['position'];
} else {
    $binary_parent_id = $placement_id;
    // Cek slot kosong
    $cek = $conn->query("SELECT id FROM users WHERE binary_parent_id = $binary_parent_id AND position = '$position'");
    if($cek->num_rows > 0) {
        echo "<script>Swal.fire({icon: 'error', title: 'Oops...', text: 'Posisi ini baru saja diisi orang lain!'}).then(() => { window.location='network.php'; });</script></body></html>";
        exit();
    }
}

// 3. TENTUKAN LEVEL
$qPar = $conn->query("SELECT depth_level FROM users WHERE id = $binary_parent_id");
$parentData = $qPar->fetch_assoc();
$new_depth = $parentData['depth_level'] + 1;

// 4. INSERT USER & TRIGGER BONUS
$conn->begin_transaction();
try {
    $sql = "INSERT INTO users (full_name, email, phone, username, password, referral_code, upline_id, binary_parent_id, position, depth_level, role, balance_idr) 
            VALUES ('$full_name', '$email', '$phone', '$username', '$password', '$my_new_ref_code', $sponsor_id, $binary_parent_id, '$position', $new_depth, 'starter', 0)";
    
    if ($conn->query($sql) === TRUE) {
        $new_user_id = $conn->insert_id;

        // Bonus Sponsor & Pairing
        processBonusSponsor($sponsor_id, $new_user_id, $conn);
        if (function_exists('processBonusPairing')) {
            processBonusPairing($new_user_id, $conn);
        }

        $conn->commit();
        
        // Notifikasi Sukses SweetAlert2
        echo "<script>
            Swal.fire({
                icon: 'success',
                title: 'Registrasi Berhasil!',
                text: 'Selamat Bergabung, $full_name.',
                confirmButtonColor: '#10b981',
                confirmButtonText: 'Lanjut Login'
            }).then((result) => {
                window.location='login.php';
            });
        </script>";
        
    } else {
        throw new Exception($conn->error);
    }
} catch (Exception $e) {
    $conn->rollback();
    echo "<script>Swal.fire({icon: 'error', title: 'Error System', text: '".$e->getMessage()."'});</script>";
}
echo "</body></html>";
?>