<?php
session_start();
// Menghubungkan ke database (posisi file config ada di folder utama, jadi naik satu level '../')
include '../config.php'; 

// ==========================================
// 1. CEK SESSION ADMIN
// ==========================================
// Aktifkan baris di bawah ini jika Anda sudah membuat sistem login khusus Admin
// if(!isset($_SESSION['admin_logged_in'])) { header("Location: ../login.php"); exit(); }

// ==========================================
// 2. HANDLE LOGIC (POST REQUESTS)
// ==========================================

// Mendapatkan nama file saat ini secara dinamis untuk redirect (agar tidak error 404)
$current_file = basename($_SERVER['PHP_SELF']);

// A. HANDLE BROADCAST (TAMBAH PESAN BARU)
if (isset($_POST['action']) && $_POST['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')");
    }
    header("Location: $current_file?page=broadcast"); exit();
}

// B. HANDLE BROADCAST (HAPUS PESAN)
if (isset($_POST['action']) && $_POST['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");
    
    header("Location: $current_file?page=broadcast"); exit();
}

// C. HANDLE WITHDRAW SETTINGS (ON/OFF SWITCH)
if (isset($_POST['action']) && $_POST['action'] == 'toggle_withdraw') {
    $status = $_POST['status']; // 'on' atau 'off'
    
    $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')");
    }
    header("Location: $current_file?page=withdraw"); exit();
}

// D. HANDLE APPROVE WITHDRAW (SET SUCCESS)
if (isset($_POST['action']) && $_POST['action'] == 'approve_wd') {
    $wd_id = intval($_POST['wd_id']);
    $conn->query("UPDATE transactions SET status = 'success' WHERE id = $wd_id");
    header("Location: $current_file?page=withdraw"); exit();
}

// ==========================================
// 3. PERSIAPAN DATA HALAMAN
// ==========================================
$page = isset($_GET['page']) ? $_GET['page'] : 'broadcast'; 

// Ambil Status Withdraw
$wd_setting_query = $conn->query("SELECT setting_value FROM settings WHERE setting_key='withdraw_status'");
$wd_status = ($wd_setting_query->num_rows > 0) ? $wd_setting_query->fetch_assoc()['setting_value'] : 'on';
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Broadcast & WD Switch - Admin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&display=swap');
        body { font-family: 'Inter', sans-serif; }
    </style>
</head>
<body class="bg-gray-100 text-slate-800">

    <div class="flex min-h-screen">
        
        <aside class="w-64 bg-slate-900 text-white flex flex-col fixed h-full shadow-2xl z-10">
            <div class="p-6 border-b border-slate-700 flex items-center gap-3">
                <i class="fas fa-shield-alt text-emerald-500 text-2xl"></i>
                <span class="text-xl font-bold tracking-wide">Admin Panel</span>
            </div>
            
            <nav class="flex-1 p-4 space-y-2 mt-4">
                <a href="?page=broadcast" class="flex items-center gap-3 p-3 rounded-xl transition duration-200 <?php echo $page=='broadcast' ? 'bg-emerald-600 shadow-lg text-white' : 'text-slate-400 hover:bg-slate-800 hover:text-white'; ?>">
                    <i class="fas fa-bullhorn w-6 text-center"></i> 
                    <span class="font-semibold">Broadcast Pesan</span>
                </a>
                
                <a href="?page=withdraw" class="flex items-center gap-3 p-3 rounded-xl transition duration-200 <?php echo $page=='withdraw' ? 'bg-emerald-600 shadow-lg text-white' : 'text-slate-400 hover:bg-slate-800 hover:text-white'; ?>">
                    <i class="fas fa-money-bill-wave w-6 text-center"></i> 
                    <span class="font-semibold">Approval Withdraw</span>
                </a>

                <div class="mt-8 border-t border-slate-700 pt-4">
                     <a href="../logout.php" class="flex items-center gap-3 p-3 rounded-xl text-red-400 hover:bg-red-500/10 hover:text-red-500 transition">
                        <i class="fas fa-sign-out-alt w-6 text-center"></i>
                        <span class="font-semibold">Logout</span>
                    </a>
                </div>
            </nav>
        </aside>

        <main class="flex-1 ml-64 p-8">
            
            <div class="mb-8 flex justify-between items-center">
                <div>
                    <h1 class="text-2xl font-bold text-slate-800 capitalize"><?php echo str_replace('_', ' ', $page); ?></h1>
                    <p class="text-sm text-slate-500">Halaman: Broadcast & WD Switch</p>
                </div>
                <div class="w-10 h-10 rounded-full bg-emerald-100 flex items-center justify-center text-emerald-600 font-bold border border-emerald-200">
                    A
                </div>
            </div>

            <?php if($page == 'broadcast'): ?>
                <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                    
                    <div class="lg:col-span-1">
                        <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-200 sticky top-8">
                            <h3 class="font-bold text-lg mb-4 flex items-center gap-2 text-slate-700">
                                <i class="fas fa-pen-nib text-emerald-500"></i> Tulis Pesan Baru
                            </h3>
                            <form method="POST" class="space-y-4">
                                <input type="hidden" name="action" value="broadcast_add">
                                
                                <div>
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Judul Pesan</label>
                                    <input type="text" name="title" class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl focus:outline-none focus:ring-2 focus:ring-emerald-500 transition" placeholder="Contoh: Maintenance Sistem" required>
                                </div>
                                
                                <div>
                                    <label class="block text-xs font-bold text-slate-500 uppercase mb-1">Isi Pesan</label>
                                    <textarea name="message" class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl h-40 focus:outline-none focus:ring-2 focus:ring-emerald-500 transition resize-none" placeholder="Tulis informasi untuk semua member..." required></textarea>
                                </div>
                                
                                <button class="w-full bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-3 rounded-xl shadow-lg shadow-emerald-200 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 rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
                            <div class="p-6 border-b border-slate-100 bg-slate-50/50">
                                <h3 class="font-bold text-lg text-slate-700">Riwayat Pesan Terkirim</h3>
                            </div>
                            <div class="overflow-x-auto">
                                <table class="w-full text-left">
                                    <thead class="bg-slate-50 text-slate-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-slate-100">
                                        <?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-slate-50 transition">
                                            <td class="p-4 text-xs text-slate-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"><?php echo $m['title']; ?></td>
                                            <td class="p-4 text-sm text-slate-600 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('Yakin ingin menghapus pesan ini? Data status baca user juga akan dihapus.');">
                                                    <input type="hidden" name="action" value="broadcast_delete">
                                                    <input type="hidden" name="id" value="<?php echo $m['id']; ?>">
                                                    <button class="w-8 h-8 rounded-full bg-red-100 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-slate-400">Belum ada pesan broadcast.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>


            <?php if($page == 'withdraw'): ?>
                
                <div class="bg-white p-6 rounded-2xl shadow-sm border border-slate-200 mb-8 flex flex-col md:flex-row justify-between items-center gap-4">
                    <div>
                        <h3 class="text-lg font-bold text-slate-800">Status Fitur Withdraw</h3>
                        <p class="text-sm text-slate-500">Atur apakah member bisa melakukan penarikan atau tidak (Maintenance Mode).</p>
                    </div>
                    
                    <form method="POST">
                        <input type="hidden" name="action" value="toggle_withdraw">
                        <?php if($wd_status == 'on'): ?>
                            <button name="status" value="off" class="group flex items-center gap-3 bg-emerald-50 border border-emerald-200 px-5 py-2.5 rounded-full cursor-pointer hover:bg-emerald-100 transition shadow-sm">
                                <div class="text-right">
                                    <p class="text-xs font-bold text-emerald-600 uppercase">System Active</p>
                                    <p class="text-[10px] text-emerald-500">Klik untuk Non-aktifkan</p>
                                </div>
                                <div class="w-10 h-6 bg-emerald-500 rounded-full relative shadow-inner transition">
                                    <div class="absolute right-1 top-1 w-4 h-4 bg-white rounded-full shadow-md transition group-hover:scale-110"></div>
                                </div>
                            </button>
                        <?php else: ?>
                            <button name="status" value="on" class="group flex items-center gap-3 bg-red-50 border border-red-200 px-5 py-2.5 rounded-full cursor-pointer hover:bg-red-100 transition shadow-sm">
                                <div class="text-right">
                                    <p class="text-xs font-bold text-red-600 uppercase">System Offline</p>
                                    <p class="text-[10px] text-red-500">Klik untuk Aktifkan</p>
                                </div>
                                <div class="w-10 h-6 bg-gray-300 rounded-full relative shadow-inner transition">
                                    <div class="absolute left-1 top-1 w-4 h-4 bg-white rounded-full shadow-md transition group-hover:scale-110"></div>
                                </div>
                            </button>
                        <?php endif; ?>
                    </form>
                </div>

                <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden">
                    <div class="p-6 border-b border-slate-100 flex justify-between items-center bg-slate-50/50">
                        <h3 class="font-bold text-lg text-slate-700">Permintaan Penarikan (Pending)</h3>
                        <span class="text-xs font-bold bg-yellow-100 text-yellow-700 px-3 py-1 rounded-full border border-yellow-200">
                            Pending: <?php echo $conn->query("SELECT COUNT(*) as t FROM transactions WHERE type='withdraw' AND status='pending'")->fetch_assoc()['t']; ?>
                        </span>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left">
                            <thead class="bg-slate-50 text-slate-500 text-xs uppercase font-bold">
                                <tr>
                                    <th class="p-4">Tanggal</th>
                                    <th class="p-4">Member</th>
                                    <th class="p-4">Nominal</th>
                                    <th class="p-4">Bank Info</th>
                                    <th class="p-4">Status</th>
                                    <th class="p-4 text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <?php 
                                $wds = $conn->query("SELECT t.*, u.username, u.full_name FROM transactions t JOIN users u ON t.user_id = u.id WHERE t.type='withdraw' ORDER BY t.created_at DESC LIMIT 50");
                                
                                if($wds->num_rows > 0):
                                    while($row = $wds->fetch_assoc()): 
                                        $badge_cls = 'bg-gray-100 text-gray-600';
                                        if($row['status'] == 'pending') $badge_cls = 'bg-yellow-100 text-yellow-700 border border-yellow-200';
                                        if($row['status'] == 'success') $badge_cls = 'bg-emerald-100 text-emerald-700 border border-emerald-200';
                                ?>
                                <tr class="hover:bg-slate-50 transition">
                                    <td class="p-4 text-xs text-slate-500">
                                        <i class="far fa-calendar-alt mr-1"></i> <?php echo date('d M Y', strtotime($row['created_at'])); ?><br>
                                        <span class="ml-5 text-[10px]"><?php echo date('H:i', strtotime($row['created_at'])); ?></span>
                                    </td>
                                    <td class="p-4">
                                        <p class="font-bold text-slate-800 text-sm"><?php echo $row['username']; ?></p>
                                        <p class="text-[10px] text-slate-400 uppercase"><?php echo $row['full_name']; ?></p>
                                    </td>
                                    <td class="p-4 font-mono font-bold text-slate-700">
                                        <?php echo "Rp " . number_format($row['amount'],0,',','.'); ?>
                                    </td>
                                    <td class="p-4 text-xs text-slate-600 italic max-w-xs break-words bg-slate-50 p-2 rounded">
                                        <?php echo $row['description']; ?>
                                    </td>
                                    <td class="p-4">
                                        <span class="px-2 py-1 rounded-md text-[10px] font-bold uppercase <?php echo $badge_cls; ?>">
                                            <?php echo $row['status']; ?>
                                        </span>
                                    </td>
                                    <td class="p-4 text-center">
                                        <?php if($row['status'] == 'pending'): ?>
                                        <form method="POST" onsubmit="return confirm('Setujui penarikan ini? Status akan berubah menjadi Success dan saldo user sudah terpotong.');">
                                            <input type="hidden" name="action" value="approve_wd">
                                            <input type="hidden" name="wd_id" value="<?php echo $row['id']; ?>">
                                            <button class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-xs font-bold shadow-md hover:shadow-lg transition transform hover:-translate-y-0.5">
                                                <i class="fas fa-check-circle mr-1"></i> Approve
                                            </button>
                                        </form>
                                        <?php else: ?>
                                            <span class="text-slate-300 cursor-not-allowed" title="Sudah diproses"><i class="fas fa-check-double"></i> Done</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php endwhile; 
                                else: ?>
                                <tr><td colspan="6" class="p-8 text-center text-slate-400">Tidak ada data penarikan.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            <?php endif; ?>

        </main>
    </div>

</body>
</html>