<?php
// functions_mlm.php

// ============================================================
// BAGIAN 1: LOGIKA PENEMPATAN OTOMATIS (AUTO PLACEMENT)
// ============================================================

function findFirstAvailableSlot($sponsor_id, $conn) {
    $queue = [$sponsor_id]; 
    
    while (count($queue) > 0) {
        $current_parent_id = array_shift($queue); 
        
        // 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) {
            return ['parent_id' => $current_parent_id, 'position' => 'left'];
        } else {
            $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) {
            return ['parent_id' => $current_parent_id, 'position' => 'right'];
        } else {
            $child = $resR->fetch_assoc();
            array_push($queue, $child['id']);
        }
    }
    return null; 
}

// ============================================================
// BAGIAN 2: LOGIKA BONUS (UPDATED)
// ============================================================

function processBonusSponsor($sponsor_id, $trigger_user_id, $conn) {
    $bonus = 300000 * 0.30; 
    
    $qUser = $conn->query("SELECT username FROM users WHERE id = $trigger_user_id");
    $trigger_name = ($qUser->fetch_assoc())['username'] ?? 'Unknown';
    
    $desc = "Bonus Sponsor New Member [$trigger_name] Level 1";
    
    $conn->query("UPDATE users SET balance_idr = balance_idr + $bonus WHERE id = $sponsor_id");
    
    $sql = "INSERT INTO transactions (user_id, type, amount, status, description) 
            VALUES ($sponsor_id, 'bonus_sponsor', $bonus, 'success', '$desc')";
    $conn->query($sql);
}

function processBonusProject($sponsor_id, $trigger_user_id, $project_type, $amount_bonus, $conn) {
    $qUser = $conn->query("SELECT username FROM users WHERE id = $trigger_user_id");
    $trigger_name = ($qUser->fetch_assoc())['username'] ?? 'Unknown';

    $desc = "Bonus Sponsor $project_type [$trigger_name] Level 1";
    
    $db_type = 'bonus_sponsor'; 
    if(strpos($project_type, 'Stokis') !== false) $db_type = 'bonus_stokis'; 
    if(strpos($project_type, 'Crowd') !== false) $db_type = 'bonus_crowd';
    if(strpos($project_type, 'Crypto') !== false) $db_type = 'bonus_crypto';

    $conn->query("UPDATE users SET balance_idr = balance_idr + $amount_bonus WHERE id = $sponsor_id");
    
    $sql = "INSERT INTO transactions (user_id, type, amount, status, description) 
            VALUES ($sponsor_id, '$db_type', $amount_bonus, 'success', '$desc')";
    $conn->query($sql);
}

function processBonusRoyalty($upline_id, $trigger_user_id, $level, $amount_bonus, $conn) {
    $qUser = $conn->query("SELECT username FROM users WHERE id = $trigger_user_id");
    $trigger_name = ($qUser->fetch_assoc())['username'] ?? 'Unknown';

    $desc = "Bonus Royalty [$trigger_name] Level $level";

    $conn->query("UPDATE users SET balance_idr = balance_idr + $amount_bonus WHERE id = $upline_id");
    
    $sql = "INSERT INTO transactions (user_id, type, amount, status, description) 
            VALUES ($upline_id, 'bonus_royalty', $amount_bonus, 'success', '$desc')";
    $conn->query($sql);
}

// Wrapper
function processBonusPairing($new_user_id, $conn) {
    hitungBonusPairing($new_user_id, $conn);
}


// ============================================================
// BAGIAN 3: LOGIKA PAIRING & LEVELING (BINARY CORE)
// ============================================================

// HELPER BARU: Mencari nama user di kedalaman tertentu pada kaki tertentu
function getOneUserAtRelativeLevel($root_id, $position, $target_rel_level, $conn) {
    // 1. Ambil anak langsung di posisi $position (left/right)
    $sqlChild = "SELECT id, username FROM users WHERE binary_parent_id = $root_id AND position = '$position'";
    $child = $conn->query($sqlChild)->fetch_assoc();

    if (!$child) return 'Unknown'; // Kaki kosong

    // Jika target level 1, kembalikan nama anak ini
    if ($target_rel_level == 1) return $child['username'];

    // Jika level > 1, kita harus mencari keturunan (BFS sederhana untuk cari 1 nama saja)
    $queue = [[$child['id'], 1]]; // [id, current_rel_depth]

    while(count($queue) > 0) {
        $current = array_shift($queue);
        $curr_id = $current[0];
        $curr_depth = $current[1];

        // Ambil anak-anaknya
        $sql = "SELECT id, username FROM users WHERE binary_parent_id = $curr_id";
        $res = $conn->query($sql);

        while($row = $res->fetch_assoc()) {
            if ($curr_depth + 1 == $target_rel_level) {
                return $row['username']; // KETEMU SATU!
            }
            array_push($queue, [$row['id'], $curr_depth + 1]);
        }
    }
    return 'Unknown';
}

function hitungBonusPairing($new_user_id, $conn) {
    // Ambil Username Member Baru (Pemicu)
    $qNew = $conn->query("SELECT username FROM users WHERE id = $new_user_id");
    $new_user_name = ($qNew->fetch_assoc())['username'] ?? 'Unknown';

    // 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'];
    
    // Variable tracking untuk mengetahui kaki mana kita datang (Left/Right)
    $child_tracker_id = $newUser['id']; 

    // 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)
    $max_levels_up = 25;
    $counter = 0;

    while ($current_upline_id != null && $counter < $max_levels_up) {
        
        // Ambil data Upline
        $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();

        // Cari tahu posisi $child_tracker_id relative terhadap $upline (Left atau Right?)
        // Ini penting untuk menentukan siapa pasangan di kaki seberang.
        $qPos = $conn->query("SELECT position FROM users WHERE id = $child_tracker_id");
        $posData = $qPos->fetch_assoc();
        $coming_from_pos = $posData['position']; // 'left' atau 'right'

        // Hitung Level Relatif
        $relative_level = $source_depth - $upline['depth_level'];

        // SYARAT PAIRING:
        $countLeft = countMemberAtLevel($upline['id'], 'left', $relative_level, $conn);
        $countRight = countMemberAtLevel($upline['id'], 'right', $relative_level, $conn);
        
        $pairs_potential = min($countLeft, $countRight);
        
        $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) {
            
            // Cek Limit Harian
            $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
                
                // Cari Nama Pasangan di Kaki Seberang
                $opposite_pos = ($coming_from_pos == 'left') ? 'right' : 'left';
                $partner_name = getOneUserAtRelativeLevel($upline['id'], $opposite_pos, $relative_level, $conn);
                
                // Format Deskripsi: "Bonus Pairing Level 1 dari [Agus] dan [Budi]"
                $desc = "Bonus Pairing Level $relative_level dari [$new_user_name] dan [$partner_name]";

                // 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
                $insTrans = "INSERT INTO transactions (user_id, type, amount, status, description) 
                             VALUES ({$upline['id']}, 'bonus_pairing', $bonus_nominal, 'success', '$desc')";
                $conn->query($insTrans);
            }
        }

        // Persiapan Loop Berikutnya
        $child_tracker_id = $upline['id']; // Naik satu tingkat
        $current_upline_id = $upline['binary_parent_id'];
        $counter++;
    }
}

// Helper Function: Menghitung total member
function countMemberAtLevel($upline_id, $position, $target_relative_depth, $conn) {
    $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;
    if ($target_relative_depth == 1) return 1;

    $target_absolute_depth = ($child['depth_level'] - 1) + $target_relative_depth;
    return getSubtreeCount($child['id'], $target_absolute_depth, $conn);
}

// Helper Tambahan
function getSubtreeCount($root_id, $target_absolute_depth, $conn) {
    $count = 0;
    $q = $conn->query("SELECT id, depth_level FROM users WHERE id = $root_id");
    if($q->num_rows == 0) return 0;
    $node = $q->fetch_assoc();
    
    if ($node['depth_level'] == $target_absolute_depth) { return 1; }
    if ($node['depth_level'] > $target_absolute_depth) { return 0; }
    
    $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);
    }
    
    $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;
}
?>