<?php
// get_member_detail.php - AJAX Handler untuk Modal Member Statistic
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

header('Content-Type: application/json');

include_once __DIR__ . '/../koneksi.php';

if (!isset($_SESSION['kode_admin'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit();
}

if (!isset($_POST['id_anggota']) || empty($_POST['id_anggota'])) {
    echo json_encode([
        'success' => false,
        'message' => 'ID Anggota tidak valid'
    ]);
    exit();
}

$id_anggota = (int)$_POST['id_anggota'];

// Fungsi untuk mendapatkan detail member
function getMemberDetail($koneksi, $id_anggota) {
    $data = [
        'member' => null,
        'total_deposit' => 0,
        'jumlah_deposit' => 0,
        'total_withdraw' => 0,
        'jumlah_withdraw' => 0,
        'tanggal_deposit_pertama' => '-',
        'bonus_referral' => 0,
        'transaksi' => []
    ];
    
    // Ambil data member
    $sql_member = "SELECT * FROM anggota WHERE id_anggota = ?";
    $stmt = $koneksi->prepare($sql_member);
    if ($stmt) {
        $stmt->bind_param("i", $id_anggota);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($member = $result->fetch_assoc()) {
            $data['member'] = $member;
        } else {
            return null; // Member tidak ditemukan
        }
        $stmt->close();
    }
    
    // Total deposit
    $sql_deposit = "SELECT 
                        COUNT(*) as jumlah,
                        SUM(CAST(REPLACE(jumlah_deposit, ',', '') AS DECIMAL(15,2))) AS total,
                        MIN(tanggal_deposit) as pertama
                    FROM deposit 
                    WHERE id_anggota_deposit = ? AND status_deposit = 'disetujui'";
    $stmt = $koneksi->prepare($sql_deposit);
    if ($stmt) {
        $stmt->bind_param("i", $id_anggota);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $data['total_deposit'] = (float)($row['total'] ?? 0);
            $data['jumlah_deposit'] = (int)($row['jumlah'] ?? 0);
            if ($row['pertama']) {
                $data['tanggal_deposit_pertama'] = date('d/m/Y H:i:s', strtotime($row['pertama']));
            }
        }
        $stmt->close();
    }
    
    // Total withdraw
    $sql_withdraw = "SELECT 
                        COUNT(*) as jumlah,
                        SUM(CAST(REPLACE(jumlah_withdraw, ',', '') AS DECIMAL(15,2))) AS total
                    FROM withdraw 
                    WHERE id_anggota_withdraw = ? AND status_withdraw = 'disetujui'";
    $stmt = $koneksi->prepare($sql_withdraw);
    if ($stmt) {
        $stmt->bind_param("i", $id_anggota);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $data['total_withdraw'] = (float)($row['total'] ?? 0);
            $data['jumlah_withdraw'] = (int)($row['jumlah'] ?? 0);
        }
        $stmt->close();
    }
    
    // Bonus referral
    $sql_referral = "SELECT SUM(bonus) as total FROM tb_refferal WHERE id_user = ?";
    $stmt = $koneksi->prepare($sql_referral);
    if ($stmt) {
        $stmt->bind_param("s", $data['member']['nama_pengguna_anggota']);
        $stmt->execute();
        $result = $stmt->get_result();
        if ($row = $result->fetch_assoc()) {
            $data['bonus_referral'] = (float)($row['total'] ?? 0);
        }
        $stmt->close();
    }
    
    // Ambil transaksi deposit
    $sql_deposit_list = "SELECT 
                            kode_deposit as referensi,
                            'Deposit' as tipe,
                            asal_deposit as pengirim,
                            tujuan_deposit as member_rek,
                            CAST(REPLACE(jumlah_deposit, ',', '') AS DECIMAL(15,2)) as saldo,
                            tanggal_deposit as tanggal
                        FROM deposit 
                        WHERE id_anggota_deposit = ? AND status_deposit = 'disetujui'";
    $stmt = $koneksi->prepare($sql_deposit_list);
    if ($stmt) {
        $stmt->bind_param("i", $id_anggota);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $data['transaksi'][] = $row;
        }
        $stmt->close();
    }
    
    // Ambil transaksi withdraw
    $sql_withdraw_list = "SELECT 
                            kode_withdraw as referensi,
                            'Withdraw' as tipe,
                            'DANA' as pengirim,
                            tujuan_withdraw as member_rek,
                            CAST(REPLACE(jumlah_withdraw, ',', '') AS DECIMAL(15,2)) as saldo,
                            tanggal_withdraw as tanggal
                        FROM withdraw 
                        WHERE id_anggota_withdraw = ? AND status_withdraw = 'disetujui'";
    $stmt = $koneksi->prepare($sql_withdraw_list);
    if ($stmt) {
        $stmt->bind_param("i", $id_anggota);
        $stmt->execute();
        $result = $stmt->get_result();
        while ($row = $result->fetch_assoc()) {
            $data['transaksi'][] = $row;
        }
        $stmt->close();
    }
    
    // Urutkan transaksi berdasarkan tanggal
    usort($data['transaksi'], function($a, $b) {
        return strtotime($b['tanggal']) - strtotime($a['tanggal']);
    });
    
    return $data;
}

$member_data = getMemberDetail($koneksi, $id_anggota);

if (!$member_data || !$member_data['member']) {
    echo json_encode([
        'success' => false,
        'message' => 'Data member tidak ditemukan'
    ]);
    exit();
}

// Generate HTML content
ob_start();
?>
<div class="row">
    <!-- Summary Grid - 2 Baris x 4 Kolom -->
    <div class="col-md-3 mb-3">
        <div class="border rounded p-3 bg-light">
            <small class="text-muted d-block mb-1">Total Deposit</small>
            <h6 class="mb-0 fw-bold">Rp <?php echo number_format($member_data['total_deposit'], 0, ',', '.'); ?></h6>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="border rounded p-3 bg-light">
            <small class="text-muted d-block mb-1">Total Jumlah Deposit</small>
            <h6 class="mb-0 fw-bold"><?php echo number_format($member_data['jumlah_deposit']); ?></h6>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="border rounded p-3 bg-light">
            <small class="text-muted d-block mb-1">Tanggal Deposit Pertama</small>
            <h6 class="mb-0 fw-bold"><?php echo htmlspecialchars($member_data['tanggal_deposit_pertama']); ?></h6>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="border rounded p-3 bg-light">
            <small class="text-muted d-block mb-1">Bonus Referral Diperoleh</small>
            <h6 class="mb-0 fw-bold">Rp <?php echo number_format($member_data['bonus_referral'], 0, ',', '.'); ?></h6>
        </div>
    </div>
    
    <div class="col-md-3 mb-3">
        <div class="border rounded p-3 bg-light">
            <small class="text-muted d-block mb-1">Total Withdraw</small>
            <h6 class="mb-0 fw-bold">Rp <?php echo number_format($member_data['total_withdraw'], 0, ',', '.'); ?></h6>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="border rounded p-3 bg-light">
            <small class="text-muted d-block mb-1">Total Jumlah Withdraw</small>
            <h6 class="mb-0 fw-bold"><?php echo number_format($member_data['jumlah_withdraw']); ?></h6>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="border rounded p-3 bg-light">
            <small class="text-muted d-block mb-1">Status</small>
            <h6 class="mb-0">
                <?php if ($member_data['member']['status_anggota'] == 'aktif'): ?>
                    <span class="badge bg-success">Aktif</span>
                <?php else: ?>
                    <span class="badge bg-danger">Terkunci</span>
                <?php endif; ?>
            </h6>
        </div>
    </div>
    <div class="col-md-3 mb-3">
        <div class="border rounded p-3 bg-light">
            <small class="text-muted d-block mb-1">Saldo</small>
            <h6 class="mb-0 fw-bold">Rp <?php echo number_format($member_data['member']['saldo_anggota'], 0, ',', '.'); ?></h6>
        </div>
    </div>
</div>

<!-- Tabel Rekening Sumber -->
<h6 class="mt-4 mb-3">Rekening Sumber</h6>
<?php if (!empty($member_data['transaksi'])): ?>
<div class="table-responsive">
    <table id="tabelTransaksiModal" class="table table-sm table-bordered table-hover" style="font-size: 13px;">
        <thead class="table-light">
            <tr>
                <th style="width: 5%;">No</th>
                <th style="width: 15%;">Referensi</th>
                <th style="width: 10%;">Tipe</th>
                <th style="width: 20%;">Rekening Member</th>
                <th style="width: 20%;">Rekening Bandar</th>
                <th style="width: 15%;">Saldo</th>
                <th style="width: 15%;">Tanggal</th>
            </tr>
        </thead>
        <tbody>
            <?php 
            $no = 1;
            foreach ($member_data['transaksi'] as $trx): 
            ?>
            <tr>
                <td><?php echo $no++; ?></td>
                <td><?php echo htmlspecialchars($trx['referensi']); ?></td>
                <td>
                    <?php if ($trx['tipe'] == 'Deposit'): ?>
                        <span class="badge bg-success">Deposit</span>
                    <?php else: ?>
                        <span class="badge bg-danger">Withdraw</span>
                    <?php endif; ?>
                </td>
                <td><?php echo htmlspecialchars($trx['pengirim']); ?></td>
                <td><?php echo htmlspecialchars($trx['member_rek']); ?></td>
                <td>Rp <?php echo number_format($trx['saldo'], 0, ',', '.'); ?></td>
                <td><?php echo date('d/m/Y H:i', strtotime($trx['tanggal'])); ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php else: ?>
<div class="alert alert-info">
    <i class="bx bx-info-circle"></i> Belum ada transaksi untuk member ini.
</div>
<?php endif; ?>
<?php
$html_content = ob_get_clean();

echo json_encode([
    'success' => true,
    'html' => $html_content
]);

if (isset($koneksi) && $koneksi instanceof mysqli && $koneksi->thread_id) {
    $koneksi->close();
}
?>