<?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">Tgl Depo Terakhir</th>
                    <th scope="col">Depo Pertama</th>
                    <th scope="col">Riwayat Depo</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'];

                    // 1. Ambil Depo Pertama
                    $depo_pertama_query = mysqli_query($koneksi, "SELECT jumlah FROM tb_deposit WHERE username = '$nama_pengguna' ORDER BY id ASC LIMIT 1");
                    $depo_pertama_data = mysqli_fetch_array($depo_pertama_query);
                    $depo_pertama = $depo_pertama_data ? $depo_pertama_data['jumlah'] : 0;

                    // 2. Ambil Tgl Depo Terakhir menggunakan created_at
                    $tgl_depo_query = mysqli_query($koneksi, "
                        SELECT MAX(created_at) as tgl_terakhir 
                        FROM tb_deposit 
                        WHERE username = '$nama_pengguna' 
                        AND status = 'Sukses'
                    ");
                    $tgl_depo_data = mysqli_fetch_array($tgl_depo_query);
                    $tgl_depo_terakhir = $tgl_depo_data['tgl_terakhir'] ? date("d-m-Y H:i", strtotime($tgl_depo_data['tgl_terakhir'])) : '-';

                    $tgl_daftar = date("d-m-Y H:i", strtotime($data['created_at']));
                    $claimed = $data['claimed']; 
                    
            ?>
                <tr>
                    <th scope="row"><?php echo $nomor++; ?></th>
                    <td><?php echo htmlspecialchars($nama_pengguna); ?></td>
                    <td><?php echo $tgl_daftar; ?></td>
                    <td><?php echo $tgl_depo_terakhir; ?></td>
                    <td>Rp <?php echo number_format($depo_pertama, 0, ',', '.'); ?></td>
                    <td>
                        <button type="button" class="btn btn-sm btn-info" onclick="bukaRiwayat('<?php echo $nama_pengguna; ?>')">
                            Lihat Semua
                        </button>
                    </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>

<!-- Modal Riwayat Deposit -->
<div class="modal fade" id="modalRiwayat" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Detail Riwayat Deposit</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body" id="isiModal">
        Memuat data...
      </div>
    </div>
  </div>
</div>

<script>
function bukaRiwayat(username) {
    $('#isiModal').load('ajax_riwayat.php?user=' + encodeURIComponent(username));
    $('#modalRiwayat').modal('show');
}

document.addEventListener("DOMContentLoaded", function() {
    // Handler Claim Bonus
    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>