<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include '../db/koneksi.php';
session_start();
$username = $_SESSION['username'] ?? '';

if (!$username) {
    echo "<tr><td colspan='4' style='text-align:center;color:red;'>Silakan login terlebih dahulu</td></tr>";
    exit;
}

$from_date = $_GET['from_date'] ?? date('Y-m-d');
$end_date  = $_GET['end_date'] ?? date('Y-m-d');

$user_q = mysqli_query($koneksi, "SELECT referral FROM tb_user WHERE username = '$username'");
$user_d = mysqli_fetch_assoc($user_q);
$kode_referral = $user_d['referral'] ?? '';

$q = mysqli_query($koneksi, "
    SELECT username, created_at 
    FROM tb_user
    WHERE referral = '$username'
    AND DATE(created_at) BETWEEN '$from_date' AND '$end_date'
    ORDER BY id desc
");

if (mysqli_num_rows($q) == 0) {
    echo "<tr style='background-color:var(--secondary-color);color:#fff;'>
            <td colspan='4' style='padding:24px;text-align:center;color:#C4C4C4;'>
                Tidak ada data referral ditemukan
            </td>
          </tr>";
    exit;
}

while ($r = mysqli_fetch_assoc($q)) {
    $uname = $r['username'];

    $bet_q = mysqli_query($koneksi, "SELECT SUM(jumlah) AS total FROM tb_deposit WHERE username = '$uname' and status = 'Sukses'");
    $bet_d = mysqli_fetch_assoc($bet_q);
    $to_bet = $bet_d['total'] ?? 0;

    $bayar_q = mysqli_query($koneksi, "SELECT SUM(jumlah) AS total FROM tb_withdraw WHERE username = '$uname' and status = 'Sukses'");
    $bayar_d = mysqli_fetch_assoc($bayar_q);
    $to_bayar = $bayar_d['total'] ?? 0;

    echo "
    <tr style='background-color:var(--secondary-color);color:#fff;'>
        <td style='padding:10px 5px;'>$uname</td>
        <td style='padding:10px 5px;'>Rp " . number_format($to_bet, 0, ',', '.') . "</td>
        <td style='padding:10px 5px;'>Rp " . number_format($to_bayar, 0, ',', '.') . "</td>
        <td style='padding:10px 5px;'>" . date('Y-m-d', strtotime($r['created_at'])) . "</td>
    </tr>";
}
?>