<?php
// promotorBK/ajax/get_referrals.php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['promotor_authenticated']) || $_SESSION['promotor_authenticated'] !== true) {
    echo json_encode(['status' => 'error', 'html' => '<div class="alert alert-danger">Sesi tidak valid.</div>']);
    exit;
}

$userLevel = (isset($_SESSION['user_level']) ? $_SESSION['user_level'] : 'viewer');
$is_admin_access = ($userLevel === 'admin');

include '../../config/koneksi.php'; 

// Fungsi NDP dan Payout
function get_ndp_data_simple($conn, $user_cuid) {
    $stmt = $conn->prepare("
        SELECT total, bk_pay 
        FROM tb_transaksi 
        WHERE userID = ? AND jenis = '1' AND status = '1'
        ORDER BY date ASC 
        LIMIT 1
    ");
    $stmt->bind_param("i", $user_cuid);
    $stmt->execute();
    $data = $stmt->get_result()->fetch_assoc();
    $stmt->close();
    
    if ($data) {
        $nominal = 'Rp ' . number_format($data['total'], 0, ',', '.');
        $payout_status = (int)$data['bk_pay'];
        
        $payout_text = $payout_status === 1 ? 'Selesai' : 'Onprogress';
        $payout_color = $payout_status === 1 ? 'primary' : 'secondary';
        
        return [
            'ndp' => '<span class="badge text-bg-success">' . $nominal . '</span>',
            'payout' => '<span class="badge text-bg-' . $payout_color . '">' . $payout_text . '</span>'
        ];
    } else {
        return [
            'ndp' => '<span class="badge text-bg-warning">Belum NDP</span>',
            'payout' => '<span class="badge text-bg-light text-dark">N/A</span>'
        ];
    }
}

// Fungsi BARU: Cek dan tampilkan label NEW (tetap sama)
function check_new_member($join_date) {
    $cutoff_timestamp = time() - (48 * 3600); 
    $join_timestamp = strtotime($join_date);
    
    if ($join_timestamp > $cutoff_timestamp) {
        return ' <span class="badge text-bg-warning ms-1">NEW</span>';
    }
    return '';
}


$response = [
    'status' => 'error',
    'message' => 'Invalid request.',
    'html' => '',
    'promotor' => null
];

if (isset($_POST['promotor_id']) && is_numeric($_POST['promotor_id'])) {
    $promotor_id = (int)$_POST['promotor_id'];

    // 1. Ambil detail Promotor (tb_user)
    $stmt_promotor = $conn->prepare("SELECT username, full_name, referral_count FROM tb_user WHERE cuid = ?");
    $stmt_promotor->bind_param("i", $promotor_id);
    $stmt_promotor->execute();
    $result_promotor = $stmt_promotor->get_result();
    $promotor = $result_promotor->fetch_assoc();
    $stmt_promotor->close();

    if ($promotor) {
        // 2. Ambil detail Bank Promotor (tb_bank) - Hanya jika Admin
        $bank_data = null;
        if ($is_admin_access) {
            $stmt_bank = $conn->prepare("
                SELECT pemilik, akun, no_rek 
                FROM tb_bank 
                WHERE userID = ? AND status = 1 
                ORDER BY cuid DESC 
                LIMIT 1
            ");
            $stmt_bank->bind_param("i", $promotor_id);
            $stmt_bank->execute();
            $result_bank = $stmt_bank->get_result();
            $bank_data = $result_bank->fetch_assoc();
            $stmt_bank->close();
        }
        
        $nama_rek = $bank_data ? htmlspecialchars($bank_data['pemilik']) : '<span class="text-danger">Data Bank Tidak Ditemukan/Aktif</span>';
        $jenis_rek = $bank_data ? htmlspecialchars($bank_data['akun']) : '-';
        $no_rek = $bank_data ? htmlspecialchars($bank_data['no_rek']) : '-';
        
        // 3. Tampilkan Detail Promotor dan Bank
        $html = '<div class="row mb-4 border-bottom border-primary pb-3">';
        $html .= '<div class="col-12 col-md-'. ($is_admin_access ? '6' : '12') .'">';
        $html .= '<h5 class="text-light">User Rujukan: ' . htmlspecialchars($promotor['full_name']) . ' (' . htmlspecialchars($promotor['username']) . ')</h5>';
        $html .= '</div>';
        
        // Tampilkan Detail Bank HANYA UNTUK ADMIN
        if ($is_admin_access) {
            $html .= '<div class="col-12 col-md-6 small text-md-end">';
            $html .= '<p class="mb-0 text-info">Nama Rekening Rujukan: <span class="fw-bold">' . $nama_rek . '</span></p>';
            $html .= '<p class="mb-0 text-info">Jenis Rekening: <span class="fw-bold">' . $jenis_rek . '</span></p>';
            $html .= '<p class="mb-0 text-info">Nomor Rekening Rujukan: <span class="fw-bold">' . $no_rek . '</span></p>';
            $html .= '</div>';
        }

        $html .= '</div>';


        // 4. Ambil SEMUA user yang dirujuk
        $stmt_referrals = $conn->prepare("
            SELECT u.cuid, u.username, u.join_date
            FROM tb_user u
            WHERE u.referral_user_id = ? 
            ORDER BY u.join_date DESC
        ");
        $stmt_referrals->bind_param("i", $promotor_id);
        $stmt_referrals->execute();
        $result_referrals = $stmt_referrals->get_result();
        $total_referrals = mysqli_num_rows($result_referrals);
        
        $html .= '<div class="alert alert-info text-center small py-2">Total ' . $total_referrals . ' user rujukan.</div>';
        
        if ($total_referrals > 0) {
            $html .= '<div class="table-responsive">';
            // Tambahkan ID untuk Datatables
            $html .= '<table id="referralTable" class="table table-dark table-striped table-hover table-bordered text-white align-middle small w-100">';
            $html .= '<thead class="table-primary">';
            
            // Kolom History selalu ada (sesuai permintaan terakhir)
            $header_history = '<th>History</th>';
            $header_delete = $is_admin_access ? '<th>Hapus Rujukan</th>' : '';
            $header_detail = $is_admin_access ? '<th>Detail</th>' : '';
            
            $html .= '<tr><th>No</th><th>Username</th><th>Tanggal Gabung</th><th>Nominal NDP</th><th>Status Payout</th>' . $header_history . $header_delete . $header_detail . '</tr>';
            $html .= '</thead><tbody>';
            
            $no = 1; 
            while($row = mysqli_fetch_assoc($result_referrals)) {
                $user_cuid = $row['cuid'];
                $ndp_payout_data = get_ndp_data_simple($conn, $user_cuid);
                
                $join_date_formatted = date('d/m/Y H:i', strtotime($row['join_date']));
                $new_label = check_new_member($row['join_date']);
                
                $html .= '<tr id="member-row-' . $user_cuid . '">';
                $html .= '<td>' . $no++ . '</td>';
                $html .= '<td>' . htmlspecialchars($row['username']) . $new_label . '</td>';
                $html .= '<td>' . $join_date_formatted . '</td>';
                $html .= '<td>' . $ndp_payout_data['ndp'] . '</td>';
                $html .= '<td>' . $ndp_payout_data['payout'] . '</td>';
                
                // Kolom History (SELALU ADA)
                $html .= '<td>';
                $html .= '<button type="button" class="btn btn-sm btn-success view-history" data-user-id="' . $user_cuid . '" data-bs-toggle="modal" data-bs-target="#transactionModal" style="font-size: 0.7rem;">History</button>';
                $html .= '</td>';
                
                // Kolom Hapus Rujukan HANYA UNTUK ADMIN
                if ($is_admin_access) {
                    $html .= '<td>';
                    $html .= '<button type="button" class="btn btn-sm btn-danger delete-referral-btn" data-member-cuid="' . $user_cuid . '" data-promotor-cuid="' . $promotor_id . '" data-username="' . htmlspecialchars($row['username']) . '" style="font-size: 0.7rem;">Hapus</button>';
                    $html .= '</td>';
                }
                
                // Kolom Detail HANYA UNTUK ADMIN
                if ($is_admin_access) {
                    $html .= '<td>';
                    $html .= '<button type="button" class="btn btn-sm btn-action view-member-detail" data-user-id="' . $user_cuid . '" data-bs-toggle="modal" data-bs-target="#memberDetailModal">Detail</button>';
                    $html .= '</td>';
                }
                $html .= '</tr>';
            }
            
            $html .= '</tbody></table></div>';
        } else {
            $html .= '<div class="alert alert-warning text-center">User rujukan tidak ditemukan.</div>';
        }

        $stmt_referrals->close();
        
        $response['status'] = 'success';
        $response['html'] = $html;
        $response['promotor'] = [
            'username' => htmlspecialchars($promotor['username']),
            'full_name' => htmlspecialchars($promotor['full_name'])
        ];

    } else {
        $response['message'] = 'Promotor tidak ditemukan.';
    }
}

mysqli_close($conn);
echo json_encode($response);