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

// 0. SET TIMEZONE JAKARTA
date_default_timezone_set('Asia/Jakarta');

// 1. LOGIC LOGOUT ADMIN
if (isset($_GET['act']) && $_GET['act'] == 'logout') {
    session_destroy();
    header("Location: login.php");
    exit();
}

// 2. CEK LOGIN & VALIDASI SESSION ROLE
if (!isset($_SESSION['admin_logged_in']) || !isset($_SESSION['admin_role'])) { 
    session_unset();
    session_destroy();
    header("Location: login.php"); 
    exit(); 
}

// Redirect Branch ke project.php
if ($_SESSION['admin_role'] == 'branch') { header("Location: project.php"); exit(); }

$admin_role = $_SESSION['admin_role']; // super_admin, secretary, branch

// ============================================================
// LOGIC HANDLER (POST REQUESTS)
// ============================================================

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // 1. HANDLER BROADCAST & SWITCH WITHDRAW
    if (isset($_POST['admin_action'])) {
        
        // A. Toggle Withdraw Status
        if ($_POST['admin_action'] == 'toggle_withdraw') {
            $status = $_POST['status']; 
            
            $cek = $conn->query("SELECT id FROM settings WHERE setting_key = 'withdraw_status'");
            
            if($cek->num_rows > 0) {
                $conn->query("UPDATE settings SET setting_value = '$status' WHERE setting_key = 'withdraw_status'");
            } else {
                $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('withdraw_status', '$status')");
            }
            
            $msg_status = ($status == 'on') ? 'AKTIF' : 'NON-AKTIF';
            $_SESSION['flash'] = "Status Withdraw Berhasil Diubah Menjadi: " . $msg_status;
            
            header("Location: index.php?page=broadcast_wd"); exit();
        }

        // B. Broadcast Add
        if ($_POST['admin_action'] == 'broadcast_add') {
            $title = $conn->real_escape_string($_POST['title']);
            $msg = $conn->real_escape_string($_POST['message']);
            if(!empty($title) && !empty($msg)){
                $conn->query("INSERT INTO admin_messages (title, message) VALUES ('$title', '$msg')");
                $_SESSION['flash'] = "Pesan Broadcast Terkirim!";
            }
            header("Location: index.php?page=broadcast_wd"); exit();
        }
        
        // C. Broadcast Delete
        if ($_POST['admin_action'] == 'broadcast_delete') {
            $id = intval($_POST['id']);
            $conn->query("DELETE FROM admin_messages WHERE id=$id");
            $conn->query("DELETE FROM message_reads WHERE message_id=$id");
            $_SESSION['flash'] = "Pesan Broadcast Dihapus!";
            header("Location: index.php?page=broadcast_wd"); exit();
        }
    }

    // 2. HANDLER TAMBAH ADMIN BARU
    if (isset($_POST['create_admin'])) {
        if($admin_role != 'super_admin') { die("Akses Ditolak"); }
        
        $username = $conn->real_escape_string($_POST['username']);
        $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
        $fullname = $conn->real_escape_string($_POST['full_name']);
        $role = $_POST['role'];

        $cek = $conn->query("SELECT id FROM admins WHERE username = '$username'");
        if($cek->num_rows > 0) {
            $_SESSION['flash'] = "Username sudah digunakan!";
        } else {
            $conn->query("INSERT INTO admins (username, password, full_name, role) VALUES ('$username', '$password', '$fullname', '$role')");
            $_SESSION['flash'] = "Admin Baru Berhasil Ditambahkan!";
        }
        header("Location: index.php?page=manage_admins"); exit();
    }

    // 3. INPUT KEUANGAN MANUAL (Laporan)
    if (isset($_POST['save_finance'])) {
        $type = $_POST['type']; 
        $cat = $_POST['category'];
        $amount = $_POST['amount'];
        $desc = $_POST['description'];
        $date = $_POST['date_recorded'];
        
        $conn->query("INSERT INTO company_finances (type, category, amount, description, date_recorded) 
                    VALUES ('$type', '$cat', '$amount', '$desc', '$date')");
        $_SESSION['flash'] = "Data Keuangan Berhasil Disimpan!";
        header("Location: index.php?page=laporan"); exit();
    }

    // 4. SIMPAN SETTINGS
    if (isset($_POST['save_settings'])) {
        if($admin_role != 'super_admin') { die("Akses Ditolak"); }
        foreach ($_POST as $key => $value) {
            if ($key != 'save_settings' && $key != 'site_logo') {
                $val = $conn->real_escape_string($value);
                $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('$key', '$val') ON DUPLICATE KEY UPDATE setting_value = '$val'");
            }
        }
        if (isset($_FILES['site_logo']) && $_FILES['site_logo']['error'] == 0) {
            $target_dir = "../uploads/";
            if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
            $file_name = "logo_site.png";
            move_uploaded_file($_FILES['site_logo']['tmp_name'], $target_dir . $file_name);
            $conn->query("INSERT INTO settings (setting_key, setting_value) VALUES ('site_logo', '$file_name') ON DUPLICATE KEY UPDATE setting_value = '$file_name'");
        }
        $_SESSION['flash'] = "Pengaturan Disimpan!";
        header("Location: index.php?page=settings"); exit();
    }

    // 5. UPLOAD BANNER
    if (isset($_POST['upload_banner'])) {
        if (isset($_FILES['banner_img']) && $_FILES['banner_img']['error'] == 0) {
            $target_dir = "../uploads/banners/";
            if (!file_exists($target_dir)) mkdir($target_dir, 0777, true);
            $file_name = "banner_" . time() . ".jpg";
            move_uploaded_file($_FILES['banner_img']['tmp_name'], $target_dir . $file_name);
            $conn->query("INSERT INTO banners (image) VALUES ('$file_name')");
            $_SESSION['flash'] = "Banner Berhasil Diupload!";
        }
        header("Location: index.php?page=banners"); exit();
    }
}

// ============================================================
// LOGIC HANDLER (GET REQUESTS)
// ============================================================

// 1. HAPUS ADMIN
if (isset($_GET['act']) && $_GET['act'] == 'del_admin' && isset($_GET['aid'])) {
    if($admin_role != 'super_admin') { die("Akses Ditolak"); }
    $aid = intval($_GET['aid']);
    if($aid == $_SESSION['admin_id']) {
        $_SESSION['flash'] = "Tidak bisa menghapus akun sendiri!";
    } else {
        $conn->query("DELETE FROM admins WHERE id = $aid");
        $_SESSION['flash'] = "Data Admin dihapus.";
    }
    header("Location: index.php?page=manage_admins"); exit();
}

// 2. HAPUS BANNER
if (isset($_GET['act']) && $_GET['act'] == 'del_banner' && isset($_GET['bid'])) {
    $bid = intval($_GET['bid']);
    $conn->query("DELETE FROM banners WHERE id = $bid");
    $_SESSION['flash'] = "Banner Dihapus";
    header("Location: index.php?page=banners"); exit();
}

// 3. ACTIONS MEMBER (Block/Delete)
if (isset($_GET['act']) && isset($_GET['uid']) && in_array($_GET['act'], ['delete', 'block', 'unblock', 'login_as'])) {
    $uid = intval($_GET['uid']);
    $act = $_GET['act'];
    if ($act == 'delete') {
        $conn->query("DELETE FROM users WHERE id = $uid");
        $conn->query("DELETE FROM transactions WHERE user_id = $uid");
        $_SESSION['flash'] = "User dihapus permanent.";
    } elseif ($act == 'block') {
        $conn->query("UPDATE users SET status = 'blocked' WHERE id = $uid");
        $_SESSION['flash'] = "User diblokir.";
    } elseif ($act == 'unblock') {
        $conn->query("UPDATE users SET status = 'active' WHERE id = $uid");
        $_SESSION['flash'] = "User diaktifkan kembali.";
    } elseif ($act == 'login_as') {
        $_SESSION['user_id'] = $uid;
        header("Location: ../dashboard.php"); exit();
    }
    header("Location: index.php?page=members"); exit();
}

// 4. HANDLE APPROVAL TRANSAKSI
// Helpers untuk ambil setting fee
$settings_query = $conn->query("SELECT * FROM settings");
$sys_sets = [];
while($r = $settings_query->fetch_assoc()) $sys_sets[$r['setting_key']] = $r['setting_value'];
$fee_wd_pct = isset($sys_sets['fee_withdraw_percent']) ? floatval($sys_sets['fee_withdraw_percent']) : 2.5;

if (isset($_GET['act']) && isset($_GET['tid']) && in_array($_GET['act'], ['approve', 'reject'])) {
    $tid = intval($_GET['tid']);
    $act = $_GET['act']; 
    $trx = $conn->query("SELECT * FROM transactions WHERE id = $tid")->fetch_assoc();
    
    if ($trx && $trx['status'] == 'pending') {
        $uid = $trx['user_id'];
        $amount = $trx['amount'];
        $type = $trx['type'];
        
        if ($act == 'approve') {
            $conn->begin_transaction();
            try {
                $conn->query("UPDATE transactions SET status = 'success' WHERE id = $tid");
                
                // A. Topup
                if ($type == 'topup') {
                    $conn->query("UPDATE users SET balance_idr = balance_idr + $amount WHERE id = $uid");
                } 
                // B. Starter
                else if ($type == 'register_starter' || $type == 'buy_starter') {
                    $conn->query("UPDATE users SET is_active = 1 WHERE id = $uid");
                }
                // C. Paket Bisnis (Stokis/Crowd/Crypto)
                else if (in_array($type, ['buy_stokis', 'buy_crowd', 'buy_crypto'])) {
                    $conn->query("UPDATE users SET role = 'premium' WHERE id = $uid");
                    
                    $user_data = $conn->query("SELECT upline_id, username FROM users WHERE id = $uid")->fetch_assoc();
                    $upline_id = $user_data['upline_id'];
                    $buyer_username = $user_data['username'];
                    $paket_label = strtoupper(str_replace('buy_', '', $type));

                    // Bonus Sponsor 10%
                    if ($upline_id) {
                        $bonus_sponsor = $amount * 0.10;
                        $conn->query("UPDATE users SET balance_idr = balance_idr + $bonus_sponsor WHERE id = $upline_id");
                        $desc_sponsor = "Bonus Sponsor 10% dari $buyer_username (Paket $paket_label)";
                        $conn->query("INSERT INTO transactions (user_id, type, amount, status, description, created_at) VALUES ($upline_id, 'bonus_sponsor', $bonus_sponsor, 'success', '$desc_sponsor', NOW())");

                        // Bonus Royalty 10 Level
                        $royalty_pct = [1=>2.0, 2=>2.0, 3=>2.0, 4=>1.0, 5=>0.5, 6=>0.5, 7=>0.5, 8=>0.5, 9=>0.5, 10=>0.5];
                        $curr_upline = $upline_id;
                        for ($level = 1; $level <= 10; $level++) {
                            if (!$curr_upline) break;
                            $persen = $royalty_pct[$level];
                            $bonus_royalty = $amount * ($persen / 100);
                            $conn->query("UPDATE users SET balance_idr = balance_idr + $bonus_royalty WHERE id = $curr_upline");
                            $desc_royalty = "Bonus Royalty L$level ($persen%) dari Omset Group";
                            $conn->query("INSERT INTO transactions (user_id, type, amount, status, description, created_at) VALUES ($curr_upline, 'bonus_royalty', $bonus_royalty, 'success', '$desc_royalty', NOW())");
                            $res_up = $conn->query("SELECT upline_id FROM users WHERE id = $curr_upline");
                            $curr_upline = ($res_up->num_rows > 0) ? $res_up->fetch_assoc()['upline_id'] : null;
                        }
                    }
                }
                
                $conn->commit();
                $_SESSION['flash'] = "Approved & Processed!";
            } catch (Exception $e) { $conn->rollback(); $_SESSION['flash'] = "Error: " . $e->getMessage(); }
            
        } elseif ($act == 'reject') {
            $conn->query("UPDATE transactions SET status = 'failed' WHERE id = $tid");
            
            // Logic Refund Saldo
            if ($type == 'withdraw') {
                $refund_amount = $amount + ($amount * ($fee_wd_pct / 100));
                $conn->query("UPDATE users SET balance_idr = balance_idr + $refund_amount WHERE id = $uid");
                $_SESSION['flash'] = "Rejected. Dana dikembalikan (Full Refund).";
            } 
            elseif (strpos($trx['description'], 'Potong Saldo') !== false) {
                $conn->query("UPDATE users SET balance_idr = balance_idr + $amount WHERE id = $uid");
                $_SESSION['flash'] = "Rejected & Saldo Dikembalikan!";
            } else {
                $_SESSION['flash'] = "Rejected!";
            }
        }
    }
    
    // Redirect logic
    $redir = 'dashboard';
    if(strpos($trx['type'], 'buy_') !== false) $redir = 'approve_paket'; 
    else if($trx['type'] == 'topup') $redir = 'approve_topup';
    else if($trx['type'] == 'withdraw') $redir = 'approve_withdraw';
    else if($trx['type'] == 'register_starter' || $trx['type'] == 'buy_starter') $redir = 'approve_starter';
    else if($trx['type'] == 'upgrade_starter') $redir = 'approve_upgrade';
    header("Location: index.php?page=$redir"); exit();
}

// ============================================================
// HELPERS & CONFIG
// ============================================================
$settings = [];
$qSet = $conn->query("SELECT * FROM settings");
while ($r = $qSet->fetch_assoc()) $settings[$r['setting_key']] = $r['setting_value'];
function getSet($key, $data) { return isset($data[$key]) ? $data[$key] : ''; }
if(!function_exists('formatRupiah')){
    function formatRupiah($angka){ return "Rp " . number_format($angka,0,',','.'); }
}

// Variable Navigasi
$page = $_GET['page'] ?? 'dashboard';
$limit = 10;
$p = isset($_GET['p']) ? intval($_GET['p']) : 1;
$offset = ($p - 1) * $limit;

// Flash Message Script
$swal_script = "";
if(isset($_SESSION['flash'])){
    $msg = $_SESSION['flash'];
    $swal_script = "Swal.fire({ icon: 'info', title: 'Info', text: '$msg', confirmButtonColor: '#10b981' });";
    unset($_SESSION['flash']);
}
?>

<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin - <?php echo ucfirst($page); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = { 
            darkMode: 'class', 
            theme: { 
                extend: { 
                    colors: { primary: '#10b981', darkbg: '#0f172a' },
                    animation: { 'shine': 'shine 3s infinite linear' },
                    keyframes: {
                        shine: { '0%': { backgroundPosition: '200% center' }, '100%': { backgroundPosition: '-200% center' } }
                    }
                } 
            } 
        }
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <style>
        .no-print { @media print { display: none; } }
        .print-only { display: none; @media print { display: block; } }
        td, th { white-space: nowrap; padding: 12px 16px; font-size: 0.85rem; border-bottom: 1px solid #334155; text-align: left; }
        thead { background-color: #1e293b; color: #94a3b8; }
        .overflow-x-auto::-webkit-scrollbar { height: 12px; }
        .overflow-x-auto::-webkit-scrollbar-track { background: #1e293b; border-radius: 4px; }
        .overflow-x-auto::-webkit-scrollbar-thumb { background-color: #64748b; border-radius: 4px; border: 2px solid #1e293b; }
        .overflow-x-auto::-webkit-scrollbar-thumb:hover { background-color: #94a3b8; }
        .pagination-btn { padding: 4px 10px; background: #334155; color: white; border-radius: 4px; margin: 0 2px; }
        .pagination-active { background: #10b981; }
        .card-bank { background: linear-gradient(135deg, rgba(30,41,59,0.9), rgba(15,23,42,1)); border: 1px solid rgba(255,255,255,0.1); position: relative; overflow: hidden; transition: all 0.3s ease; }
        .card-bank:hover { transform: translateY(-5px); box-shadow: 0 20px 25px -5px rgba(0,0,0,0.3); border-color: rgba(16,185,129,0.5); }
        .card-shimmer::before { content: ''; position: absolute; top: 0; left: -100%; width: 50%; height: 100%; background: linear-gradient(to right, transparent, rgba(255,255,255,0.1), transparent); transform: skewX(-20deg); animation: shine 3s infinite; }
    </style>
</head>
<body class="bg-gray-100 dark:bg-darkbg text-gray-800 dark:text-gray-200 font-sans h-screen flex overflow-hidden" x-data="{ sidebarOpen: false }">

    <aside class="fixed inset-y-0 left-0 z-40 w-64 bg-slate-900 border-r border-slate-800 transition-transform duration-300 transform no-print" :class="sidebarOpen ? 'translate-x-0' : '-translate-x-full md:translate-x-0'">
        <div class="h-16 flex items-center justify-center border-b border-slate-800 gap-2">
            <?php $logo = getSet('site_logo', $settings) ?: "https://via.placeholder.com/40"; ?>
            <img src="../uploads/<?php echo $logo; ?>" class="w-8 h-8 rounded-full border border-primary">
            <h1 class="font-bold text-white text-xl">Admin Panel</h1>
        </div>
        
        <nav class="flex-1 overflow-y-auto px-2 space-y-1 py-4">
            <a href="?page=dashboard" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-gray-400 hover:text-white transition"><i class="fas fa-home w-5 text-center"></i> <span>Dashboard</span></a>
            <a href="?page=members" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-gray-400 hover:text-white transition"><i class="fas fa-users w-5 text-center"></i> <span>Data Member</span></a>
            <a href="project.php" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-blue-400 hover:text-white transition"><i class="fas fa-chart-pie w-5 text-center"></i> <span>Pengelolaan Asset</span></a>
            <a href="?page=banners" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-pink-400 hover:text-white transition"><i class="fas fa-images w-5 text-center"></i> <span>Kelola Banner</span></a>
            <a href="?page=laporan" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-yellow-400 hover:text-white transition"><i class="fas fa-file-invoice-dollar w-5 text-center"></i> <span>Laporan Perusahaan</span></a>

            <div class="text-xs font-bold text-gray-600 mt-4 mb-2 px-4">APPROVAL</div>
            
            <a href="?page=broadcast_wd" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-purple-400 hover:text-white transition"><i class="fas fa-bullhorn w-5 text-center"></i> <span>Broadcast & WD Switch</span></a>
            
            <a href="?page=approve_topup" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-gray-400 hover:text-white transition"><i class="fas fa-wallet w-5 text-center"></i> <span>Approve Top Up</span></a>
            <a href="?page=approve_withdraw" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-gray-400 hover:text-white transition"><i class="fas fa-money-bill-wave w-5 text-center"></i> <span>Approve Withdraw</span></a>
            <a href="?page=approve_paket" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-gray-400 hover:text-white transition"><i class="fas fa-box w-5 text-center"></i> <span>Approve Paket Bisnis</span></a>
            <a href="?page=approve_starter" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-gray-400 hover:text-white transition"><i class="fas fa-user-plus w-5 text-center"></i> <span>Approve Beli Starter</span></a>
            <a href="?page=approve_upgrade" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-emerald-400 hover:text-white transition"><i class="fas fa-level-up-alt w-5 text-center"></i> <span>Approve Upgrade</span></a>

            <?php if($admin_role == 'super_admin'): ?>
            <div class="text-xs font-bold text-gray-600 mt-4 mb-2 px-4">SUPER ADMIN</div>
            <a href="?page=manage_admins" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-purple-400 hover:text-white transition"><i class="fas fa-user-shield w-5 text-center"></i> <span>Kelola Admin</span></a>
            <a href="?page=settings" class="flex items-center gap-3 py-3 px-4 rounded-xl hover:bg-slate-800 text-gray-400 hover:text-white transition"><i class="fas fa-cogs w-5 text-center"></i> <span>Settings</span></a>
            <?php endif; ?>

            <a href="?act=logout" class="flex items-center gap-3 py-3 px-4 rounded-xl text-red-400 hover:bg-red-900/30 mt-8 transition"><i class="fas fa-sign-out-alt w-5 text-center"></i> <span>Logout</span></a>
        </nav>
    </aside>

    <div x-show="sidebarOpen" @click="sidebarOpen = false" class="fixed inset-0 z-30 bg-black/50 md:hidden"></div>

    <div class="flex-1 flex flex-col md:ml-64 transition-all duration-300 h-full">
        <header class="h-16 bg-slate-900 flex justify-between items-center px-4 shadow-md z-20 sticky top-0 no-print">
            <div class="flex items-center gap-3">
                <button @click="sidebarOpen = !sidebarOpen" class="text-gray-400 hover:text-white focus:outline-none md:hidden"><i class="fas fa-bars text-xl"></i></button>
            </div>
            <div class="flex items-center gap-4">
                <div class="text-right">
                    <p class="text-xs text-gray-400">Server Time (WIB)</p>
                    <p class="text-sm font-bold text-white"><?php echo date('d M Y H:i'); ?></p>
                </div>
                <div class="bg-green-500/20 border border-green-500 text-green-400 px-3 py-1 rounded-full text-xs font-bold flex items-center gap-2 animate-pulse"><div class="w-2 h-2 bg-green-500 rounded-full"></div> ONLINE</div>
            </div>
        </header>

        <div class="flex-1 overflow-y-auto p-6 relative">
            
            <?php if ($page == 'dashboard'): ?>
                <?php if($admin_role == 'branch'): ?>
                <h2 class="text-2xl font-bold mb-6 text-blue-400">Dashboard Cabang</h2>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                    <div class="card-bank card-shimmer rounded-2xl p-6 text-white h-40 flex flex-col justify-between">
                        <div class="flex justify-between items-start"><div><p class="text-xs font-bold text-blue-300 tracking-widest">TOTAL CABANG</p></div><i class="fas fa-code-branch text-2xl text-blue-500/50"></i></div>
                        <h3 class="text-3xl font-bold">1</h3><div class="text-[10px] text-gray-400">Unit Cabang Aktif</div>
                    </div>
                </div>
                <?php else: 
                    // HITUNGAN DASHBOARD UTAMA
                    $tm = $conn->query("SELECT COUNT(*) as c FROM users")->fetch_assoc()['c'];
                    $os = $conn->query("SELECT SUM(amount) as s FROM transactions WHERE type='buy_stokis' AND status='success'")->fetch_assoc()['s'] ?? 0;
                    $oc = $conn->query("SELECT SUM(amount) as s FROM transactions WHERE type='buy_crowd' AND status='success'")->fetch_assoc()['s'] ?? 0;
                    $ok = $conn->query("SELECT SUM(amount) as s FROM transactions WHERE type='buy_crypto' AND status='success'")->fetch_assoc()['s'] ?? 0;
                ?>
                <h2 class="text-2xl font-bold mb-6">Dashboard Overview</h2>
                <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                    <div class="card-bank card-shimmer rounded-2xl p-6 text-white h-48 flex flex-col justify-between relative group">
                        <div class="absolute -right-6 -top-6 w-24 h-24 bg-blue-500/20 rounded-full blur-xl group-hover:bg-blue-500/40 transition"></div>
                        <div class="flex justify-between items-start z-10">
                            <div><p class="text-xs font-bold text-blue-300 tracking-widest">TOTAL MEMBER</p><h3 class="text-4xl font-bold mt-2"><?php echo number_format($tm); ?></h3></div>
                            <div class="p-3 bg-blue-500/20 rounded-lg"><i class="fas fa-users text-blue-400"></i></div>
                        </div>
                        <div class="z-10 mt-4"><div class="w-full bg-slate-700 h-1 rounded-full overflow-hidden"><div class="bg-blue-500 h-full w-[70%]"></div></div><p class="text-[10px] mt-2 text-gray-400">Active Users Growth</p></div>
                    </div>
                    <div class="card-bank card-shimmer rounded-2xl p-6 text-white h-48 flex flex-col justify-between relative group">
                        <div class="absolute -right-6 -top-6 w-24 h-24 bg-emerald-500/20 rounded-full blur-xl group-hover:bg-emerald-500/40 transition"></div>
                        <div class="flex justify-between items-start z-10">
                            <div><p class="text-xs font-bold text-emerald-300 tracking-widest">OMSET STOKIS</p><h3 class="text-2xl font-bold mt-2"><?php echo formatRupiah($os); ?></h3></div>
                            <div class="p-3 bg-emerald-500/20 rounded-lg"><i class="fas fa-cubes text-emerald-400"></i></div>
                        </div>
                        <div class="z-10 mt-4"><p class="text-[10px] text-emerald-400 border border-emerald-500/30 px-2 py-1 rounded w-fit">+ Product Sales</p></div>
                    </div>
                    <div class="card-bank card-shimmer rounded-2xl p-6 text-white h-48 flex flex-col justify-between relative group">
                        <div class="absolute -right-6 -top-6 w-24 h-24 bg-purple-500/20 rounded-full blur-xl group-hover:bg-purple-500/40 transition"></div>
                        <div class="flex justify-between items-start z-10">
                            <div><p class="text-xs font-bold text-purple-300 tracking-widest">OMSET CROWD</p><h3 class="text-2xl font-bold mt-2"><?php echo formatRupiah($oc); ?></h3></div>
                            <div class="p-3 bg-purple-500/20 rounded-lg"><i class="fas fa-users-cog text-purple-400"></i></div>
                        </div>
                        <div class="z-10 mt-4"><p class="text-[10px] text-purple-400 border border-purple-500/30 px-2 py-1 rounded w-fit">+ Investment Pools</p></div>
                    </div>
                    <div class="card-bank card-shimmer rounded-2xl p-6 text-white h-48 flex flex-col justify-between relative group">
                        <div class="absolute -right-6 -top-6 w-24 h-24 bg-orange-500/20 rounded-full blur-xl group-hover:bg-orange-500/40 transition"></div>
                        <div class="flex justify-between items-start z-10">
                            <div><p class="text-xs font-bold text-orange-300 tracking-widest">OMSET CRYPTO</p><h3 class="text-2xl font-bold mt-2"><?php echo formatRupiah($ok); ?></h3></div>
                            <div class="p-3 bg-orange-500/20 rounded-lg"><i class="fab fa-bitcoin text-orange-400"></i></div>
                        </div>
                        <div class="z-10 mt-4"><p class="text-[10px] text-orange-400 border border-orange-500/30 px-2 py-1 rounded w-fit">+ Mining & Staking</p></div>
                    </div>
                </div>
                <?php endif; ?>
            
            <?php elseif ($page == 'broadcast_wd'): 
                // AMBIL STATUS WD SAAT INI
                $wd_q = $conn->query("SELECT setting_value FROM settings WHERE setting_key='withdraw_status'");
                $wd_status = ($wd_q->num_rows > 0) ? $wd_q->fetch_assoc()['setting_value'] : 'on';
            ?>
                <h2 class="text-2xl font-bold mb-6">Broadcast & WD Switch</h2>
                
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    <div class="lg:col-span-1 space-y-8">
                        
                        <div class="bg-white dark:bg-slate-800 p-6 rounded-2xl shadow-sm border border-gray-200 dark:border-slate-700">
                            <h3 class="font-bold text-lg mb-4 text-slate-700 dark:text-gray-200">Status Fitur Withdraw</h3>
                            <form method="POST">
                                <input type="hidden" name="admin_action" value="toggle_withdraw">
                                
                                <?php if($wd_status == 'on'): ?>
                                    <button type="submit" name="status" value="off" class="w-full group flex items-center justify-between bg-emerald-500/20 border border-emerald-500 px-5 py-3 rounded-xl cursor-pointer hover:bg-emerald-500/30 transition">
                                        <div class="text-left">
                                            <p class="text-sm font-bold text-emerald-400 uppercase">System Active</p>
                                            <p class="text-[10px] text-emerald-300">Klik untuk Non-aktifkan</p>
                                        </div>
                                        <div class="w-10 h-6 bg-emerald-500 rounded-full relative shadow-inner">
                                            <div class="absolute right-1 top-1 w-4 h-4 bg-white rounded-full shadow-md"></div>
                                        </div>
                                    </button>
                                <?php else: ?>
                                    <button type="submit" name="status" value="on" class="w-full group flex items-center justify-between bg-red-500/20 border border-red-500 px-5 py-3 rounded-xl cursor-pointer hover:bg-red-500/30 transition">
                                        <div class="text-left">
                                            <p class="text-sm font-bold text-red-400 uppercase">System Offline</p>
                                            <p class="text-[10px] text-red-300">Klik untuk Aktifkan</p>
                                        </div>
                                        <div class="w-10 h-6 bg-gray-600 rounded-full relative shadow-inner">
                                            <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full shadow-md"></div>
                                        </div>
                                    </button>
                                <?php endif; ?>
                            </form>
                        </div>

                        <div class="bg-white dark:bg-slate-800 p-6 rounded-2xl shadow-sm border border-gray-200 dark:border-slate-700">
                            <h3 class="font-bold text-lg mb-4 flex items-center gap-2 text-slate-700 dark:text-gray-200">
                                <i class="fas fa-pen-nib text-purple-500"></i> Tulis Pesan Baru
                            </h3>
                            <form method="POST" class="space-y-4">
                                <input type="hidden" name="admin_action" value="broadcast_add">
                                <div>
                                    <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Judul Pesan</label>
                                    <input type="text" name="title" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-300 dark:border-slate-600 p-3 rounded-xl focus:outline-none focus:ring-2 focus:ring-purple-500 transition" placeholder="Contoh: Maintenance Sistem" required>
                                </div>
                                <div>
                                    <label class="block text-xs font-bold text-gray-500 uppercase mb-1">Isi Pesan</label>
                                    <textarea name="message" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-300 dark:border-slate-600 p-3 rounded-xl h-32 focus:outline-none focus:ring-2 focus:ring-purple-500 transition resize-none" placeholder="Tulis informasi..." required></textarea>
                                </div>
                                <button type="submit" class="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-3 rounded-xl shadow-lg transition transform active:scale-95">
                                    <i class="fas fa-paper-plane mr-2"></i> Kirim Broadcast
                                </button>
                            </form>
                        </div>
                    </div>

                    <div class="lg:col-span-2">
                        <div class="bg-white dark:bg-slate-800 rounded-2xl shadow-sm border border-gray-200 dark:border-slate-700 overflow-hidden">
                            <div class="p-6 border-b border-gray-200 dark:border-slate-700 bg-gray-50/50 dark:bg-slate-900/50">
                                <h3 class="font-bold text-lg text-slate-700 dark:text-gray-200">Riwayat Pesan Terkirim</h3>
                            </div>
                            <div class="overflow-x-auto">
                                <table class="w-full text-left">
                                    <thead class="bg-gray-50 dark:bg-slate-900 text-gray-500 text-xs uppercase font-bold">
                                        <tr>
                                            <th class="p-4 w-32">Tanggal</th>
                                            <th class="p-4 w-1/4">Judul</th>
                                            <th class="p-4">Isi Pesan</th>
                                            <th class="p-4 text-center w-20">Aksi</th>
                                        </tr>
                                    </thead>
                                    <tbody class="divide-y divide-gray-200 dark:divide-slate-700">
                                        <?php 
                                        $msgs = $conn->query("SELECT * FROM admin_messages ORDER BY created_at DESC");
                                        if($msgs->num_rows > 0):
                                            while($m = $msgs->fetch_assoc()): 
                                        ?>
                                        <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/50 transition">
                                            <td class="p-4 text-xs text-gray-500">
                                                <i class="far fa-clock mr-1"></i> <?php echo date('d M Y', strtotime($m['created_at'])); ?><br>
                                                <span class="ml-4 text-[10px]"><?php echo date('H:i', strtotime($m['created_at'])); ?></span>
                                            </td>
                                            <td class="p-4 font-bold text-slate-700 dark:text-gray-300"><?php echo $m['title']; ?></td>
                                            <td class="p-4 text-sm text-slate-600 dark:text-gray-400 leading-relaxed"><?php echo nl2br(substr($m['message'], 0, 100)) . (strlen($m['message'])>100 ? '...' : ''); ?></td>
                                            <td class="p-4 text-center">
                                                <form method="POST" onsubmit="return confirm('Hapus pesan ini?');">
                                                    <input type="hidden" name="admin_action" value="broadcast_delete">
                                                    <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                                                    <button type="submit" class="w-8 h-8 rounded-full bg-red-100 dark:bg-red-900/30 text-red-500 hover:bg-red-500 hover:text-white transition flex items-center justify-center">
                                                        <i class="fas fa-trash-alt text-sm"></i>
                                                    </button>
                                                </form>
                                            </td>
                                        </tr>
                                        <?php endwhile; 
                                        else: ?>
                                        <tr><td colspan="4" class="p-8 text-center text-gray-400">Belum ada pesan broadcast.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

            <?php elseif ($page == 'members'): 
                $total_res = $conn->query("SELECT COUNT(*) as c FROM users")->fetch_assoc()['c'];
                $total_page = ceil($total_res / $limit);
                $sql = "SELECT u.*, s.username as sponsor_name FROM users u LEFT JOIN users s ON u.upline_id = s.id ORDER BY u.id DESC LIMIT $offset, $limit";
                $members = $conn->query($sql);
            ?>
                <h2 class="text-2xl font-bold mb-4">Data Member</h2>
                <div class="bg-white dark:bg-slate-800 rounded-xl overflow-x-auto shadow-sm border border-gray-200 dark:border-slate-700">
                    <table class="w-full text-left whitespace-nowrap">
                        <thead><tr><th>Member</th><th>Sponsor</th><th class="text-center">Downline</th><th>Investasi Active</th><th>Status</th><th>Aksi</th></tr></thead>
                        <tbody>
                            <?php while($row = $members->fetch_assoc()): 
                                $dl = $conn->query("SELECT COUNT(*) as c FROM users WHERE upline_id = ".$row['id'])->fetch_assoc()['c'];
                                $inv = [];
                                $qInv = $conn->query("SELECT DISTINCT type FROM transactions WHERE user_id=".$row['id']." AND type IN ('buy_stokis','buy_crowd','buy_crypto') AND status='success'");
                                while($ri = $qInv->fetch_assoc()) { $label = str_replace('buy_', '', strtoupper($ri['type'])); $inv[] = "<span class='bg-blue-900 text-blue-200 px-1 rounded text-[10px]'>$label</span>"; }
                                $inv_str = empty($inv) ? '-' : implode(' ', $inv);
                                $is_blocked = (isset($row['status']) && $row['status'] == 'blocked');
                                $badge = ($is_blocked) ? "<span class='bg-red-600 text-white px-2 py-1 rounded text-xs font-bold animate-pulse'>BLOCK</span>" : "<span class='bg-green-600 text-white px-2 py-1 rounded text-xs font-bold'>ACTIVE</span>";
                            ?>
                            <tr class="hover:bg-slate-700/50">
                                <td><b><?php echo $row['full_name']; ?></b><br><span class="text-xs text-primary"><?php echo $row['username']; ?></span></td>
                                <td><?php echo $row['sponsor_name'] ?? '-'; ?></td>
                                <td class="text-center font-bold"><?php echo $dl; ?></td>
                                <td><?php echo $inv_str; ?></td>
                                <td><?php echo $badge; ?></td>
                                <td class="flex gap-2">
                                    <a href="?act=login_as&uid=<?php echo $row['id']; ?>" target="_blank" class="bg-blue-500 text-white p-1 rounded"><i class="fas fa-key"></i></a>
                                    <?php if(!$is_blocked): ?>
                                        <a href="?act=block&uid=<?php echo $row['id']; ?>" onclick="return confirm('Block User?')" class="bg-yellow-500 text-white p-1 rounded"><i class="fas fa-ban"></i></a>
                                    <?php else: ?>
                                        <a href="?act=unblock&uid=<?php echo $row['id']; ?>" onclick="return confirm('Unblock User?')" class="bg-green-500 text-white p-1 rounded"><i class="fas fa-check"></i></a>
                                    <?php endif; ?>
                                    <a href="?act=delete&uid=<?php echo $row['id']; ?>" onclick="return confirm('Hapus?')" class="bg-red-500 text-white p-1 rounded"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 flex justify-center">
                    <?php for($i=1; $i<=$total_page; $i++): ?>
                        <a href="?page=members&p=<?php echo $i; ?>" class="pagination-btn <?php echo ($p==$i)?'pagination-active':''; ?>"><?php echo $i; ?></a>
                    <?php endfor; ?>
                </div>

            <?php elseif ($page == 'banners'): ?>
                <h2 class="text-2xl font-bold mb-4">Kelola Banner</h2>
                <div class="bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm mb-6 w-full md:w-1/2">
                    <form method="POST" enctype="multipart/form-data">
                        <input type="hidden" name="upload_banner" value="1">
                        <label class="block text-sm font-bold mb-2">Upload Banner Baru</label>
                        <input type="file" name="banner_img" required class="w-full bg-slate-900 border border-slate-700 rounded p-2 mb-2">
                        <button type="submit" class="bg-pink-500 text-white px-4 py-2 rounded font-bold">Upload</button>
                    </form>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <?php $qb = $conn->query("SELECT * FROM banners ORDER BY id DESC"); while($rb = $qb->fetch_assoc()): ?>
                    <div class="relative group rounded-xl overflow-hidden shadow-lg border border-slate-700">
                        <img src="../uploads/banners/<?php echo $rb['image']; ?>" class="w-full h-40 object-cover">
                        <a href="?act=del_banner&bid=<?php echo $rb['id']; ?>" onclick="return confirm('Hapus Banner?')" class="absolute top-2 right-2 bg-red-600 text-white w-8 h-8 flex items-center justify-center rounded-full opacity-0 group-hover:opacity-100 transition"><i class="fas fa-trash"></i></a>
                    </div>
                    <?php endwhile; ?>
                </div>

            <?php elseif ($page == 'laporan'): 
                // LOGIC LAPORAN (Menghitung Total Pendapatan & Pengeluaran)
                $qInc1 = $conn->query("SELECT SUM(amount) * 0.025 as total FROM transactions WHERE type='withdraw' AND status='success'");
                $inc_wd = $qInc1->fetch_assoc()['total'] ?? 0;
                $qInc2 = $conn->query("SELECT SUM(amount) * 0.025 as total FROM transactions WHERE type IN ('buy_stokis','buy_crowd','buy_crypto') AND status='success'");
                $inc_proj = $qInc2->fetch_assoc()['total'] ?? 0;
                $qInc3 = $conn->query("SELECT SUM(amount) * 0.025 as total FROM transactions WHERE type IN ('transfer_out','swap') AND status='success'");
                $inc_trx = $qInc3->fetch_assoc()['total'] ?? 0;
                
                // ✅ BAGIAN INI SUDAH BENAR UNTUK MENGHITUNG PENDAPATAN PAKET STARTER
                $inc_starter = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE type IN ('register_starter', 'buy_starter') AND status='success'")->fetch_assoc()['total'] ?? 0;
                $inc_upgrade = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE type='upgrade_starter' AND status='success'")->fetch_assoc()['total'] ?? 0;
                $inc_manual = $conn->query("SELECT SUM(amount) as total FROM company_finances WHERE type='income'")->fetch_assoc()['total'] ?? 0;
                $TOTAL_PENDAPATAN = $inc_wd + $inc_proj + $inc_trx + $inc_starter + $inc_upgrade + $inc_manual;

                $exp_bonus = $conn->query("SELECT SUM(amount) as total FROM transactions WHERE type LIKE 'bonus%' AND status='success'")->fetch_assoc()['total'] ?? 0;
                $exp_manual = $conn->query("SELECT SUM(amount) as total FROM company_finances WHERE type='expense'")->fetch_assoc()['total'] ?? 0;
                $TOTAL_PENGELUARAN = $exp_bonus + $exp_manual;
                $NET_PROFIT = $TOTAL_PENDAPATAN - $TOTAL_PENGELUARAN;
            ?>
                <div class="flex justify-between items-center mb-6 no-print">
                    <h2 class="text-2xl font-bold">Laporan Keuangan</h2>
                    <button onclick="window.print()" class="bg-blue-600 text-white px-4 py-2 rounded-lg shadow"><i class="fas fa-print mr-2"></i>PDF / Print</button>
                </div>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                    <div class="bg-green-100 dark:bg-green-900/30 p-4 rounded-xl border border-green-500 text-green-700 dark:text-green-400"><h3 class="text-sm font-bold uppercase">Total Pendapatan</h3><p class="text-2xl font-bold"><?php echo formatRupiah($TOTAL_PENDAPATAN); ?></p></div>
                    <div class="bg-red-100 dark:bg-red-900/30 p-4 rounded-xl border border-red-500 text-red-700 dark:text-red-400"><h3 class="text-sm font-bold uppercase">Total Pengeluaran</h3><p class="text-2xl font-bold"><?php echo formatRupiah($TOTAL_PENGELUARAN); ?></p></div>
                    <div class="bg-blue-100 dark:bg-blue-900/30 p-4 rounded-xl border border-blue-500 text-blue-700 dark:text-blue-400"><h3 class="text-sm font-bold uppercase">Pendapatan Bersih (Netto)</h3><p class="text-2xl font-bold"><?php echo formatRupiah($NET_PROFIT); ?></p></div>
                </div>
                <div class="bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm mb-6">
                    <h3 class="font-bold text-lg mb-4 text-green-500 border-b pb-2">A. Rincian Pendapatan</h3>
                    <table class="w-full text-sm">
                        <tr><td>Fee Admin (Withdrawal) 2.5%</td><td class="text-right font-mono"><?php echo formatRupiah($inc_wd); ?></td></tr>
                        <tr><td>Fee Admin (Project Inv) 2.5%</td><td class="text-right font-mono"><?php echo formatRupiah($inc_proj); ?></td></tr>
                        <tr><td>Fee Admin (Transaksi) 2.5%</td><td class="text-right font-mono"><?php echo formatRupiah($inc_trx); ?></td></tr>
                        <tr><td>Paket Starter (300k)</td><td class="text-right font-mono"><?php echo formatRupiah($inc_starter); ?></td></tr>
                        <tr><td>Paket Upgrade (500k)</td><td class="text-right font-mono"><?php echo formatRupiah($inc_upgrade); ?></td></tr>
                        <tr><td>Profit Pengelolaan Project (Manual)</td><td class="text-right font-mono"><?php echo formatRupiah($inc_manual); ?></td></tr>
                        <tr class="font-bold border-t"><td class="pt-2">TOTAL PENDAPATAN</td><td class="text-right pt-2"><?php echo formatRupiah($TOTAL_PENDAPATAN); ?></td></tr>
                    </table>
                </div>
                <div class="bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm mb-6">
                    <h3 class="font-bold text-lg mb-4 text-red-500 border-b pb-2">B. Rincian Pengeluaran</h3>
                    <table class="w-full text-sm">
                        <tr><td>Pembayaran Bonus (System)</td><td class="text-right font-mono"><?php echo formatRupiah($exp_bonus); ?></td></tr>
                        <?php $qManExp = $conn->query("SELECT category, SUM(amount) as t FROM company_finances WHERE type='expense' GROUP BY category"); while($rm = $qManExp->fetch_assoc()): ?>
                        <tr><td><?php echo $rm['category']; ?></td><td class="text-right font-mono"><?php echo formatRupiah($rm['t']); ?></td></tr>
                        <?php endwhile; ?>
                        <tr class="font-bold border-t"><td class="pt-2">TOTAL PENGELUARAN</td><td class="text-right pt-2"><?php echo formatRupiah($TOTAL_PENGELUARAN); ?></td></tr>
                    </table>
                </div>
                <div class="bg-white dark:bg-slate-800 p-6 rounded-xl shadow-sm border border-orange-500/30 no-print">
                    <h3 class="font-bold text-lg mb-4"><i class="fas fa-edit mr-2"></i>Input Keuangan Manual</h3>
                    <form method="POST" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                        <input type="hidden" name="save_finance" value="1">
                        <select name="type" class="p-3 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded">
                            <option value="expense">Pengeluaran</option>
                            <option value="income">Pendapatan Lain</option>
                        </select>
                        <select name="category" class="p-3 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded">
                            <option value="Biaya Admin Office">Biaya Admin Office</option>
                            <option value="Biaya Support/Promosi">Biaya Support/Promosi</option>
                            <option value="Biaya Event">Biaya Event</option>
                            <option value="Biaya Legalitas">Biaya Legalitas</option>
                            <option value="Biaya Produksi">Biaya Produksi</option>
                            <option value="Biaya Crowdfunding">Biaya Crowdfunding</option>
                            <option value="Biaya Crypto">Biaya Crypto</option>
                            <option value="Biaya Lain-lain">Biaya Lain-lain</option>
                            <option value="Profit Project">Profit Project (Pendapatan)</option>
                        </select>
                        <input type="number" name="amount" placeholder="Nominal" class="p-3 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded" required>
                        <input type="text" name="description" placeholder="Keterangan Detail" class="p-3 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded lg:col-span-2">
                        <input type="date" name="date_recorded" value="<?php echo date('Y-m-d'); ?>" class="p-3 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded">
                        <button type="submit" class="bg-primary text-white font-bold p-3 rounded lg:col-span-3">Simpan Data</button>
                    </form>
                </div>

            <?php elseif (in_array($page, ['approve_topup', 'approve_withdraw', 'approve_paket', 'approve_starter', 'approve_upgrade'])):
                $type_map = [
                    'approve_topup' => "'topup'",
                    'approve_withdraw' => "'withdraw'",
                    'approve_paket' => "'buy_stokis','buy_crowd','buy_crypto'", // FILTER KHUSUS STOKIS, CROWD, CRYPTO
                    'approve_starter' => "'register_starter','buy_starter'", 
                    'approve_upgrade' => "'upgrade_starter'"
                ];
                $title_map = [
                    'approve_topup' => "Approval Top Up",
                    'approve_withdraw' => "Approval Withdraw",
                    'approve_paket' => "Approval Paket Bisnis", // JUDUL
                    'approve_starter' => "Approval Beli Starter (Aktivasi Member)",
                    'approve_upgrade' => "Approval Upgrade Starter (500K)"
                ];
                $filter = $type_map[$page];
                $title_page = $title_map[$page];
                
                $count_q = $conn->query("SELECT COUNT(*) as c FROM transactions WHERE type IN ($filter) AND status='pending'")->fetch_assoc()['c'];
                $total_page = ceil($count_q / $limit);
                
                // MENGAMBIL DATA TRANSAKSI
                $sql = "SELECT t.*, u.username, u.full_name FROM transactions t JOIN users u ON t.user_id = u.id WHERE t.type IN ($filter) AND t.status = 'pending' ORDER BY t.created_at DESC LIMIT $offset, $limit";
                $data = $conn->query($sql);
            ?>
                <h2 class="text-2xl font-bold mb-6"><?php echo $title_page; ?></h2>
                <div class="bg-white dark:bg-slate-800 rounded-xl overflow-x-auto shadow-sm border border-gray-200 dark:border-slate-700">
                    <table class="w-full whitespace-nowrap">
                        <thead><tr><th>Waktu/Tanggal</th><th>Nama</th><th>Username</th><th>Description</th><th>Jenis Pembayaran</th><th>Nominal</th><th>Bukti</th><th>Status / Aksi</th></tr></thead>
                        <tbody>
                            <?php if($data->num_rows == 0): ?><tr><td colspan="8" class="text-center py-4 text-gray-500">Data Kosong</td></tr><?php endif; ?>
                            <?php while($row = $data->fetch_assoc()): 
                                // Clean up type label (e.g. buy_stokis -> STOKIS)
                                $clean_type = strtoupper(str_replace('buy_', '', $row['type']));
                            ?>
                            <tr class="hover:bg-slate-700/50">
                                <td><?php echo date('d/m/Y H:i', strtotime($row['created_at'])); ?></td>
                                <td><?php echo $row['full_name']; ?></td>
                                <td class="text-primary"><?php echo $row['username']; ?></td>
                                <td class="whitespace-normal min-w-[200px]"><?php echo $row['description']; ?></td>
                                <td><span class="uppercase text-xs bg-slate-700 text-white px-2 py-1 rounded"><?php echo $clean_type; ?></span></td>
                                <td class="font-bold"><?php echo formatRupiah($row['amount']); ?></td>
                                <td><?php if(isset($row['proof_image']) && !empty($row['proof_image'])): ?><a href="../uploads/<?php echo $row['proof_image']; ?>" target="_blank" class="text-blue-400 underline text-xs">Lihat</a><?php else: ?> - <?php endif; ?></td>
                                <td class="flex gap-2">
                                    <a href="?act=approve&tid=<?php echo $row['id']; ?>" class="bg-green-500 text-white px-3 py-1 rounded text-xs">Approve</a>
                                    <a href="?act=reject&tid=<?php echo $row['id']; ?>" class="bg-red-500 text-white px-3 py-1 rounded text-xs">Tolak</a>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
                <div class="mt-4 flex justify-center">
                    <?php for($i=1; $i<=$total_page; $i++): ?>
                        <a href="?page=<?php echo $page; ?>&p=<?php echo $i; ?>" class="pagination-btn <?php echo ($p==$i)?'pagination-active':''; ?>"><?php echo $i; ?></a>
                    <?php endfor; ?>
                </div>

            <?php elseif ($page == 'manage_admins' && $admin_role == 'super_admin'): 
                $admins = $conn->query("SELECT * FROM admins ORDER BY id DESC"); ?>
                <h2 class="text-2xl font-bold mb-6">Kelola Administrator</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="bg-white dark:bg-slate-800 rounded-xl p-4 shadow-sm border border-gray-200 dark:border-slate-700">
                        <h3 class="font-bold mb-4">Daftar Admin</h3>
                        <div class="overflow-x-auto">
                            <table class="w-full text-sm text-left whitespace-nowrap">
                                <thead><tr><th>Username</th><th>Nama</th><th>Role</th><th>Aksi</th></tr></thead>
                                <tbody>
                                    <?php while($row = $admins->fetch_assoc()): ?>
                                    <tr class="border-b dark:border-slate-700">
                                        <td class="font-bold"><?php echo $row['username']; ?></td>
                                        <td><?php echo $row['full_name']; ?></td>
                                        <td><span class="px-2 py-0.5 rounded text-[10px] bg-slate-700 text-white uppercase"><?php echo str_replace('_', ' ', $row['role']); ?></span></td>
                                        <td><?php if($row['id'] != $_SESSION['admin_id']): ?><a href="?act=del_admin&aid=<?php echo $row['id']; ?>" onclick="return confirm('Hapus Admin?')" class="text-red-500 hover:text-red-700"><i class="fas fa-trash"></i></a><?php endif; ?></td>
                                    </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="bg-white dark:bg-slate-800 rounded-xl p-6 shadow-sm border border-gray-200 dark:border-slate-700 h-fit">
                        <h3 class="font-bold mb-4 text-purple-500">Tambah Admin Baru</h3>
                        <form method="POST" class="space-y-4">
                            <input type="hidden" name="create_admin" value="1">
                            <div><label class="text-xs font-bold text-gray-500">Username</label><input type="text" name="username" required class="w-full bg-slate-900 border border-slate-600 rounded p-2"></div>
                            <div><label class="text-xs font-bold text-gray-500">Password</label><input type="password" name="password" required class="w-full bg-slate-900 border border-slate-600 rounded p-2"></div>
                            <div><label class="text-xs font-bold text-gray-500">Nama Lengkap</label><input type="text" name="full_name" required class="w-full bg-slate-900 border border-slate-600 rounded p-2"></div>
                            <div><label class="text-xs font-bold text-gray-500">Role</label>
                                <select name="role" class="w-full bg-slate-900 border border-slate-600 rounded p-2">
                                    <option value="secretary">Secretary</option>
                                    <option value="branch">Branch</option>
                                    <option value="super_admin">Super Admin</option>
                                </select>
                            </div>
                            <button type="submit" class="w-full bg-purple-600 text-white font-bold py-2 rounded">Buat Akun</button>
                        </form>
                    </div>
                </div>

            <?php elseif ($page == 'settings' && $admin_role == 'super_admin'): ?>
                <h2 class="text-2xl font-bold mb-6">Pengaturan Sistem</h2>
                <form method="POST" action="" enctype="multipart/form-data" class="space-y-6">
                    <input type="hidden" name="save_settings" value="1">

                    <div class="bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-sm border border-gray-200 dark:border-slate-700">
                        <h3 class="font-bold text-lg mb-4 text-purple-500 border-b dark:border-slate-700 pb-2">Setting Website</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div><label class="block text-xs font-bold text-gray-500 mb-1">URL Website</label><input type="text" name="site_url" value="<?php echo getSet('site_url', $settings); ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-300 dark:border-slate-600 rounded-lg p-3"></div>
                            <div><label class="block text-xs font-bold text-gray-500 mb-1">Logo Website</label><input type="file" name="site_logo" class="w-full bg-gray-50 dark:bg-slate-900 border border-gray-300 dark:border-slate-600 rounded-lg p-2 text-xs"></div>
                        </div>
                    </div>

                    <div class="bg-white dark:bg-slate-800 rounded-2xl p-6 shadow-sm border border-gray-200 dark:border-slate-700">
                        <h3 class="font-bold text-lg mb-4 text-primary border-b dark:border-slate-700 pb-2">Pengaturan Fee & Bonus</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div class="space-y-3">
                                <h4 class="font-bold text-sm text-gray-400">Fee Transaksi (%)</h4>
                                <div class="flex items-center gap-2"><span class="w-24 text-xs">Fee Transfer</span><input type="number" step="0.01" name="fee_send_percent" value="<?php echo getSet('fee_send_percent', $settings); ?>" class="flex-1 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2" placeholder="2.5"></div>
                                <div class="flex items-center gap-2"><span class="w-24 text-xs">Fee Swap</span><input type="number" step="0.01" name="fee_swap_percent" value="<?php echo getSet('fee_swap_percent', $settings); ?>" class="flex-1 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2" placeholder="2.5"></div>
                                <div class="flex items-center gap-2"><span class="w-24 text-xs">Fee Withdraw</span><input type="number" step="0.01" name="fee_withdraw_percent" value="<?php echo getSet('fee_withdraw_percent', $settings); ?>" class="flex-1 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2" placeholder="2.5"></div>
                            </div>
                            <div class="space-y-3">
                                <h4 class="font-bold text-sm text-gray-400">Bonus Sponsor (%)</h4>
                                <div class="flex items-center gap-2"><span class="w-24 text-xs">Starter</span><input type="number" step="0.01" name="sponsor_starter" value="<?php echo getSet('sponsor_starter', $settings); ?>" class="flex-1 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2"></div>
                                <div class="flex items-center gap-2"><span class="w-24 text-xs">Stokis</span><input type="number" step="0.01" name="sponsor_stokis" value="<?php echo getSet('sponsor_stokis', $settings); ?>" class="flex-1 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2"></div>
                                <div class="flex items-center gap-2"><span class="w-24 text-xs">Crowd</span><input type="number" step="0.01" name="sponsor_crowd" value="<?php echo getSet('sponsor_crowd', $settings); ?>" class="flex-1 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2"></div>
                                <div class="flex items-center gap-2"><span class="w-24 text-xs">Crypto</span><input type="number" step="0.01" name="sponsor_crypto" value="<?php echo getSet('sponsor_crypto', $settings); ?>" class="flex-1 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2"></div>
                            </div>
                        </div>

                        <div class="mt-6">
                            <h4 class="font-bold text-sm text-gray-400 mb-2">Royalty Level (%)</h4>
                            <div class="grid grid-cols-2 md:grid-cols-5 gap-3">
                                <?php for($i=1; $i<=10; $i++): ?>
                                    <div>
                                        <span class="text-[10px] font-bold text-gray-500 block mb-1">Level <?php echo $i; ?> (%)</span>
                                        <input type="number" step="0.1" name="royalty_l<?php echo $i; ?>" value="<?php echo getSet('royalty_l'.$i, $settings); ?>" class="w-full bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2 text-center text-xs">
                                    </div>
                                <?php endfor; ?>
                            </div>
                        </div>

                         <div class="mt-6">
                            <h4 class="font-bold text-sm text-gray-400 mb-2">Bonus Reward</h4>
                            <?php for($i=1; $i<=6; $i++): ?>
                            <div class="flex gap-2 mb-2">
                                <span class="text-xs w-8 pt-2 font-bold">#<?php echo $i; ?></span>
                                <input type="number" name="reward_<?php echo $i; ?>_target" value="<?php echo getSet('reward_'.$i.'_target', $settings); ?>" placeholder="Target" class="w-1/3 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2 text-xs">
                                <input type="text" name="reward_<?php echo $i; ?>_prize" value="<?php echo getSet('reward_'.$i.'_prize', $settings); ?>" placeholder="Hadiah" class="flex-1 bg-gray-50 dark:bg-slate-900 border border-slate-600 rounded p-2 text-xs">
                            </div>
                            <?php endfor; ?>
                        </div>
                    </div>
                    <button type="submit" class="w-full bg-primary hover:bg-emerald-600 text-white font-bold py-3 rounded-xl shadow-lg transition">Simpan Semua Pengaturan</button>
                </form>

            <?php endif; ?>

        </div>
    </div>

    <script> <?php echo $swal_script; ?> </script>
</body>
</html>