<?php
ob_start();
include 'config.php';
checkLogin(); 
if (!has_access($conn, 'perm_manage_members')) {
    header("Location: index.php?status=restricted");
    exit;
}

// --- LOGIKA PROSES ---

// 1. TAMBAH MEMBER
if(isset($_POST['add_member'])) {
    $nama = mysqli_real_escape_string($conn, $_POST['nama']);
    $telp = mysqli_real_escape_string($conn, $_POST['telepon']);
    
    // Cek duplikat
    $cek = mysqli_query($conn, "SELECT id FROM members WHERE nama_member = '$nama'");
    if(mysqli_num_rows($cek) == 0) {
        mysqli_query($conn, "INSERT INTO members (nama_member, telepon) VALUES ('$nama', '$telp')");
    }
    header("Location: members.php");
    exit;
}

// 2. PROSES TOP UP (PERBAIKAN DISINI)
if(isset($_POST['top_up'])) {
    $id = (int)$_POST['member_id'];
    $jumlah = (int)$_POST['jumlah'];
    
    // A. Update Saldo Member
    mysqli_query($conn, "UPDATE members SET saldo = saldo + $jumlah WHERE id='$id'");

    // B. CATAT KE RIWAYAT (INI YANG SEBELUMNYA KURANG)
    // Pastikan tabel member_topups sudah dibuat di database
    $cek_tabel = mysqli_query($conn, "SHOW TABLES LIKE 'member_topups'");
    if(mysqli_num_rows($cek_tabel) > 0) {
        mysqli_query($conn, "INSERT INTO member_topups (member_id, amount, created_at) VALUES ('$id', '$jumlah', NOW())");
    }

    header("Location: members.php");
    exit;
}

// 3. HAPUS MEMBER
if(isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    mysqli_query($conn, "DELETE FROM members WHERE id='$id'");
    header("Location: members.php");
    exit;
}

// --- HITUNG STATISTIK ---
$total_members = mysqli_num_rows(mysqli_query($conn, "SELECT id FROM members"));
$total_assets_q = mysqli_fetch_assoc(mysqli_query($conn, "SELECT SUM(saldo) as total FROM members"));
$total_assets = $total_assets_q['total'] ?? 0;

$page_title = "Member VIP";
$active_page = "members";
include 'layout.php';
?>

<!-- --- CSS MODERN GLASS STYLE --- -->
<style>
    :root {
        --glass-bg: rgba(30, 41, 59, 0.7);
        --glass-border: rgba(255, 255, 255, 0.08);
        --accent-gradient: linear-gradient(135deg, #6366f1 0%, #a855f7 100%);
        --text-muted: #94a3b8;
        --card-bg: #1e293b;
    }

    .dashboard-grid {
        display: grid;
        grid-template-columns: 350px 1fr;
        gap: 30px;
        padding-bottom: 50px;
    }

    .stats-row {
        grid-column: 1 / -1;
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 20px;
        margin-bottom: 10px;
    }

    .stat-card {
        background: var(--glass-bg);
        border: 1px solid var(--glass-border);
        padding: 20px;
        border-radius: 16px;
        display: flex;
        align-items: center;
        gap: 15px;
        backdrop-filter: blur(10px);
    }
    .stat-icon {
        width: 50px; height: 50px;
        border-radius: 12px;
        display: flex; align-items: center; justify-content: center;
        font-size: 1.5rem;
        background: rgba(255,255,255,0.05);
        color: #fff;
    }
    .stat-info h4 { margin: 0; color: var(--text-muted); font-size: 0.85rem; font-weight: 500; }
    .stat-info h2 { margin: 5px 0 0 0; color: #fff; font-size: 1.5rem; }

    .modern-card {
        background: var(--glass-bg);
        border: 1px solid var(--glass-border);
        border-radius: 20px;
        padding: 25px;
        backdrop-filter: blur(12px);
        position: relative;
        overflow: hidden;
    }
    
    .modern-card::before {
        content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 4px;
        background: var(--accent-gradient);
    }

    .card-header {
        display: flex; justify-content: space-between; align-items: center;
        margin-bottom: 25px;
    }
    .card-title {
        font-size: 1.1rem; color: #fff; font-weight: 700; display: flex; align-items: center; gap: 10px;
    }

    .input-group { margin-bottom: 20px; position: relative; }
    .input-label {
        display: block; color: var(--text-muted); font-size: 0.8rem; margin-bottom: 8px; font-weight: 600;
    }
    .modern-input {
        width: 100%;
        background: rgba(0,0,0,0.2);
        border: 1px solid var(--glass-border);
        color: #fff;
        padding: 12px 15px;
        border-radius: 10px;
        font-size: 0.95rem;
        transition: 0.3s;
    }
    .modern-input:focus {
        border-color: #8b5cf6;
        background: rgba(0,0,0,0.4);
        outline: none;
        box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.2);
    }

    .btn-gradient {
        width: 100%; border: none; padding: 14px;
        border-radius: 10px;
        background: var(--accent-gradient);
        color: #fff; font-weight: 700; font-size: 0.9rem;
        cursor: pointer;
        transition: transform 0.2s, box-shadow 0.2s;
        text-shadow: 0 1px 2px rgba(0,0,0,0.2);
    }
    .btn-gradient:hover {
        transform: translateY(-2px);
        box-shadow: 0 10px 20px -5px rgba(168, 85, 247, 0.4);
    }

    .member-list {
        display: flex; flex-direction: column; gap: 10px;
        max-height: 500px; overflow-y: auto; padding-right: 5px;
    }
    .member-list::-webkit-scrollbar { width: 6px; }
    .member-list::-webkit-scrollbar-thumb { background: #475569; border-radius: 10px; }

    .member-row {
        background: rgba(255,255,255,0.03);
        border-radius: 12px;
        padding: 15px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border: 1px solid transparent;
        transition: 0.2s;
    }
    .member-row:hover {
        background: rgba(255,255,255,0.06);
        border-color: rgba(255,255,255,0.1);
        transform: translateX(5px);
    }

    .user-info { display: flex; align-items: center; gap: 15px; }
    .avatar {
        width: 40px; height: 40px;
        background: linear-gradient(45deg, #3b82f6, #8b5cf6);
        border-radius: 50%;
        display: flex; align-items: center; justify-content: center;
        font-weight: bold; color: #fff; font-size: 1rem;
        text-shadow: 0 1px 2px rgba(0,0,0,0.3);
    }
    .user-details h5 { margin: 0; color: #fff; font-size: 0.95rem; }
    .user-details span { font-size: 0.8rem; color: var(--text-muted); display: block; margin-top: 3px; }

    .saldo-badge {
        background: rgba(16, 185, 129, 0.15);
        color: #34d399;
        padding: 5px 10px;
        border-radius: 6px;
        font-size: 0.85rem;
        font-weight: 600;
        border: 1px solid rgba(16, 185, 129, 0.2);
        min-width: 90px; text-align: right;
    }

    .action-btn {
        background: transparent; border: none; cursor: pointer;
        padding: 8px; border-radius: 8px; transition: 0.2s; color: var(--text-muted);
    }
    .action-btn.topup:hover { background: rgba(59, 130, 246, 0.2); color: #60a5fa; }
    .action-btn.delete:hover { background: rgba(239, 68, 68, 0.2); color: #f87171; }

    .modal-overlay {
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.7); backdrop-filter: blur(5px);
        z-index: 1000;
        display: none; align-items: center; justify-content: center;
        opacity: 0; transition: opacity 0.3s;
    }
    .modal-box {
        background: #1e293b; border: 1px solid rgba(255,255,255,0.1);
        padding: 30px; width: 100%; max-width: 400px;
        border-radius: 20px;
        transform: scale(0.9); transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        box-shadow: 0 25px 50px -12px rgba(0,0,0,0.5);
    }
    .modal-active { display: flex; opacity: 1; }
    .modal-active .modal-box { transform: scale(1); }

    @media (max-width: 900px) {
        .dashboard-grid { grid-template-columns: 1fr; }
        .member-row { flex-direction: column; align-items: flex-start; gap: 10px; }
        .member-row .actions { align-self: flex-end; width: 100%; display: flex; justify-content: space-between; margin-top: 10px; border-top: 1px solid rgba(255,255,255,0.05); padding-top: 10px; }
    }
</style>

<div class="dashboard-grid">

    <!-- STATS ROW -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon" style="background: rgba(99, 102, 241, 0.2); color: #818cf8;">
                <i class='bx bxs-user-detail'></i>
            </div>
            <div class="stat-info">
                <h4>Total Member</h4>
                <h2><?= number_format($total_members) ?></h2>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon" style="background: rgba(16, 185, 129, 0.2); color: #34d399;">
                <i class='bx bxs-wallet'></i>
            </div>
            <div class="stat-info">
                <h4>Total Aset User</h4>
                <h2>Rp <?= number_format($total_assets / 1000) ?>k</h2>
            </div>
        </div>
    </div>

    <!-- KOLOM KIRI: FORM REGISTRASI -->
    <div class="modern-card">
        <div class="card-header">
            <span class="card-title"><i class='bx bxs-id-card'></i> Member Baru</span>
        </div>
        <form method="POST">
            <div class="input-group">
                <label class="input-label">Nama Lengkap</label>
                <input type="text" name="nama" class="modern-input" placeholder="Isi nama member..." required autocomplete="off">
            </div>
            <div class="input-group">
                <label class="input-label">Nomor WhatsApp</label>
                <input type="number" name="telepon" class="modern-input" placeholder="08xxxxx" required autocomplete="off">
            </div>
            <button type="submit" name="add_member" class="btn-gradient">
                <i class='bx bx-plus-circle'></i> Tambah Member
            </button>
        </form>
    </div>

    <!-- KOLOM KANAN: LIST MEMBER -->
    <div class="modern-card">
        <div class="card-header">
            <span class="card-title"><i class='bx bxs-data'></i> Database Member</span>
            <div style="font-size:0.8rem; color:#64748b;">Terbaru: Hari ini</div>
        </div>

        <div class="member-list">
            <?php 
            $res = mysqli_query($conn, "SELECT * FROM members ORDER BY id DESC");
            if(mysqli_num_rows($res) > 0):
                while($m = mysqli_fetch_assoc($res)): 
                    $initial = strtoupper(substr($m['nama_member'], 0, 1));
            ?>
            <div class="member-row">
                <div class="user-info">
                    <div class="avatar"><?= $initial ?></div>
                    <div class="user-details">
                        <h5><?= htmlspecialchars($m['nama_member']) ?></h5>
                        <span><?= htmlspecialchars($m['telepon']) ?></span>
                    </div>
                </div>
                <div class="actions" style="display:flex; align-items:center; gap:15px;">
                    <div class="saldo-badge">Rp <?= number_format($m['saldo']) ?></div>
                    
                    <button onclick="openTopUp('<?= $m['id'] ?>', '<?= htmlspecialchars($m['nama_member']) ?>')" class="action-btn topup" title="Top Up Saldo">
                        <i class='bx bxs-plus-square' style="font-size:1.3rem;"></i>
                    </button>
                    
                    <a href="?delete=<?= $m['id'] ?>" onclick="return confirm('Hapus data permanen?')" class="action-btn delete" title="Hapus Member">
                        <i class='bx bxs-trash-alt' style="font-size:1.2rem;"></i>
                    </a>
                </div>
            </div>
            <?php endwhile; 
            else: ?>
                <div style="text-align:center; padding:40px; color:var(--text-muted);">
                    <i class='bx bx-ghost' style="font-size:2rem; margin-bottom:10px;"></i><br>
                    Belum ada member terdaftar.
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- MODAL TOP UP -->
<div id="modalTopUp" class="modal-overlay">
    <div class="modal-box">
        <h3 style="color:#fff; margin-top:0; font-size:1.2rem;">Top Up Saldo <span style="color:#818cf8;">⚡</span></h3>
        <p style="color:var(--text-muted); font-size:0.9rem; margin-bottom:20px;">Menambahkan saldo untuk <b id="tu_name" style="color:#fff;">...</b></p>
        
        <form method="POST">
            <input type="hidden" name="member_id" id="tu_id">
            <div class="input-group">
                <label class="input-label">Nominal (Rp)</label>
                <input type="number" name="jumlah" id="input_jml" class="modern-input" style="font-size:1.2rem; font-weight:bold; color:#34d399;" placeholder="0" required autofocus>
            </div>
            
            <div style="display:flex; gap:8px; margin-bottom:20px; overflow-x:auto;">
                <button type="button" onclick="fillNominal(10000)" class="action-btn" style="border:1px solid #334155; font-size:0.8rem; color:#fff;">10k</button>
                <button type="button" onclick="fillNominal(20000)" class="action-btn" style="border:1px solid #334155; font-size:0.8rem; color:#fff;">20k</button>
                <button type="button" onclick="fillNominal(50000)" class="action-btn" style="border:1px solid #334155; font-size:0.8rem; color:#fff;">50k</button>
            </div>

            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:15px;">
                <button type="button" onclick="closeTopUp()" style="background:transparent; border:1px solid #475569; color:#cbd5e1; padding:12px; border-radius:10px; cursor:pointer;">Batal</button>
                <button type="submit" name="top_up" class="btn-gradient">Konfirmasi</button>
            </div>
        </form>
    </div>
</div>

<script>
const modal = document.getElementById('modalTopUp');

function openTopUp(id, name) {
    document.getElementById('tu_id').value = id;
    document.getElementById('tu_name').innerText = name;
    modal.classList.add('modal-active');
}

function closeTopUp() {
    modal.classList.remove('modal-active');
}

function fillNominal(amount) {
    document.getElementById('input_jml').value = amount;
}

modal.addEventListener('click', function(e) {
    if (e.target === modal) closeTopUp();
});
</script>

<?php 
echo "</div></body></html>";
ob_end_flush();
?>