<?php
session_start();
$key = md5(date("Y-m-d").":".$_SERVER['REMOTE_ADDR']);
if (isset($_SESSION['aW1iZXN0cmEuY29tLm15']) <> $key) {
    header("location:".$_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME']);
    exit;
}

include "_headerg.php";
include "_navtop.php";
include "_navside.php";
include "_functions.php";
require "conn.php";   

// Load settings
$setQ = mysqli_query($con, "SELECT mlm_type, width, level_limit FROM setting WHERE id = 1 LIMIT 1");
$set = mysqli_fetch_assoc($setQ);
$levelLimit = (int)($set['level_limit'] ?? 3);

// Package mapping
$packageStyles = [
    'None' => ['label'=>'None','color'=>'#64748b'],
    'Silver' => ['label'=>'Silver','color'=>'#C0C0C0'],
    'Gold' => ['label'=>'Gold','color'=>'#FFD700'],
    'Platinum' => ['label'=>'Platinum','color'=>'#6B0000'],
];

// Determine root
$usr = $_SESSION['username'];
$sid = (int)$_SESSION['aidi'];

// Helper
function profileImagePath($username) {
    return "uploads/profile/{$username}.jpg";
}

// Build tree recursively
$processedNodes = [];
function buildTreeData($con, $parentId, &$processedNodes, $level = 0) {
    global $levelLimit;

    if (in_array($parentId, $processedNodes)) return null;
    $processedNodes[] = $parentId;

    $res = mysqli_query($con, "SELECT * FROM ahli WHERE id='$parentId' LIMIT 1");
    $user = mysqli_fetch_assoc($res);
    if (!$user) return null;

    $node = [
        'id' => $user['id'],
        'username' => ($level==0) ? 'YOU' : $user['username'],
        'nama' => $user['nama'],
        'pakej' => $user['pakej'],
        'photo' => profileImagePath($user['username']),
        'level' => $level,
        'children' => []
    ];

    if ($_SESSION['role'] == 'admin' || $level < $levelLimit) {
        $childRes = mysqli_query($con, "SELECT id FROM ahli WHERE upline_id='{$parentId}' ORDER BY id");
        while ($child = mysqli_fetch_assoc($childRes)) {
            $childNode = buildTreeData($con, $child['id'], $processedNodes, $level + 1);
            if ($childNode) $node['children'][] = $childNode;
        }
    }

    return $node;
}

$treeData = buildTreeData($con, $sid, $processedNodes);
$treeJson = json_encode($treeData, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
$packageJson = json_encode($packageStyles, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
?>

<div id="page-wrapper">
    <div id="page-inner">
        <div class="row">
            <div class="col-md-6"><h2>Genealogy</h2></div>
        </div>
        <hr/>

        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading"><?= htmlspecialchars($usr) ?></div>
                    <div class="panel-body">

                        <!-- ✅ SCROLL CONTAINER UPDATED -->
                        <div style="overflow-x:auto; overflow-y:auto; width:100%; height:720px; background:#f7fbfc; padding:12px; border-radius:8px; white-space:nowrap;">
                            <div id="tree-container" style="display:inline-block;"></div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
body { font-family: Arial,sans-serif; }
.genealogy-tree { display:flex; flex-direction:column; align-items:center; gap:60px; position:relative; }
.tree-level { display:flex; justify-content:center; gap:50px; position:relative; width:100%; }
.parent-group { display:flex; flex-direction:column; align-items:center; position:relative; }
.children-group { display:flex; justify-content:center; gap:50px; position:relative; margin-top:60px; }
.node-box { width:120px; height:120px; background:#fff; border-radius:8px; display:flex; flex-direction:column; align-items:center; justify-content:center; cursor:pointer; position:relative; border:1px solid rgba(0,0,0,0.08); box-shadow:0 2px 4px rgba(0,0,0,0.1); z-index:2; }
.node-box.you { background:#e3f2fd; border:2px solid #2196f3; }
.node-photo { width:48px; height:48px; border-radius:8px; object-fit:cover; border:2px solid #fff; margin-bottom:4px; }
.node-info { font-size:12px; text-align:center; line-height:1.3; }
.node-badge { font-size:10px; margin-top:2px; padding:2px 6px; border-radius:4px; color:#fff; }
.tooltip { position:absolute; pointer-events:none; background:rgba(0,0,0,0.8); color:#fff; padding:6px 10px; border-radius:6px; font-size:12px; display:none; z-index:9999; }
.expand-btn { position:absolute; top:4px; right:4px; width:18px; height:18px; font-size:14px; background:#2196f3; color:#fff; border-radius:50%; text-align:center; line-height:18px; cursor:pointer; user-select:none; z-index:10; }

/* ✅ Smooth drag scroll cursor */
#tree-container { cursor: grab; }
#tree-container:active { cursor: grabbing; }

@media(max-width:600px){
    .genealogy-tree { gap:40px; }
    .node-box { width:100px; height:70px; }

    /* ❗ DO NOT WRAP CHILDREN → allow horizontal width */
    .children-group { 
        margin-top:40px; 
        flex-wrap:nowrap; 
    }
}
</style>

<script>
const treeData = <?= $treeJson ?>;
const packageStyles = <?= $packageJson ?>;
let collapsedNodes = new Set();

const tip=document.createElement('div'); tip.className='tooltip'; document.body.appendChild(tip);
function showTip(ev,node){ tip.style.display='block'; tip.innerHTML=`Username: ${node.username}<br>Package: ${node.pakej}<br>Level ${node.level}`; tip.style.left=(ev.pageX+8)+'px'; tip.style.top=(ev.pageY+8)+'px'; }
function moveTip(ev){ tip.style.left=(ev.pageX+8)+'px'; tip.style.top=(ev.pageY+8)+'px'; }
function hideTip(){ tip.style.display='none'; }

function createNode(node){
    const el=document.createElement('div'); el.className='node-box';
    if(node.username==='YOU') el.classList.add('you');

    const img=document.createElement('img'); img.src=node.photo||'assets/img/find_user.png'; img.className='node-photo';
    img.onerror=function(){ this.src='assets/img/find_user.png'; };
    const info=document.createElement('div'); info.className='node-info';
    info.innerHTML=`<strong>${node.username}</strong>
${node.level > 0 ? `<br><span class="node-badge" style="background:${packageStyles[node.pakej]?.color||'#64748b'}">${node.pakej}</span><br>Level ${node.level}` : ''}`;

    el.appendChild(img); el.appendChild(info);

    if(node.children && node.children.length>0){
        const btn=document.createElement('div'); btn.className='expand-btn';
        btn.textContent = collapsedNodes.has(node.id)?'+':'−';
        btn.addEventListener('click', e=>{ 
            e.stopPropagation();
            collapsedNodes.has(node.id) ? collapsedNodes.delete(node.id) : collapsedNodes.add(node.id);
            renderTree(treeData);
        });
        el.appendChild(btn);
    }

    el.addEventListener('mouseenter', e=>showTip(e,node));
    el.addEventListener('mousemove', moveTip);
    el.addEventListener('mouseleave', hideTip);
    return el;
}

function renderTree(root){
    const container=document.getElementById('tree-container');
    container.innerHTML='';
    const treeContainer=document.createElement('div'); treeContainer.className='genealogy-tree';
    const displayedNodes=new Set();

    function traverse(node){
        if(!node || displayedNodes.has(node.id)) return null;
        displayedNodes.add(node.id);

        const parentGroup=document.createElement('div'); parentGroup.className='parent-group';
        parentGroup.appendChild(createNode(node));

        if(node.children && node.children.length>0 && !collapsedNodes.has(node.id)){
            const childrenGroup=document.createElement('div'); childrenGroup.className='children-group';
            node.children.forEach(child=>{
                const c = traverse(child);
                if(c) childrenGroup.appendChild(c);
            });
            parentGroup.appendChild(childrenGroup);
        }
        return parentGroup;
    }

    treeContainer.appendChild(traverse(root));
    container.appendChild(treeContainer);
}
renderTree(treeData);

// ✅ Touch + Mouse drag scroll
let posX=0, scrollLeft=0;
const wrapper=document.querySelector('#tree-container').parentElement;

wrapper.addEventListener('mousedown',e=>{
    wrapper.isDown=true; posX=e.pageX-wrapper.offsetLeft; scrollLeft=wrapper.scrollLeft;
});
wrapper.addEventListener('mouseleave',()=>wrapper.isDown=false);
wrapper.addEventListener('mouseup',()=>wrapper.isDown=false);
wrapper.addEventListener('mousemove',e=>{
    if(!wrapper.isDown) return;
    e.preventDefault();
    const x=e.pageX-wrapper.offsetLeft;
    wrapper.scrollLeft=scrollLeft-(x-posX);
});
wrapper.addEventListener('touchstart',e=>{
    posX=e.touches[0].pageX-wrapper.offsetLeft; scrollLeft=wrapper.scrollLeft;
},{passive:true});
wrapper.addEventListener('touchmove',e=>{
    const x=e.touches[0].pageX-wrapper.offsetLeft;
    wrapper.scrollLeft=scrollLeft-(x-posX);
},{passive:true});
</script>

<?php include "_footer.php"; ?>
