    <?php
    include_once '../db/koneksi.php';

    // Pastikan admin terautentikasi
    // if (!isset($_SESSION['kode_admin'])) {
    //     echo '
    //       <script>
    //         alert("Terjadi kesalahan, harap masuk kembali!");
    //         window.location.replace("' . $alamat_admin . 'keluar.php");
    //       </script>
    //     ';
    //     exit;
    // }

    // Ambil parameter user referral
    // if (!isset($_GET['upline'])) {
    //     echo '<script>alert("User referral tidak ditemukan!"); window.location.replace("' . $alamat_admin . 'referral.php");</script>';
    //     exit;
    // }

    $upline = isset($_GET['halaman_item']) ? $_GET['halaman_item'] : null;
    if(is_null($upline)) {
        echo '<script>alert("User referral tidak ditemukan!"); window.location.replace("' . $alamat_admin . 'referral");</script>';
    }
    $q_upline = mysqli_query($koneksi, "SELECT username FROM tb_user WHERE referral = '$upline' LIMIT 1");
    $data_upline = mysqli_fetch_assoc($q_upline);

    $nama_upline = $data_upline ? $data_upline['username'] : $upline;
    // Ambil semua downline
    $downline_query = mysqli_query($koneksi, "
        SELECT id, username 
        FROM tb_user
        WHERE referral = '$upline'
    ");

    ?>

    <div class="container-xxl flex-grow-1 container-p-y">
        <div class="row gy-4 mb-4">
            <div class="col-md-6">
                <div class="fw-bold fs-4 text-center text-md-start">
                    Downline dari <span class="text-primary"><?php echo $nama_upline; ?></span>
                </div>
            </div>
        </div>
        <div class="card table-responsive p-3">
            <table class="table" id="example">
                <thead>
                    <tr>
                        <th scope="col">#</th>
                        <th scope="col">Nama Pengguna</th>
                        <th scope="col">Tgl Daftar</th>
                        <th scope="col">Deposit Pertama</th>
                        <th scope="col">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if (mysqli_num_rows($downline_query) > 0) {
                        $nomor = 1;
                        while ($data = mysqli_fetch_array($downline_query)) {
                            $id_anggota = $data['id'];
                            $nama_pengguna = $data['username'];

                            // Hitung total deposit downline ini
                            $deposit_query = mysqli_query($koneksi, "
                                SELECT SUM(jumlah) AS total_deposit
                                FROM tb_deposit
                                WHERE username = '$nama_pengguna'
                                AND status = 'Sukses'
                            ");
                            $deposit_data = mysqli_fetch_array($deposit_query);
                            $total_deposit = $deposit_data['total_deposit'] ? $deposit_data['total_deposit'] : 0;

                            // Turnover (10% dari deposit)
                            $total_turnover = $total_deposit * 0.10;

                            // Total referral si downline ini
                            $referral_query = mysqli_query($koneksi, "
                                SELECT COUNT(*) AS total_referral
                                FROM tb_user
                                WHERE referral = '$nama_pengguna'
                            ");
                            $referral_data = mysqli_fetch_array($referral_query);
                            $total_referral = $referral_data['total_referral'];

                            $depo_pertama_query = mysqli_query($koneksi, "
                                SELECT * FROM tb_deposit
                                WHERE username = '$nama_pengguna'
                                ORDER BY id ASC
                                LIMIT 1
                            ");

                            $depo_pertama_data = mysqli_fetch_array($depo_pertama_query);

                            if ($depo_pertama_data && isset($depo_pertama_data['jumlah'])) {
                                $depo_pertama = $depo_pertama_data['jumlah'];
                            } else {
                                $depo_pertama = 0;
                            }

                            $tgl_q = mysqli_query($koneksi, "
                                SELECT * from tb_user
                                WHERE username = '$nama_pengguna' limit 1
                            ");
                            $tg_q_data = mysqli_fetch_array($tgl_q);
                            $tgl = date("d-m-Y H:i", strtotime($tg_q_data['created_at']));

                            $claimed = $tg_q_data['claimed'];
                    ?>
                    <tr>
                        <th scope="row"><?php echo $nomor++; ?></th>
                        <td><?php echo $nama_pengguna; ?></td>
                        <td><?php echo $tgl; ?></td>
                        <td><?php echo number_format($depo_pertama, 2, ',', '.'); ?></td>
                        <td class="text-center">
                            <?php if($claimed == 1) { ?>
                            <span class="btn btn-sm btn-success waves-effect waves-light">
                                Claim
                            </span>
                            <?php } else { ?>
                            <button class="btn btn-sm btn-warning waves-effect waves-light btn-claim"
                                data-id="<?php echo $id_anggota; ?>">
                                Belum Claim
                            </button>
                            <?php } ?>
                        </td>
                    </tr>
                    <?php
                       }
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
    <script>
document.addEventListener("DOMContentLoaded", function() {
    const claimButtons = document.querySelectorAll(".btn-claim");

    claimButtons.forEach(btn => {
        btn.addEventListener("click", function() {
            const id = this.getAttribute("data-id");
            const button = this;

            if (!confirm("Yakin mau claim?")) return;

            button.disabled = true;
            button.innerText = "Memproses...";

            fetch(`update_claim.php?id=${id}`)
                .then(res => res.json())
                .then(data => {
                    if (data.status === "success") {
                        button.classList.remove("btn-warning");
                        button.classList.add("btn-success");
                        button.innerText = "Claim";
                        button.disabled = true;
                    } else {
                        alert("Gagal claim: " + data.message);
                        button.disabled = false;
                        button.innerText = "Belum Claim";
                    }
                })
                .catch(err => {
                    alert("Terjadi kesalahan koneksi.");
                    button.disabled = false;
                    button.innerText = "Belum Claim";
                });
        });
    });
});
    </script>

    <script>
$(document).ready(function () {
    $('#example').DataTable({
        "pageLength": 25,
        "autoWidth": false,
        "ordering": true
    });
});
</script>

<script>
$(document).ready(function(){
    var table = $('#example').DataTable();
    $('#searchTable').on('keyup', function(){
        table.search(this.value).draw();
    });
});
</script>
