<?php
// functions_mlm.php

// ============================================================
// BAGIAN 1: LOGIKA BARU (AUTO PLACEMENT & BONUS SPONSOR)
// ============================================================

// 1. Fungsi Mencari Posisi Kosong (Auto-Placement / Spillover)
// Algoritma: Breadth-First Search (BFS) - Mencari level teratas, dari kiri ke kanan.
function findFirstAvailableSlot($sponsor_id, $conn) {
    $queue = [$sponsor_id]; // Mulai antrian dari Sponsor
    
    while (count($queue) > 0) {
        $current_parent_id = array_shift($queue); // Ambil antrian paling depan
        
        // Cek Kaki KIRI
        $sqlL = "SELECT id FROM users WHERE binary_parent_id = $current_parent_id AND position = 'left'";
        $resL = $conn->query($sqlL);
        if ($resL->num_rows == 0) {
            // KETEMU! Slot Kiri Kosong
            return ['parent_id' => $current_parent_id, 'position' => 'left'];
        } else {
            // Jika ada isinya, masukkan anak ini ke antrian untuk diperiksa nanti
            $child = $resL->fetch_assoc();
            array_push($queue, $child['id']);
        }
        
        // Cek Kaki KANAN
        $sqlR = "SELECT id FROM users WHERE binary_parent_id = $current_parent_id AND position = 'right'";
        $resR = $conn->query($sqlR);
        if ($resR->num_rows == 0) {
            // KETEMU! Slot Kanan Kosong
            return ['parent_id' => $current_parent_id, 'position' => 'right'];
        } else {
            // Jika ada isinya, masukkan anak ini ke antrian
            $child = $resR->fetch_assoc();
            array_push($queue, $child['id']);
        }
    }
    return null; // Should not happen in infinite tree
}

// 2. Fungsi Eksekusi Bonus Sponsor (30% Starter)
function processBonusSponsor($sponsor_id, $conn) {
    $bonus = 300000 * 0.30; // 30% dari 300rb = 90.000
    
    // Update Saldo
    $conn->query("UPDATE users SET balance_idr = balance_idr + $bonus WHERE id = $sponsor_id");
    
    // Catat Transaksi
    $desc = "Bonus Sponsor New Member";
    $conn->query("INSERT INTO transactions (user_id, type, amount, status, description) 
                  VALUES ($sponsor_id, 'bonus_sponsor', $bonus, 'success', '$desc')");
}

// 3. Wrapper untuk memanggil Logika Pairing Lama
function processBonusPairing($new_user_id, $conn) {
    // Memanggil fungsi logika hitungBonusPairing yang lama
    hitungBonusPairing($new_user_id, $conn);
}


// ============================================================
// BAGIAN 2: LOGIKA LAMA (HITUNG BONUS PAIRING & LEVELING)
// ============================================================

function hitungBonusPairing($new_user_id, $conn) {
    // 1. Ambil Data User Baru
    $sql = "SELECT id, binary_parent_id, position, depth_level FROM users WHERE id = $new_user_id";
    $res = $conn->query($sql);
    
    if($res->num_rows == 0) return;
    $newUser = $res->fetch_assoc();
    
    if (!$newUser || !$newUser['binary_parent_id']) return;

    $current_upline_id = $newUser['binary_parent_id'];
    $source_depth = $newUser['depth_level'];
    
    // Nilai Bonus
    $paket_starter = 300000;
    $persen_bonus = 0.05; // 5%
    $bonus_nominal = $paket_starter * $persen_bonus; // Rp 15.000
    
    // LOOPING NAIK KE ATAS (Mencari nenek moyang)
    // Kita batasi loop max 25 level ke atas sesuai request
    $max_levels_up = 25;
    $counter = 0;

    while ($current_upline_id != null && $counter < $max_levels_up) {
        
        // Ambil data Upline saat ini
        $qUpline = "SELECT id, binary_parent_id, position, depth_level FROM users WHERE id = $current_upline_id";
        $resUpline = $conn->query($qUpline);
        if($resUpline->num_rows == 0) break;
        $upline = $resUpline->fetch_assoc();

        // Hitung Level Relatif (Jarak Level Upline ke User Baru)
        $relative_level = $source_depth - $upline['depth_level'];

        // SYARAT PAIRING:
        // Cek jumlah member di Kaki Kiri vs Kaki Kanan pada Level Relatif tersebut
        $countLeft = countMemberAtLevel($upline['id'], 'left', $relative_level, $conn);
        $countRight = countMemberAtLevel($upline['id'], 'right', $relative_level, $conn);
        
        // Pairing terjadi jika: Jumlah Terkecil > Jumlah Pasangan yang SUDAH dibayar
        $pairs_potential = min($countLeft, $countRight);
        
        // Cek berapa pasang yang SUDAH dibayar ke Upline ini untuk Level ini
        $qPaid = "SELECT COUNT(*) as total FROM pairing_logs 
                  WHERE user_id = {$upline['id']} AND pair_from_level = $relative_level";
        $paidData = $conn->query($qPaid)->fetch_assoc();
        $already_paid = $paidData['total'];

        if ($pairs_potential > $already_paid) {
            // ADA PASANGAN BARU TERBENTUK!
            
            // Cek Limit Harian (Flash Out) -> Max 10 per level per hari
            $today = date('Y-m-d');
            $qDaily = "SELECT COUNT(*) as today_count FROM pairing_logs 
                       WHERE user_id = {$upline['id']} 
                       AND pair_from_level = $relative_level 
                       AND date_recorded = '$today'";
            $dailyData = $conn->query($qDaily)->fetch_assoc();
            
            if ($dailyData['today_count'] < 10) {
                // EKSEKUSI BONUS
                
                // 1. Catat Log
                $insLog = "INSERT INTO pairing_logs (user_id, pair_from_level, bonus_amount, date_recorded) 
                           VALUES ({$upline['id']}, $relative_level, $bonus_nominal, '$today')";
                $conn->query($insLog);
                
                // 2. Tambah Saldo Upline
                $updSaldo = "UPDATE users SET balance_idr = balance_idr + $bonus_nominal WHERE id = {$upline['id']}";
                $conn->query($updSaldo);
                
                // 3. Catat Transaksi agar muncul di history
                $desc = "Bonus Pairing Level $relative_level";
                $insTrans = "INSERT INTO transactions (user_id, type, amount, status, description) 
                             VALUES ({$upline['id']}, 'bonus_pairing', $bonus_nominal, 'success', '$desc')";
                $conn->query($insTrans);
            } else {
                // FLUSH OUT (Sudah lebih dari 10 pasang hari ini)
                // Bonus hangus
            }
        }

        // --- Persiapan Loop Berikutnya ---
        // Pindah pointer ke Upline di atasnya lagi
        $current_upline_id = $upline['binary_parent_id'];
        $counter++;
    }
}

// Helper Function: Menghitung total member di kaki tertentu pada kedalaman tertentu
function countMemberAtLevel($upline_id, $position, $target_relative_depth, $conn) {
    // Cari dulu ID anak langsung di posisi $position (Kiri/Kanan)
    $sqlChild = "SELECT id, depth_level FROM users WHERE binary_parent_id = $upline_id AND position = '$position'";
    $child = $conn->query($sqlChild)->fetch_assoc();
    
    if (!$child) return 0; // Kakinya putus/kosong
    
    // Jika target depth adalah 1, berarti anak langsung itu sendiri
    if ($target_relative_depth == 1) return 1;

    // Jika lebih dalam, hitung semua node di bawah anak tersebut yang memiliki depth = upline_depth + target
    $target_absolute_depth = ($child['depth_level'] - 1) + $target_relative_depth;
    
    // Panggil fungsi rekursif pencari subtree (Helper tambahan agar tidak error)
    return getSubtreeCount($child['id'], $target_absolute_depth, $conn);
}

// Helper Tambahan: Mencari jumlah node dalam subtree yang memiliki depth tertentu
function getSubtreeCount($root_id, $target_absolute_depth, $conn) {
    $count = 0;
    
    // Ambil info node saat ini
    $q = $conn->query("SELECT id, depth_level FROM users WHERE id = $root_id");
    if($q->num_rows == 0) return 0;
    $node = $q->fetch_assoc();
    
    // Jika depth node ini sama dengan target, hitung 1
    if ($node['depth_level'] == $target_absolute_depth) {
        return 1; 
    }
    
    // Jika depth node ini sudah LEBIH dari target, stop (optimasi)
    if ($node['depth_level'] > $target_absolute_depth) {
        return 0;
    }
    
    // Recursive cari ke anak kiri
    $qL = $conn->query("SELECT id FROM users WHERE binary_parent_id = $root_id AND position = 'left'");
    if($childL = $qL->fetch_assoc()) {
        $count += getSubtreeCount($childL['id'], $target_absolute_depth, $conn);
    }
    
    // Recursive cari ke anak kanan
    $qR = $conn->query("SELECT id FROM users WHERE binary_parent_id = $root_id AND position = 'right'");
    if($childR = $qR->fetch_assoc()) {
        $count += getSubtreeCount($childR['id'], $target_absolute_depth, $conn);
    }
    
    return $count;
}
?>