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

// Pastikan parameter upline ada
$upline = isset($_GET['halaman_item']) ? $_GET['halaman_item'] : null;
if(is_null($upline)) {
    echo '<script>alert("User referral tidak ditemukan!"); window.location.replace("referral.php");</script>';
    exit;
}

$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, created_at, claimed 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 htmlspecialchars($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 htmlspecialchars($nama_pengguna); ?></td>
                    <td><?php echo $tgl; ?></td>
                    <td>Rp <?php echo number_format($depo_pertama, 0, ',', '.'); ?></td>
                    <td class="text-center">
                        <?php if($claimed == 1) { ?>
                            <span class="badge bg-success">Dicairkan</span>
                        <?php } else { ?>
                            <button class="btn btn-sm btn-warning btn-claim" data-id="<?php echo $id_anggota; ?>">
                                Belum Claim
                            </button>
                        <?php } ?>
                    </td>
                </tr>
                <?php
                    }
                }
                ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    document.querySelectorAll(".btn-claim").forEach(btn => {
        btn.addEventListener("click", function() {
            const id = this.getAttribute("data-id");
            const button = this;

            if (!confirm("Yakin ingin mencairkan bonus untuk downline ini?")) return;

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

            fetch(`update_claim.php?id=${id}`)
                .then(res => res.json())
                .then(data => {
                    if (data.status === "success") {
                        button.parentElement.innerHTML = '<span class="badge bg-success">Dicairkan</span>';
                    } 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";
                });
        });
    });

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