<?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']); // cara baru !
} else {
    include "_headerg.php";
    include "_navtop.php";
    include "_navside.php";
    include "_functions.php";
    require "conn.php";   
    
    // --- Cari jumlah level komisen secara dinamik
    $columnsRes = mysqli_query($con, "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='komisen' AND COLUMN_NAME LIKE 'lvl%' ORDER BY COLUMN_NAME ASC");
    $levels = [];
    while ($row = mysqli_fetch_assoc($columnsRes)) {
        $levels[] = $row['COLUMN_NAME'];
    }
    // Dapatkan setting sistem
    $set = mysqli_fetch_assoc(mysqli_query($con, "SELECT level_limit FROM setting WHERE id = 1 LIMIT 1"));
    $maxLevel = (int)$set['level_limit']; // Contoh: 9

    // --- Mapping pakej ke color
    $packageStyles = [
        0 => ['color'=>'#FF0000'], // tiada pakej / default
        1 => ['color'=>'#6B0000'], // Silver
        2 => ['color'=>'#FFD700'], // Gold
        3 => ['color'=>'#C0C0C0'], // Platinum
        // tambah lagi kalau perlu
    ];
?>
<div id="page-wrapper" >
    <div id="page-inner">
        <div class="row">
            <div class="col-md-12" style="vertical-align: middle;">
                <div class="col-md-6" style="display: inline-block; vertical-align: middle;">
                    <h2>Genealogy</h2> 
                </div>
                <?php if ($_SESSION['username'] == "admin") { ?>
                <br/>
                <div class="col-md-6 "  style="display: inline-block; vertical-align: middle;">
                    <form role="form" method="post">
                        <div class="input-group">
                            <input type="text" name="u" class="form-control" placeholder="username" />
                            <span class="form-group input-group-btn">
                                <button class="btn btn-default" type="submit" name="<?= sha1($_SERVER['REMOTE_ADDR']) ?>"> Search </button>
                            </span>
                        </div>
                    </form>
                </div>
                <?php } ?>
            </div>
        </div>
        <hr />

        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
<?php
                        if (isset($_POST[sha1($_SERVER['REMOTE_ADDR'])])) {
                            $uuu = mysqli_real_escape_string($con, $_POST['u']);
                            $sql = "SELECT id FROM ahli WHERE username = '".$uuu."' LIMIT 1";
                            $count = mysqli_num_rows(mysqli_query($con, $sql));
                        
                            if ($count == 1) {
                                $uuid = mysqli_fetch_array(mysqli_query($con, $sql));
                                $usr = $uuu;
                                $sid = $uuid[0];
                            } else {
                                $usr = "Result";
                                $blank = "&nbsp;&nbsp;<code>Username not found !</code>";
                            } 
                        } else {
                            $usr = $_SESSION['username'];
                            $sid = $_SESSION['aidi'];
                            $blank = "";
                        }
?>
                        <?= htmlspecialchars($usr) ?>
                    </div>
                    <div class="panel-body" style="margin-left:-30px;">
                        <div class="col-md-12">
                            <div class="tree-container">
                                <?= $blank ?>                                
                                <ul >
<?php
                                    function renderTree($con, $parentId, $level, $maxLevel, $packageStyles) {
                                        if ($_SESSION['role'] != 'admin')    {    if ($level > $maxLevel) return;    }
                                    
                                        $ssql = "SELECT * FROM ahli WHERE penaja='".$parentId."' ORDER BY id";
                                        $result = mysqli_query($con, $ssql);
                                        $num = mysqli_num_rows($result);
                                    
                                        if ($num > 0) {
                                            echo "<ul id='treemenu1' class='treeview'>";
                                            while ($row = mysqli_fetch_assoc($result)) {
                                                $pakej = $row['pakej']; 
                                                $color = isset($packageStyles[$pakej]['color']) ? $packageStyles[$pakej]['color'] : '#000';
                                    
                                                $strText = "
                                                    <span style='display:block; color:{$color}; font-weight:bold;'>" . htmlspecialchars($row['nama']) . "</span>
                                                    <span style='display:block;'><code>" . htmlspecialchars($row['username']) . "</code></span>
                                                    <span style='display:block;'><code>" . htmlspecialchars($row['tarikh']) . "</code></span>
                                                    <span style='display:block;'><code>" . htmlspecialchars($pakej) . "</code></span>
                                                ";
                                    
                                                $icon = "assets/img/level{$level}.png"; // icon ikut level
                                    
                                                if ($_SESSION['role'] == 'admin')    {    
                                                    
                                                    if ($level > $maxLevel) {    
                                                
                                                        $userImage = "uploads/profile/{$row['username']}.jpg";
                                                        $defaultImage = "assets/img/find_user.png";
                                                        
                                                        if (!empty($_SESSION['photo']) && file_exists($userImage)) {
                                                            $icon = $userImage . "?v=" . time(); // force refresh
                                                        } else {
                                                            $icon = $defaultImage;
                                                        }
                                                    }
                                                }
                                    
                                                echo "<li>
                                                    <div class='row' style='margin-bottom:15px; padding-top:10px; '>
                                                            <div class='text-middle text-center'>
                                                                <img class='img-thumbnail img-circle' src='{$icon}'/>
                                                                <h6><code> Level {$level} </code></h6>
                                                                <div style='display:inline-block; vertical-align:middle;'>{$strText}</div>
                                                            </div>
                                                    </div>";
                                    
                                                renderTree($con, $row['id'], $level + 1, $maxLevel, $packageStyles);
                                    
                                                echo "</li>";
                                            }
                                            echo "</ul>";
                                        }
                                    }
                                    
                                    renderTree($con, $sid, 1, $maxLevel, $packageStyles);
                                    
                                    mysqli_close($con);
?>
                                </ul>

                                <script type="text/javascript">
                                    ddtreemenu.createTree("treemenu1", true);
                                </script>
                                <div class="col-md-12">
                                </div>                                
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

<?php kaki: ?>			 
    </div>
</div>
<?php
    include "_footer.php";
}
?>
