<?php
session_start();
include '../config/koneksi.php'; 

$is_authenticated = isset($_SESSION['promotor_authenticated']) && $_SESSION['promotor_authenticated'] === true;
$userLevel = isset($_SESSION['user_level']) ? $_SESSION['user_level'] : '';
$is_admin = ($userLevel === 'admin');

// NOTE: Ini hanya contoh, di produksi, user_id harus diambil dari sesi login yang sebenarnya
if (isset($_SESSION['promotor_authenticated']) && $is_admin) {
    $_SESSION['user_id'] = 4;
}

$promotors_active = null;
$members_without_upline = null;
$list_of_promotors = null;
$all_users = null;

if ($is_authenticated) {
    // Menambahkan kolom join_date untuk pengecekan NEW
    $query_active = "SELECT cuid, username, full_name, referral_code, referral_count, referral_user_id, join_date FROM tb_user WHERE referral_count > 0 ORDER BY cuid DESC";
    $promotors_active = mysqli_query($conn, $query_active);

    if ($is_admin) {
        $query_promotor_list = "SELECT cuid, username, full_name FROM tb_user WHERE referral_code IS NOT NULL AND referral_code != '' AND cuid != 0 ORDER BY full_name ASC";
        $list_of_promotors = mysqli_query($conn, $query_promotor_list);

        $query_no_upline = "SELECT cuid, username, full_name, referral_code FROM tb_user WHERE referral_user_id IS NULL OR referral_user_id = 0 ORDER BY cuid ASC";
        $members_without_upline = mysqli_query($conn, $query_no_upline);
        
        $query_all_users = "SELECT cuid, username, full_name, referral_count, join_date FROM tb_user ORDER BY cuid DESC";
        $all_users = mysqli_query($conn, $query_all_users);
    }
}

// Fungsi untuk menandai Upline/Promotor yang baru
function check_new_upline($join_date) {
    $cutoff_timestamp = time() - (7 * 24 * 3600); // Batasan 7 hari
    $join_timestamp = strtotime($join_date);
    
    if ($join_timestamp > $cutoff_timestamp) {
        return ' <span class="badge text-bg-warning ms-1">NEW</span>';
    }
    return '';
}

?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BK Promotor</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs5/dt-1.11.5/datatables.min.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-theme/0.1.0-beta.10/select2-bootstrap.min.css" rel="stylesheet" />
    
    <style>
        body {
            background-color: #0a0a0a;
            color: #E0E0E0; 
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            min-height: 100vh;
        }
        .navbar {
            background-color: #1a237e !important;
            border-bottom: 3px solid #00b0ff;
        }
        #main-content {
            display: <?php echo $is_authenticated ? 'block' : 'none'; ?>;
        }
        .card-promotor {
            background-color: #1f1f1f; 
            border: 1px solid #1a237e;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.5);
        }
        .modal-backdrop.show {
            backdrop-filter: blur(5px);
            -webkit-backdrop-filter: blur(5px);
            opacity: 0.8 !important;
            background-color: #0a0a0a !important;
        }
        .table {
            --bs-table-bg: #1f1f1f; 
            --bs-table-color: #E0E0E0; 
            border: 1px solid #1a237e;
            --bs-table-padding: 0.45rem;
        }
        .table-sm {
             --bs-table-padding: 0.45rem;
        }
        .table-primary {
            --bs-table-bg: #1a237e;
            --bs-table-color: #ffffff;
            font-weight: bold;
        }
        .table-info {
            --bs-table-bg: #00b0ff;
            --bs-table-color: #000000;
            font-weight: bold;
        }
        .btn-action {
            background-color: #00b0ff;
            border-color: #00b0ff;
            color: black;
            font-weight: 600;
            transition: all 0.3s;
        }
        .btn-action:hover {
            background-color: #0087c5;
            border-color: #0087c5;
            color: white;
        }
        .modal-content {
            background-color: #1f1f1f;
            color: #E0E0E0;
            border: 2px solid #1a237e;
        }
        .modal-header {
            border-bottom: 1px solid #1a237e;
        }
        .btn-xs {
            padding: 0.1rem 0.4rem;
        }
        .upline-link {
            cursor: pointer;
            color: #ffc107;
            font-weight: bold;
            text-decoration: none;
        }
        .upline-link:hover {
            text-decoration: underline;
        }
        
        /* PENYESUAIAN UKURAN FONT DATATABLES */
        #main-content .table,
        .dataTables_wrapper .table {
            font-size: 0.9rem;
        }
        .dataTables_wrapper .dataTables_filter input,
        .dataTables_wrapper .dataTables_length select,
        .dataTables_wrapper .dataTables_paginate .paginate_button {
            font-size: 0.9rem;
            padding: 0.2rem 0.4rem;
        }
        table.dataTable thead th {
            white-space: nowrap;
            padding-right: 20px !important;
        }

        .select2-container--bootstrap .select2-selection {
            background-color: #1f1f1f !important;
            color: #E0E0E0 !important;
            border-color: #1a237e !important;
            box-shadow: none !important;
        }
        .select2-container--bootstrap .select2-dropdown {
            background-color: #1f1f1f !important;
            border-color: #1a237e !important; 
        }
        .select2-container--bootstrap .select2-results__option {
            color: #E0E0E0;
        }
        .select2-container--bootstrap .select2-results__option--highlighted[aria-selected] {
            background-color: #1565c0 !important;
            color: white !important;
        }
        .select2-container--bootstrap .select2-selection--multiple .select2-selection__choice {
            background-color: #0d47a1 !important;
            color: white !important;
            border-color: #0d47a1 !important;
        }
    </style>
</head>
<body>
    
    <nav class="navbar navbar-expand-lg navbar-dark shadow-lg">
        <div class="container">
            <a class="navbar-brand" href="index.php">
                <span style="color: #00b0ff;">BK</span> PROMOTOR
            </a>
            
            <?php if ($is_authenticated): ?>
                <div class="d-flex">
                    <a href="logout.php" class="btn btn-sm btn-outline-light">
                        <i class="fas fa-sign-out-alt me-1"></i> Logout (<?php echo ucfirst($userLevel); ?>)
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </nav>

    <div id="main-content" class="container my-5">
        
        <div class="card card-promotor p-3 p-md-4 mb-4">
            <h4 class="mb-4 border-bottom border-primary pb-2 text-light">Daftar Promotor</h4>
            
            <?php if ($promotors_active && mysqli_num_rows($promotors_active) > 0): ?>
                <div class="table-responsive">
                    <table id="mainTablePromotor" class="table table-sm table-dark table-striped table-hover align-middle small w-100">
                        <thead class="table-primary">
                            <tr>
                                <th scope="col">CUID</th>
                                <th scope="col">Username</th>
                                <th scope="col">Nama Lengkap</th>
                                <th scope="col">Kode Refferal</th>
                                <th scope="col">Rujukan</th>
                                <th scope="col">Upline</th>
                                <th scope="col">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($row = mysqli_fetch_assoc($promotors_active)): ?>
                                <?php 
                                    $upline_cuid = (int)$row['referral_user_id'];
                                    $new_label = check_new_upline($row['join_date']);
                                ?>
                                <tr data-cuid="<?php echo $row['cuid']; ?>">
                                    <td><?php echo $row['cuid']; ?></td>
                                    <td>
                                        <span class="fw-bold text-info"><?php echo htmlspecialchars($row['username']); ?></span>
                                        <?php echo $new_label; ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                    <td><span class="badge text-bg-success"><?php echo htmlspecialchars($row['referral_code']); ?></span></td>
                                    <td><span class="badge bg-primary"><?php echo $row['referral_count']; ?></span></td>
                                    <td>
                                        <?php if ($upline_cuid > 0): ?>
                                            <span class="upline-link" data-upline-id="<?php echo $upline_cuid; ?>">
                                                ID: <?php echo $upline_cuid; ?>
                                            </span>
                                        <?php else: ?>
                                            <span class="badge text-bg-secondary">N/A</span>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button 
                                            type="button" 
                                            class="btn btn-sm btn-action view-referrals" 
                                            data-cuid="<?php echo $row['cuid']; ?>"
                                            data-bs-toggle="modal" 
                                            data-bs-target="#referralModal"
                                        >
                                            Rujukan
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php elseif ($is_authenticated): ?>
                <div class="alert alert-info text-center">Tidak ada promotor aktif yang ditemukan.</div>
            <?php endif; ?>
        </div>

        <?php if ($is_admin): ?>
        
        <div class="card card-promotor p-3 p-md-4 mb-4">
            <h4 class="mb-4 border-bottom border-info pb-2 text-info">Daftar Semua Member</h4>
            
            <?php if ($all_users && mysqli_num_rows($all_users) > 0): ?>
                <div class="table-responsive">
                    <table id="mainTableAllUsers" class="table table-sm table-dark table-striped table-hover align-middle small w-100">
                        <thead class="table-info text-dark">
                            <tr>
                                <th scope="col">ID</th>
                                <th scope="col">Username</th>
                                <th scope="col">Nama Lengkap</th>
                                <th scope="col">Jml Rujukan</th>
                                <th scope="col">Detail</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($row = mysqli_fetch_assoc($all_users)): ?>
                                <tr>
                                    <td><?php echo $row['cuid']; ?></td>
                                    <td><span class="fw-bold text-light"><?php echo htmlspecialchars($row['username']); ?></span></td>
                                    <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                    <td><span class="badge bg-primary"><?php echo $row['referral_count']; ?></span></td>
                                    <td>
                                        <button 
                                            type="button" 
                                            class="btn btn-xs btn-action view-member-detail" 
                                            data-user-id="<?php echo $row['cuid']; ?>" 
                                            data-bs-toggle="modal" 
                                            data-bs-target="#memberDetailModal"
                                            style="font-size: 0.7rem;"
                                        >
                                            Detail
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-warning text-center">Tidak ada user ditemukan.</div>
            <?php endif; ?>
        </div>
        
        <div class="card card-promotor p-3 p-md-4 mb-4">
            <h4 class="mb-4 border-bottom border-warning pb-2 text-warning">Member Tanpa Referral</h4>
            
            <?php if ($members_without_upline && mysqli_num_rows($members_without_upline) > 0): ?>
                <div class="table-responsive">
                    <table id="mainTableNoUpline" class="table table-sm table-dark table-striped table-hover align-middle small w-100">
                        <thead class="table-warning text-dark">
                            <tr>
                                <th scope="col">CUID</th>
                                <th scope="col">Username</th>
                                <th scope="col">Nama Lengkap</th>
                                <th scope="col">Kode Refferal</th>
                                <th scope="col">Tautkan ke Promotor</th>
                                <th scope="col">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            if ($list_of_promotors) mysqli_data_seek($list_of_promotors, 0); 
                            while($row = mysqli_fetch_assoc($members_without_upline)): ?>
                                <tr>
                                    <td><?php echo $row['cuid']; ?></td>
                                    <td><span class="fw-bold text-info"><?php echo htmlspecialchars($row['username']); ?></span></td>
                                    <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                    <td><?php echo htmlspecialchars($row['referral_code']); ?></td>
                                    <td>
                                        <select class="form-select form-select-sm promotor-dropdown select2-promotor" data-member-cuid="<?php echo $row['cuid']; ?>">
                                            <option value="">-- Pilih Promotor --</option>
                                            <?php 
                                            if ($list_of_promotors) mysqli_data_seek($list_of_promotors, 0); 
                                            while($promotor = mysqli_fetch_assoc($list_of_promotors)): ?>
                                                <option value="<?php echo $promotor['cuid']; ?>">
                                                    <?php echo htmlspecialchars($promotor['username']) . ' (' . htmlspecialchars($promotor['full_name']) . ')'; ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </td>
                                    <td>
                                        <button 
                                            type="button" 
                                            class="btn btn-sm btn-danger link-member-btn"
                                            data-member-username="<?php echo $row['username']; ?>"
                                        >
                                            Tautkan
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-success text-center">Semua member sudah memiliki upline.</div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

    </div>
    
    <div class="modal fade" id="authModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="authModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-sm modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="authModalLabel">Akses Terbatas</h5>
                </div>
                <div class="modal-body">
                    <p class="text-warning small">Masukkan password untuk melanjutkan.</p>
                    <div id="auth-message" class="alert d-none small" role="alert"></div>
                    <form id="authForm">
                        <div class="mb-3">
                            <label for="authPassword" class="form-label small">Password</label>
                            <input type="password" class="form-control" id="authPassword" required>
                        </div>
                        <button type="submit" class="btn btn-action w-100">Masuk</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="referralModal" tabindex="-1" aria-labelledby="referralModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="referralModalLabel">Detail User Rujukan</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="referral-content" class="text-center">
                        <div class="spinner-border text-primary" role="status"></div>
                        <p class="mt-2 text-secondary">Memuat data rujukan...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="memberDetailModal" tabindex="-1" aria-labelledby="memberDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="memberDetailModalLabel">Detail Member dan Aksi Payout</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="member-detail-content" class="text-center">
                        <div class="spinner-border text-primary" role="status"></div>
                        <p class="mt-2 text-secondary">Memuat detail member...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-sm btn-info view-all-transactions-from-detail" style="display:none;">Lihat Semua Transaksi</button> 
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>
    
    <div class="modal fade" id="transactionModal" tabindex="-1" aria-labelledby="transactionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="transactionModalLabel">Detail Transaksi User</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="transaction-content" class="text-center">
                        <div class="spinner-border text-info" role="status"></div>
                        <p class="mt-2 text-secondary">Memuat data transaksi...</p>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                </div>
            </div>
        </div>
    </div>
    
    <script type="text/javascript" src="https://cdn.datatables.net/v/bs5/dt-1.11.5/datatables.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script>
        function getPayoutText(code) {
            return code == 1 ? 'Selesai' : 'Onprogress';
        }
        function getPayoutColor(code) {
            return code == 1 ? 'primary' : 'secondary';
        }
        function getPayoutActionText(code) {
            return code == 1 ? 'Set Onprogress' : 'Set Selesai';
        }
        function getPayoutActionButtonClass(code) {
            // return code == 1 ? 'btn-danger' : 'btn-success'; // DIBALIK UNTUK AKSI
            return code == 1 ? 'btn-success' : 'btn-secondary'; // DIBALIK UNTUK AKSI
        }

        $(document).ready(function() {
            
            var isAuthenticated = <?php echo isset($_SESSION['promotor_authenticated']) && $_SESSION['promotor_authenticated'] ? 'true' : 'false'; ?>;
            var userLevel = '<?php echo isset($_SESSION['user_level']) ? $_SESSION['user_level'] : ''; ?>';
            var authModal = new bootstrap.Modal(document.getElementById('authModal'));
            
            if (!isAuthenticated) {
                authModal.show();
            }

            var referralModal = new bootstrap.Modal(document.getElementById('referralModal'));
            var transactionModal = new bootstrap.Modal(document.getElementById('transactionModal'));
            var memberDetailModal = new bootstrap.Modal(document.getElementById('memberDetailModal'));

            // INISIALISASI DATATABLES DENGAN PAGINATION BARU
            var dataTableOptions = {
                "language": {
                    "url": "//cdn.datatables.net/plug-ins/1.11.5/i18n/id.json"
                },
                "responsive": true,
                "order": [[ 0, "desc" ]],
                // Pagination baru (10, 25, 50, 100)
                "lengthMenu": [ [10, 25, 50, 100, -1], [10, 25, 50, 100, "Semua"] ],
                "pageLength": 10
            };

            if (isAuthenticated) {
                // Tabel Promotor Aktif
                $('#mainTablePromotor').DataTable($.extend(true, {}, dataTableOptions, {
                    "columnDefs": [
                         { "orderable": false, "targets": [6] }
                    ]
                }));
                
                // Tabel Semua User (Admin)
                if (userLevel === 'admin' && $('#mainTableAllUsers').length) {
                    $('#mainTableAllUsers').DataTable($.extend(true, {}, dataTableOptions, {
                        "columnDefs": [
                            { "orderable": false, "targets": [4] }
                        ]
                    }));
                }
                
                // Tabel Tanpa Upline (Admin)
                if (userLevel === 'admin' && $('#mainTableNoUpline').length) {
                    $('#mainTableNoUpline').DataTable($.extend(true, {}, dataTableOptions, {
                        "columnDefs": [
                            { "orderable": false, "targets": [4, 5] }
                        ]
                    }));
                }
            }

            // LOGIN
            $('#authForm').on('submit', function(e) {
                e.preventDefault();
                var password = $('#authPassword').val();
                var authMessage = $('#auth-message');
                var authButton = $('#authForm button[type="submit"]');

                authMessage.addClass('d-none').removeClass('alert-success alert-danger');
                authButton.prop('disabled', true).text('Memverifikasi...');

                $.ajax({
                    url: 'ajax/check_password.php',
                    type: 'POST',
                    data: { password: password },
                    dataType: 'json',
                    success: function(response) {
                        authButton.prop('disabled', false).text('Masuk');
                        authMessage.removeClass('d-none').text(response.message);
                        
                        if (response.status === 'success') {
                            authMessage.addClass('alert-success');
                            userLevel = response.level; 
                            
                            setTimeout(function() {
                                window.location.reload(); 
                            }, 500);
                        } else {
                            authMessage.addClass('alert-danger');
                        }
                    },
                    error: function() {
                        authButton.prop('disabled', false).text('Masuk');
                        authMessage.removeClass('d-none').addClass('alert-danger').text('Terjadi kesalahan koneksi.');
                    }
                });
            });
            
            // SELECT2 INIT
            $('.select2-promotor').select2({
                theme: "bootstrap",
                width: '100%',
                placeholder: "-- Cari & Pilih Promotor --",
                allowClear: true
            });

            if (isAuthenticated) {
                
                // LINK MEMBER
                $(document).on('click', '.link-member-btn', function() {
                    if (userLevel !== 'admin') {
                        alert('Akses Ditolak: Hanya Admin yang dapat menautkan referral.');
                        return;
                    }
                    
                    var button = $(this);
                    var row = button.closest('tr');                
                    var memberCuid = row.find('.promotor-dropdown').data('member-cuid'); 
                    var promotorCuid = row.find('.promotor-dropdown').val();
                    var memberUsername = button.data('member-username'); 

                    if (!promotorCuid || promotorCuid === "") {
                        alert('Pilih Promotor Tujuan dari dropdown.');
                        return;
                    }
                    
                    if (!confirm(`Yakin menautkan member ${memberUsername} (CUID: ${memberCuid}) ke Promotor ID ${promotorCuid}?`)) {
                        return;
                    }
                    
                    button.prop('disabled', true).text('Tautkan...');

                    $.ajax({
                        url: 'ajax/update_referral_link.php',
                        type: 'POST',
                        data: { member_cuid: memberCuid, promotor_cuid: promotorCuid },
                        dataType: 'json',
                        success: function(response) {
                            alert(response.message);
                            if (response.status === 'success') {
                                var table = $('#mainTableNoUpline').DataTable();
                                table.row(row).remove().draw();
                                window.location.reload(); 
                            } else {
                                 button.prop('disabled', false).text('Tautkan');
                            }
                        },
                        error: function() {
                            alert('Error koneksi saat linking atau server error (cek console).');
                            button.prop('disabled', false).text('Tautkan');
                        }
                    });
                });

                // MODAL 1: REFERRALS
                $(document).on('click', '.view-referrals', function() {
                    var promotorId = $(this).data('cuid');
                    var modalTitle = $('#referralModalLabel');
                    var modalBody = $('#referral-content');
                    
                    modalTitle.text('Detail User Rujukan');
                    modalBody.html('<div class="spinner-border text-primary" role="status"></div><p class="mt-2 text-secondary">Memuat data rujukan...</p>');

                    $.ajax({
                        url: 'ajax/get_referrals.php', 
                        type: 'POST',
                        data: { promotor_id: promotorId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                modalTitle.text('Detail User Rujukan');
                                modalBody.html(response.html);
                                
                                // Target columns for ordering: -1 is Detail, -2 is Delete Rujukan, -3 is History
                                var orderableTargets = userLevel === 'admin' ? [-1, -2, -3] : [-1]; 
                                
                                $('#referralTable').DataTable($.extend(true, {}, dataTableOptions, {
                                    "searching": true,
                                    "ordering": true,
                                    "order": [[ 0, "asc" ]],
                                    "columnDefs": [
                                        { "orderable": false, "targets": orderableTargets }
                                    ]
                                }));
                            } else {
                                modalBody.html('<div class="alert alert-danger">' + response.message + '</div>');
                            }
                        },
                        error: function() {
                            modalBody.html('<div class="alert alert-danger">Terjadi kesalahan koneksi saat mengambil data rujukan.</div>');
                        }
                    });
                });
                
                // FITUR KLIK UPLINE
                $(document).on('click', '.upline-link', function() {
                    var uplineId = $(this).data('upline-id');
                    
                    if ($('#mainTablePromotor').length) {
                        var table = $('#mainTablePromotor').DataTable();
                        table.search('').draw(); 
                        table.search(uplineId).draw();
                        
                        $('html, body').animate({
                            scrollTop: $("#mainTablePromotor").offset().top - 100
                        }, 500);
                    }
                });
                
                // --- LOGIKA HAPUS RUJUKAN (ADMIN ONLY) ---
                // Menggunakan event delegation pada Modal Rujukan
                $(document).on('click', '#referralModal .delete-referral-btn', function() { 
                    if (userLevel !== 'admin') {
                        alert('Akses Ditolak.');
                        return;
                    }
                    
                    var button = $(this);
                    var memberCuid = button.data('member-cuid');
                    var promotorCuid = button.data('promotor-cuid');
                    var username = button.data('username');
                    var table = $('#referralTable').DataTable();

                    if (!confirm(`Yakin menghapus tautan rujukan ${username} dari Promotor ID ${promotorCuid}? Member akan menjadi tanpa Upline.`)) {
                        return;
                    }
                    
                    button.prop('disabled', true).text('Menghapus...');

                    $.ajax({
                        url: 'ajax/delete_referral.php',
                        type: 'POST',
                        data: { member_cuid: memberCuid, promotor_cuid: promotorCuid },
                        dataType: 'json',
                        success: function(response) {
                            alert(response.message);
                            if (response.status === 'success') {
                                // Hapus baris dari Datatables Rujukan
                                table.row(button.parents('tr')).remove().draw();
                                
                                // Tutup Modal Rujukan agar halaman utama refresh dan update Referral Count
                                referralModal.hide();
                                window.location.reload(); 
                            } else {
                                 button.prop('disabled', false).text('Hapus');
                            }
                        },
                        error: function() {
                            alert('Error koneksi saat menghapus rujukan.');
                            button.prop('disabled', false).text('Hapus');
                        }
                    });
                });
                // --- AKHIR LOGIKA HAPUS RUJUKAN ---

                // MODAL 3: MEMBER DETAIL (Dipanggil dari Tabel Semua User Admin ATAU dari Modal Rujukan)
                $(document).on('click', '.view-member-detail', function(e) {
                    e.preventDefault();
                    var userId = $(this).data('user-id');
                    var modalTitle = $('#memberDetailModalLabel');
                    var modalBody = $('#member-detail-content');
                    var viewAllTransBtn = $('.view-all-transactions-from-detail');
                    
                    // Cek jika dipanggil dari Modal Rujukan, sembunyikan Modal 1
                    var isFromReferralModal = $(e.target).closest('#referralModal').length > 0;
                    if (isFromReferralModal) {
                        referralModal.hide();
                        // Tandai bahwa Modal 3 dipicu dari Modal 1
                        $('#memberDetailModal').data('is-from-referral', true);
                    } else {
                        // Dipicu dari Tabel Admin Utama
                        $('#memberDetailModal').data('is-from-referral', false);
                    }
                    
                    memberDetailModal.show();

                    modalTitle.text('Detail Member');
                    modalBody.html('<div class="spinner-border text-primary" role="status"></div><p class="mt-2 text-secondary">Memuat detail member...</p>');
                    viewAllTransBtn.hide().data('user-id', userId);

                    $.ajax({
                        url: 'ajax/get_member_detail.php', 
                        type: 'POST',
                        data: { user_id: userId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                modalTitle.text('Detail Member');
                                modalBody.html(response.html);
                                viewAllTransBtn.show(); 
                                
                                if (userLevel !== 'admin') {
                                     $('#memberDetailModal .update-payout-btn').hide();
                                }
                            } else {
                                modalBody.html('<div class="alert alert-danger">' + response.message + '</div>');
                            }
                        },
                        error: function() {
                            modalBody.html('<div class="alert alert-danger">Terjadi kesalahan koneksi saat mengambil detail member.</div>');
                        }
                    });
                });
                
                // TOMBOL LIHAT SEMUA TRANSAKSI (Modal 3 -> Modal 2)
                $(document).on('click', '.view-all-transactions-from-detail', function(e) {
                    e.preventDefault();
                    var userId = $(this).data('user-id');
                    memberDetailModal.hide();
                    openTransactionModal(userId);
                });


                // MODAL 2: SEMUA TRANSAKSI (Dipanggil dari Modal 3)
                function openTransactionModal(userId) {
                    var modalTitle = $('#transactionModalLabel');
                    var modalBody = $('#transaction-content');
                    
                    transactionModal.show();
                    modalTitle.text('Detail Transaksi User');
                    modalBody.html('<div class="spinner-border text-info" role="status"></div><p class="mt-2 text-secondary">Memuat data transaksi...</p>');

                    $.ajax({
                        url: 'ajax/get_transactions.php', 
                        type: 'POST',
                        data: { user_id: userId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                modalTitle.text('Detail Transaksi');
                                modalBody.html(response.html);
                                
                                $('#transactionTableAll').DataTable($.extend(true, {}, dataTableOptions, {
                                    "searching": true,
                                    "order": [[ 1, "desc" ]]
                                }));
                                
                                if (userLevel !== 'admin') {
                                     $('#transactionModal .update-payout-btn-all').hide();
                                }
                            } else {
                                modalBody.html('<div class="alert alert-danger">' + response.message + '</div>');
                            }
                        },
                        error: function() {
                            modalBody.html('<div class="alert alert-danger">Terjadi kesalahan koneksi saat mengambil data transaksi.</div>');
                        }
                    });
                }
                
                // MODAL 2: HISTORY TRANSAKSI (Dipanggil dari Modal 1)
                $(document).on('click', '.view-history', function(e) {
                    e.preventDefault();
                    var userId = $(this).data('user-id');
                    referralModal.hide(); // Sembunyikan Modal Rujukan
                    // Set flag agar penutupan Modal 2 tahu harus kembali ke Modal 1
                    $('.view-all-transactions-from-detail').data('user-id', null); 
                    openHistoryModal(userId);
                });

                function openHistoryModal(userId) {
                    var modalTitle = $('#transactionModalLabel');
                    var modalBody = $('#transaction-content');
                    
                    transactionModal.show();
                    modalTitle.text('History Transaksi Payout Selesai');
                    modalBody.html('<div class="spinner-border text-info" role="status"></div><p class="mt-2 text-secondary">Memuat data history...</p>');

                    $.ajax({
                        url: 'ajax/get_history.php', 
                        type: 'POST',
                        data: { user_id: userId },
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                modalTitle.text('History Transaksi Payout Selesai');
                                modalBody.html(response.html);
                                
                                $('#historyTableAll').DataTable($.extend(true, {}, dataTableOptions, {
                                    "searching": true,
                                    "order": [[ 1, "desc" ]]
                                }));
                                
                                $('#transactionModal .update-payout-btn-all').hide(); 
                            } else {
                                modalBody.html('<div class="alert alert-danger">' + response.message + '</div>');
                            }
                        },
                        error: function() {
                            modalBody.html('<div class="alert alert-danger">Terjadi kesalahan koneksi saat mengambil data history.</div>');
                        }
                    });
                }
                
                // UPDATE USER DATA FORM SUBMISSION
                $(document).on('submit', '#updateUserForm', function(e) {
                    e.preventDefault();
                    
                    var form = $(this);
                    var formData = form.serialize();
                    var button = form.find('button[type="submit"]');
                    var messageBox = $('#updateMessage');

                    messageBox.removeClass('d-none alert-success alert-danger').addClass('alert-info').text('Menyimpan data...');
                    button.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i> Menyimpan...');

                    $.ajax({
                        url: 'ajax/update_user_data.php',
                        type: 'POST',
                        data: formData,
                        dataType: 'json',
                        success: function(response) {
                            button.prop('disabled', false).html('<i class="fas fa-save me-1"></i> Simpan Perubahan User');
                            messageBox.removeClass('alert-info').addClass(response.status === 'success' ? 'alert-success' : 'alert-danger').text(response.message);
                            
                            if (response.status === 'success') {
                                setTimeout(function() {
                                    window.location.reload(); 
                                }, 1000);
                            }
                        },
                        error: function() {
                            button.prop('disabled', false).html('<i class="fas fa-save me-1"></i> Simpan Perubahan User');
                            messageBox.removeClass('alert-info').addClass('alert-danger').text('Error koneksi saat update user data.');
                        }
                    });
                });
                
                // UPDATE BK_PAY NDP (Modal 3)
                $(document).on('click', '#memberDetailModal .update-payout-btn', function() {
                    if (userLevel !== 'admin') {
                        alert('Akses Ditolak: Hanya Admin yang dapat melakukan update.');
                        return;
                    }

                    var button = $(this);
                    var transId = button.data('trans-id');
                    var newStatus = button.data('status'); 
                    var currentText = button.text();
                    var payoutCell = button.closest('td').prev('td'); 
                    
                    button.prop('disabled', true).text('Updating...');

                    $.ajax({
                        url: 'ajax/update_bk_pay.php', 
                        type: 'POST',
                        data: { trans_id: transId, new_status: newStatus },
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                
                                var updatedStatus = response.new_status_code;
                                var nextStatusForButton = (updatedStatus === 1) ? 0 : 1;
                                
                                var newBadge = '<span id="status-text-' + transId + '" class="badge text-bg-' + getPayoutColor(updatedStatus) + ' me-2">' + getPayoutText(updatedStatus) + '</span>';
                                
                                // Logic untuk button class saat ini
                                var newBtnClass = updatedStatus === 1 ? 'btn-success' : 'btn-secondary';
                                var oldBtnClass = newStatus === 1 ? 'btn-success' : 'btn-secondary';
                                
                                button.removeClass(oldBtnClass).addClass(newBtnClass);
                                button.data('status', nextStatusForButton);
                                button.text(getPayoutActionText(updatedStatus));
                                button.prop('disabled', false);
                                payoutCell.find('.badge').remove();
                                payoutCell.append(newBadge); 
                                
                            } else {
                                alert('Error: ' + response.message);
                                button.prop('disabled', false).text(currentText);
                            }
                        },
                        error: function() {
                            alert('Terjadi kesalahan koneksi saat update.');
                            button.prop('disabled', false).text(currentText);
                        }
                    });
                });
                
                // UPDATE BK_PAY SEMUA TRANSAKSI (Modal 2)
                $(document).on('click', '#transactionModal .update-payout-btn-all', function() {
                    if (userLevel !== 'admin') {
                        alert('Akses Ditolak: Hanya Admin yang dapat melakukan update.');
                        return;
                    }

                    var button = $(this);
                    var transId = button.data('trans-id');
                    var newStatus = button.data('status'); 
                    var currentText = button.text();
                    var payoutCell = $('#payout-cell-all-' + transId); 
                    
                    button.prop('disabled', true).text('Updating...');

                    $.ajax({
                        url: 'ajax/update_bk_pay.php', 
                        type: 'POST',
                        data: { trans_id: transId, new_status: newStatus },
                        dataType: 'json',
                        success: function(response) {
                            if (response.status === 'success') {
                                
                                var updatedStatus = response.new_status_code;
                                var nextStatusForButton = (updatedStatus === 1) ? 0 : 1;
                                
                                var newBadge = '<span id="status-text-trans-' + transId + '" class="badge text-bg-' + getPayoutColor(updatedStatus) + ' me-2">' + getPayoutText(updatedStatus) + '</span>';
                                
                                // Logic untuk button class saat ini
                                var newBtnClass = updatedStatus === 1 ? 'btn-danger' : 'btn-success';
                                var oldBtnClass = newStatus === 1 ? 'btn-danger' : 'btn-success';
                                
                                button.removeClass(oldBtnClass).addClass(newBtnClass);
                                button.data('status', nextStatusForButton);
                                button.text(getPayoutActionText(updatedStatus));
                                button.prop('disabled', false);
                                
                                payoutCell.html(newBadge + button[0].outerHTML);
                            } else {
                                alert('Error: ' + response.message);
                                button.prop('disabled', false).text(currentText);
                            }
                        },
                        error: function() {
                            alert('Terjadi kesalahan koneksi saat update.');
                            button.prop('disabled', false).text(currentText);
                        }
                    });
                });
                
                // BACKDROP LOGIC FIX: Menutup Modal 3 kembali ke Modal 1 atau ke Tabel Admin
                $('#memberDetailModal').on('hidden.bs.modal', function () {
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove();
                    
                    var isFromReferral = $('#memberDetailModal').data('is-from-referral');
                    
                    // Kembali ke Modal Rujukan HANYA JIKA dipicu dari Modal Rujukan
                    if (isFromReferral && userLevel === 'admin') {
                       referralModal.show();
                    } 
                    // Jika tidak (misal dari Tabel Semua User), biarkan modal tertutup semua.
                    
                    // Reset flag
                    $('#memberDetailModal').data('is-from-referral', false);
                });
                
                // BACKDROP LOGIC FIX: Menutup Modal 2 kembali ke Modal 3 atau Modal 1
                $('#transactionModal').on('hidden.bs.modal', function () {
                    $('body').removeClass('modal-open');
                    $('.modal-backdrop').remove(); 
                    
                    var userIdInDetail = $('.view-all-transactions-from-detail').data('user-id');
                    
                    if (userIdInDetail) {
                       memberDetailModal.show(); // Kembali ke Modal 3
                    } else {
                       referralModal.show(); // Kembali ke Modal 1 (History dipanggil dari sini)
                    }
                });
            }

        });
    </script>
</body>
</html>
<?php
// Pastikan semua hasil query dibebaskan
if ($promotors_active) mysqli_free_result($promotors_active);
if ($members_without_upline) mysqli_free_result($members_without_upline);
if ($list_of_promotors) mysqli_free_result($list_of_promotors);
if ($all_users) mysqli_free_result($all_users);

if ($is_authenticated) {
    mysqli_close($conn);
}
?>