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

// 1. Cek Login & Ambil Data User Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php"); exit();
}

$my_id = $_SESSION['user_id'];

// Ambil Kode Referral User (Untuk link register node kosong)
$sqlUser = "SELECT referral_code FROM users WHERE id = $my_id";
$resUser = $conn->query($sqlUser)->fetch_assoc();
$my_ref_code = $resUser['referral_code'] ?? '';

// 2. Tentukan Root Node
$root_id = isset($_GET['id']) ? intval($_GET['id']) : $my_id;

// ============================================================
// FUNGSI LOGIKA HITUNG DOWNLINE (REAL COUNT)
// ============================================================

// Fungsi Rekursif: Menghitung total member di bawah ID tertentu (Unlimited Depth)
function countTotalDownlineRecursive($parent_id, $conn) {
    if (!$parent_id) return 0;
    
    $total = 0;
    // Cari semua anak langsung (Direct Child) di bawah parent ini
    $sql = "SELECT id FROM users WHERE binary_parent_id = $parent_id";
    $result = $conn->query($sql);
    
    while ($row = $result->fetch_assoc()) {
        // Hitung 1 (anak ini) + semua keturunannya
        $total += 1 + countTotalDownlineRecursive($row['id'], $conn);
    }
    return $total;
}

// Fungsi Utama: Mengambil Statistik L/R untuk Node Tertentu
function getNetworkStats($node_id, $conn) {
    if (!$node_id) return ['L' => 0, 'R' => 0, 'total' => 0];

    // 1. Cari ID Anak Kiri
    $sqlL = "SELECT id FROM users WHERE binary_parent_id = $node_id AND position = 'left'";
    $resL = $conn->query($sqlL)->fetch_assoc();
    $idL = $resL ? $resL['id'] : null;

    // 2. Cari ID Anak Kanan
    $sqlR = "SELECT id FROM users WHERE binary_parent_id = $node_id AND position = 'right'";
    $resR = $conn->query($sqlR)->fetch_assoc();
    $idR = $resR ? $resR['id'] : null;

    // 3. Hitung Rekursif masing-masing kaki
    // Jika ada anak kiri, hitung 1 (anak itu sendiri) + seluruh keturunannya
    $countL = $idL ? 1 + countTotalDownlineRecursive($idL, $conn) : 0;
    
    // Jika ada anak kanan, hitung 1 (anak itu sendiri) + seluruh keturunannya
    $countR = $idR ? 1 + countTotalDownlineRecursive($idR, $conn) : 0;

    return [
        'L' => $countL,
        'R' => $countR,
        'total' => $countL + $countR
    ];
}

// Fungsi Helper: Ambil Data Node User
function getNodeData($id, $conn) {
    if (!$id) return null;
    
    $sql = "SELECT id, username, role, balance_idr FROM users WHERE id = $id";
    $result = $conn->query($sql);
    
    if ($result->num_rows > 0) {
        $data = $result->fetch_assoc();
        
        // --- HITUNG REAL STATS ---
        $stats = getNetworkStats($id, $conn);
        
        $data['left_count'] = $stats['L'];
        $data['right_count'] = $stats['R'];
        $data['total_downline'] = $stats['total'];
        
        return $data;
    }
    return null;
}

// Fungsi Helper: Cari ID anak untuk navigasi Tree View
function getChildId($parent_id, $pos, $conn) {
    if(!$parent_id) return null;
    $sql = "SELECT id FROM users WHERE binary_parent_id = $parent_id AND position = '$pos'";
    $res = $conn->query($sql)->fetch_assoc();
    return $res ? $res['id'] : null;
}

// ============================================================
// PERSIAPAN DATA VISUALISASI TREE (3 LEVEL)
// ============================================================

// 1. Root
$node_root = getNodeData($root_id, $conn);

// 2. Level 1
$id_L = getChildId($root_id, 'left', $conn);
$node_L = getNodeData($id_L, $conn);

$id_R = getChildId($root_id, 'right', $conn);
$node_R = getNodeData($id_R, $conn);

// 3. Level 2 (Cucu)
$id_LL = ($node_L) ? getChildId($node_L['id'], 'left', $conn) : null;
$node_LL = getNodeData($id_LL, $conn);
$id_LR = ($node_L) ? getChildId($node_L['id'], 'right', $conn) : null;
$node_LR = getNodeData($id_LR, $conn);

$id_RL = ($node_R) ? getChildId($node_R['id'], 'left', $conn) : null;
$node_RL = getNodeData($id_RL, $conn);
$id_RR = ($node_R) ? getChildId($node_R['id'], 'right', $conn) : null;
$node_RR = getNodeData($id_RR, $conn);


// --- FUNGSI RENDER HTML NODE ---
function renderNode($data, $position_label, $parent_id = null, $position = null) {
    global $my_ref_code; 
    $bg_color = "bg-gray-100 dark:bg-slate-700"; 
    $border_color = "border-gray-300 dark:border-slate-600";
    $icon_color = "text-gray-400";
    $role_badge = "";

    // PENTING: Tambahkan 'mx-auto' agar kotak selalu di tengah-tengah list item (li)
    $center_class = "mx-auto"; 

    // KONDISI 1: Node Kosong (Target Registrasi)
    if (!$data) {
        $link = "register.php?placement_id=$parent_id&pos=$position&ref=$my_ref_code";
        return '
        <a href="'.$link.'" class="'.$center_class.' flex flex-col items-center justify-center p-2 w-24 h-28 rounded-xl border-2 border-dashed border-gray-300 hover:border-green-400 group transition bg-white dark:bg-slate-800 opacity-60">
            <div class="w-8 h-8 rounded-full bg-gray-100 flex items-center justify-center mb-1 group-hover:bg-green-100">
                <i class="fas fa-plus text-xs text-gray-400 group-hover:text-green-500"></i>
            </div>
            <span class="text-[9px] text-gray-400">Empty</span>
            <span class="text-[8px] uppercase font-bold text-gray-300">'.$position_label.'</span>
        </a>';
    }

    // KONDISI 2: Node Terisi
    if ($data['role'] == 'premium') {
        $bg_color = "bg-gradient-to-b from-yellow-50 to-white dark:from-slate-800 dark:to-slate-900";
        $border_color = "border-yellow-400";
        $icon_color = "text-yellow-500";
        $role_badge = '<span class="absolute -top-2 -right-2 bg-yellow-400 text-black text-[8px] px-1 rounded font-bold shadow">PRO</span>';
    } else {
        $bg_color = "bg-white dark:bg-slate-800";
        $border_color = "border-gray-300 dark:border-slate-600";
        $icon_color = "text-blue-500";
        $role_badge = '<span class="absolute -top-2 -right-2 bg-gray-400 text-white text-[8px] px-1 rounded font-bold">STD</span>';
    }

    $link = "?id=" . $data['id'];

    // Update Class: Tambahkan 'mx-auto' dan 'z-10' agar posisi pas di tengah garis
    return '
    <a href="'.$link.'" class="'.$center_class.' relative flex flex-col items-center p-2 w-24 sm:w-28 rounded-xl border-b-4 shadow-sm hover:shadow-lg hover:-translate-y-1 transition-all duration-200 '.$bg_color.' '.$border_color.' z-10">
        '.$role_badge.'
        <div class="w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-900 flex items-center justify-center mb-1 shadow-inner">
            <i class="fas fa-user '.$icon_color.'"></i>
        </div>
        <div class="text-center w-full overflow-hidden leading-tight mb-1">
            <p class="font-bold text-xs truncate w-full dark:text-gray-200">'.$data['username'].'</p>
            <p class="text-[9px] text-gray-400 uppercase">'.$position_label.'</p>
        </div>
        
        <div class="w-full space-y-1">
            <div class="flex justify-between w-full text-[9px] bg-slate-100 dark:bg-slate-900 rounded px-1.5 py-0.5">
                <span class="text-blue-500 font-bold">L:'.$data['left_count'].'</span>
                <span class="text-gray-300">|</span>
                <span class="text-green-500 font-bold">R:'.$data['right_count'].'</span>
            </div>
            <div class="text-[8px] text-center bg-gray-200 dark:bg-slate-600 rounded px-1 text-gray-600 dark:text-gray-300">
                Downline: <b>'.$data['total_downline'].'</b>
            </div>
        </div>
    </a>';
}

// 4. SET MENU AKTIF
$active_menu = 'network';
?>

<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jaringan Binary</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: { extend: { colors: { primary: '#10b981', darkbg: '#0f172a' } } }
        }
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    
    <style>
        /* CSS TREE GENEALOGY YANG DIPERBAIKI */
        .tree {
            display: flex;
            justify-content: center;
            padding-top: 20px;
            width: max-content; 
            min-width: 100%;
            padding-bottom: 120px;
            margin: 0 auto;
        }
        .tree ul {
            padding-top: 20px; 
            position: relative;
            transition: all 0.5s;
            display: flex;
            justify-content: center; /* PENTING: Agar anak berada di tengah induk */
        }
        .tree li {
            text-align: center; /* PENTING: Agar konten di dalam li (yaitu <a>) berada di tengah */
            list-style-type: none;
            position: relative;
            padding: 20px 5px 0 5px;
            transition: all 0.5s;
        }
        
        /* GARIS PENGHUBUNG */
        /* Garis Horizontal diatas Node Anak */
        .tree li::before, .tree li::after{
            content: '';
            position: absolute; top: 0; right: 50%;
            border-top: 2px solid #94a3b8;
            width: 50%; height: 20px;
        }
        .tree li::after{
            right: auto; left: 50%;
            border-left: 2px solid #94a3b8;
        }
        
        /* Hilangkan garis untuk anak tunggal/pertama/terakhir agar rapi */
        .tree li:only-child::after, .tree li:only-child::before { display: none; }
        .tree li:only-child{ padding-top: 0;}
        .tree li:first-child::before, .tree li:last-child::after{ border: 0 none; }
        
        /* Lengkungan Siku Garis */
        .tree li:last-child::before{
            border-right: 2px solid #94a3b8;
            border-radius: 0 5px 0 0;
        }
        .tree li:first-child::after{
            border-radius: 5px 0 0 0;
        }
        
        /* Garis Vertikal Turun dari Induk ke Anak-anak */
        .tree ul ul::before{
            content: '';
            position: absolute; top: 0; left: 50%;
            border-left: 2px solid #94a3b8;
            width: 0; height: 20px;
        }
        
        /* Warna Garis Mode Gelap */
        .dark .tree li::before, .dark .tree li::after, .dark .tree ul ul::before {
            border-color: #475569;
        }
        
        /* Utilities */
        .hide-scroll::-webkit-scrollbar { display: none; }
        .hide-scroll { -ms-overflow-style: none; scrollbar-width: none; }
        
        .bg-dot-pattern {
            background-image: radial-gradient(#cbd5e1 1px, transparent 1px);
            background-size: 20px 20px;
        }
        .dark .bg-dot-pattern {
            background-image: radial-gradient(#334155 1px, transparent 1px);
        }
        
        .tree-container {
            display: flex;
            justify-content: center;
            min-width: 100%;
        }
    </style>
</head>
<body class="bg-gray-50 dark:bg-darkbg text-gray-800 dark:text-gray-200 transition-colors duration-300">

    

[Image of binary tree structure]


    <div class="fixed top-0 w-full z-40 bg-white dark:bg-slate-900 shadow-sm border-b dark:border-slate-800">
        <div class="max-w-md mx-auto px-4 py-3 flex justify-between items-center">
            <h1 class="font-bold text-lg"><i class="fas fa-sitemap text-primary mr-2"></i>Network Tree</h1>
            <?php if($root_id != $my_id): ?>
                <a href="network.php" class="text-xs bg-slate-200 dark:bg-slate-700 px-3 py-1 rounded-full hover:bg-slate-300 transition">
                    <i class="fas fa-arrow-up mr-1"></i> Back to Me
                </a>
            <?php endif; ?>
        </div>
    </div>

    <div class="max-w-md mx-auto min-h-screen pt-16 relative bg-dot-pattern">
        
        <div class="px-4 mt-2 mb-2 flex gap-4 justify-center text-[10px]">
            <div class="flex items-center gap-1">
                <div class="w-3 h-3 bg-yellow-400 rounded-sm"></div> Premium
            </div>
            <div class="flex items-center gap-1">
                <div class="w-3 h-3 bg-white border border-gray-300 rounded-sm"></div> Starter
            </div>
            <div class="flex items-center gap-1">
                <div class="w-3 h-3 border border-dashed border-gray-400 rounded-sm"></div> Empty
            </div>
        </div>

        <div class="overflow-x-auto hide-scroll pb-24">
            <div class="tree-container">
                <div class="tree">
                    <ul>
                        <li>
                            <?php echo renderNode($node_root, 'ROOT', null, null); ?>
                            
                            <ul>
                                <li>
                                    <?php echo renderNode($node_L, 'LEFT', $node_root['id'], 'left'); ?>
                                    <ul>
                                        <li><?php echo renderNode($node_LL, 'L-L', $node_L ? $node_L['id'] : null, 'left'); ?></li>
                                        <li><?php echo renderNode($node_LR, 'L-R', $node_L ? $node_L['id'] : null, 'right'); ?></li>
                                    </ul>
                                </li>
                                
                                <li>
                                    <?php echo renderNode($node_R, 'RIGHT', $node_root['id'], 'right'); ?>
                                    <ul>
                                        <li><?php echo renderNode($node_RL, 'R-L', $node_R ? $node_R['id'] : null, 'left'); ?></li>
                                        <li><?php echo renderNode($node_RR, 'R-R', $node_R ? $node_R['id'] : null, 'right'); ?></li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        
        <?php include 'footer_nav.php'; ?>

    </div>
</body>
</html>