<?php
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('X-LiteSpeed-Cache-Control: no-cache');
require_once __DIR__ . '/config.php';

// Güvenli Admin Kimlik Bilgileri
define('ADMIN_USER', 'admin');
define('ADMIN_PASS', 'AdminPassword123!'); // İsteğe göre değiştirilebilir

// Brute-force koruması takibi
if (!isset($_SESSION['login_attempts'])) {
    $_SESSION['login_attempts'] = 0;
    $_SESSION['last_attempt_time'] = time();
}

// Oturum Zaman Aşımı (15 dakika başarısız denemede kilit)
if ($_SESSION['login_attempts'] >= 5 && (time() - $_SESSION['last_attempt_time']) < 900) {
    $lockTimeLeft = ceil((900 - (time() - $_SESSION['last_attempt_time'])) / 60);
    $loginLocked = "Çok fazla başarısız deneme! Lütfen {$lockTimeLeft} dakika bekleyin.";
} else if (time() - $_SESSION['last_attempt_time'] >= 900) {
    $_SESSION['login_attempts'] = 0;
}

// 1. Çıkış İşlemi
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    unset($_SESSION['admin_logged_in']);
    session_regenerate_id(true);
    header("Location: " . SITE_URL . "/admin");
    exit;
}

// 2. Giriş İşlemi (PRG Pattern)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'login') {
    if (isset($loginLocked)) {
        $_SESSION['flash_admin'] = ['type' => 'danger', 'text' => $loginLocked];
        header("Location: " . SITE_URL . "/admin");
        exit;
    }

    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (verifyAdminLogin($username, $password)) {
        session_regenerate_id(true);
        $_SESSION['admin_logged_in'] = true;
        $_SESSION['login_attempts'] = 0;
        header("Location: " . SITE_URL . "/admin");
        exit;
    } else {
        $_SESSION['login_attempts']++;
        $_SESSION['last_attempt_time'] = time();
        $_SESSION['flash_admin'] = ['type' => 'danger', 'text' => 'Geçersiz kullanıcı adı veya şifre!'];
        header("Location: " . SITE_URL . "/admin");
        exit;
    }
}

// 3. Şifre Değiştirme İşlemi (PRG Pattern)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'change_password') {
    if (!empty($_SESSION['admin_logged_in'])) {
        $currentPass = trim($_POST['current_password'] ?? '');
        $newPass = trim($_POST['new_password'] ?? '');
        $confirmPass = trim($_POST['confirm_password'] ?? '');

        $adminConfig = getAdminConfig();
        if (!password_verify($currentPass, $adminConfig['password_hash'])) {
            $_SESSION['flash_admin'] = ['type' => 'danger', 'text' => 'Mevcut şifreniz yanlış!'];
        } elseif (strlen($newPass) < 6) {
            $_SESSION['flash_admin'] = ['type' => 'danger', 'text' => 'Yeni şifreniz en az 6 karakter olmalıdır.'];
        } elseif ($newPass !== $confirmPass) {
            $_SESSION['flash_admin'] = ['type' => 'danger', 'text' => 'Yeni şifre ve şifre tekrarı eşleşmiyor!'];
        } else {
            updateAdminPassword($newPass);
            $_SESSION['flash_admin'] = ['type' => 'success', 'text' => 'Admin şifreniz başarıyla güncellendi.'];
        }
    }
    header("Location: " . SITE_URL . "/admin");
    exit;
}

// 4. Mesaj Silme İşlemi (POST / PRG Pattern - GET İle Silme Yasaktır)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_message') {

    if (!empty($_SESSION['admin_logged_in'])) {
        $msgId = (int)($_POST['id'] ?? 0);
        if ($msgId > 0) {
            $db = getDbConnection();
            if ($db) {
                $stmt = $db->prepare("DELETE FROM iletisim_bilgileri WHERE id = ?");
                $stmt->execute([$msgId]);
                $_SESSION['flash_admin'] = ['type' => 'success', 'text' => 'Mesaj başarıyla silindi.'];
            }
        }
    }
    header("Location: " . SITE_URL . "/admin");
    exit;
}

// 5. Sistem Ayarlarını Güncelleme İşlemi (PRG Pattern)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_settings') {
    if (!empty($_SESSION['admin_logged_in'])) {
        $mode = trim($_POST['system_mode'] ?? 'original');
        if (in_array($mode, ['original', 'api'])) {
            $configFile = STORAGE_DIR . 'admin_config.json';
            $config = getAdminConfig();
            $config['system_mode'] = $mode;
            file_put_contents($configFile, json_encode($config));
            $_SESSION['flash_admin'] = ['type' => 'success', 'text' => 'Sistem çalışma modu başarıyla güncellendi.'];
        } else {
            $_SESSION['flash_admin'] = ['type' => 'danger', 'text' => 'Geçersiz çalışma modu seçimi!'];
        }
    }
    header("Location: " . SITE_URL . "/admin");
    exit;
}

// Flash Mesaj Okuma
$flashAdmin = $_SESSION['flash_admin'] ?? null;
unset($_SESSION['flash_admin']);

$isLoggedIn = !empty($_SESSION['admin_logged_in']);
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Paneli - YouTube Dönüştürücü | Ücretsiz MP3, MP4, Video İndir</title>
    <!-- Favicon -->
    <link rel="icon" type="image/webp" href="fav.webp">
    <link rel="stylesheet" href="css/style.css">

</head>
<body>

    <main class="container">
        <header class="app-header">
            <div class="brand-badge">
                <svg viewBox="0 0 24 24">
                    <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-5.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8s0 0 0 0z"/>
                </svg>
                <span>Yönetici Kontrol Paneli</span>
            </div>
            <h1 class="app-title">Admin Paneli</h1>
            <p class="app-subtitle">İstatistikler, medya depolama analizi ve gelen iletişim mesajları.</p>
        </header>

        <?php if (!$isLoggedIn): ?>
            <!-- GİRİŞ FORMU -->
            <section class="converter-card" style="max-width: 450px; margin: 0 auto;">
                <h2 style="font-size: 1.3rem; text-align: center; margin-bottom: 20px;">Yönetici Girişi</h2>

                <?php if ($flashAdmin): ?>
                    <div style="padding: 12px; border-radius: var(--radius-md); margin-bottom: 20px; font-size: 0.9rem; background: #da3633; color: white; text-align: center;">
                        <?php echo htmlspecialchars($flashAdmin['text']); ?>
                    </div>
                <?php endif; ?>

                <form action="admin" method="POST" class="url-form">
                    <input type="hidden" name="action" value="login">


                    <div>
                        <label style="display: block; font-size: 0.85rem; color: var(--text-muted); margin-bottom: 6px;">Kullanıcı Adı</label>
                        <input type="text" name="username" class="url-input" style="padding-left: 16px;" placeholder="admin" required>
                    </div>

                    <div>
                        <label style="display: block; font-size: 0.85rem; color: var(--text-muted); margin-bottom: 6px;">Şifre</label>
                        <input type="password" name="password" class="url-input" style="padding-left: 16px;" placeholder="••••••••" required>
                    </div>

                    <button type="submit" class="btn-submit" style="width: 100%; margin-top: 10px;">
                        Giriş Yap
                    </button>
                </form>
            </section>
        <?php else: ?>
            <!-- ADMIN DASHBOARD -->

            <?php
            // İstatistik Verileri Çekme
            $db = getDbConnection();
            $totalMessages = 0;
            $messages = [];

            if ($db) {
                try {
                    $totalMessages = (int)$db->query("SELECT COUNT(*) FROM iletisim_bilgileri")->fetchColumn();
                    $stmt = $db->query("SELECT * FROM iletisim_bilgileri ORDER BY id DESC LIMIT 50");
                    $messages = $stmt->fetchAll();
                } catch (Exception $e) {
                    $totalMessages = 0;
                }
            }

            // Ziyaretçi İstatistikleri
            $visitorStats = getVisitorStats();

            // Storage Klasörü Analizi
            $storageFiles = array_diff(scandir(STORAGE_DIR), ['.', '..', '.htaccess', 'visitors.json']);
            $totalConvertedFiles = count($storageFiles);
            $totalStorageSizeBytes = 0;
            foreach ($storageFiles as $file) {
                $filePath = STORAGE_DIR . $file;
                if (is_file($filePath)) {
                    $totalStorageSizeBytes += filesize($filePath);
                }
            }
            $totalStorageMB = round($totalStorageSizeBytes / (1024 * 1024), 2);
            ?>

            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
                <span style="font-size: 0.95rem; color: var(--text-muted);">Hoş geldiniz, <strong>admin</strong></span>
                <div style="display: flex; align-items: center; gap: 16px;">
                    <button id="themeToggleBtn" class="theme-toggle-btn" title="Temayı Değiştir"></button>
                    <a href="admin?action=logout" style="color: #ff4d4d; text-decoration: none; font-size: 0.9rem; font-weight: 500;">Oturumu Kapat &rarr;</a>
                </div>
            </div>



            <?php if ($flashAdmin): ?>
                <div style="padding: 12px 18px; border-radius: var(--radius-md); margin-bottom: 24px; font-size: 0.9rem; background: <?php echo $flashAdmin['type'] === 'success' ? '#238636' : '#da3633'; ?>; color: white;">
                    <?php echo htmlspecialchars($flashAdmin['text']); ?>
                </div>
            <?php endif; ?>

            <!-- İSTATİSTİK KARTLARI -->
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px; margin-bottom: 36px;">
                <div style="background: var(--card-bg); border: 1px solid var(--card-border); padding: 20px; border-radius: var(--radius-lg);">
                    <span style="font-size: 0.85rem; color: var(--text-muted);">Toplam Ziyaret</span>
                    <h2 style="font-size: 2rem; color: var(--text-main); margin-top: 4px;"><?php echo number_format($visitorStats['total_views']); ?></h2>
                </div>

                <div style="background: var(--card-bg); border: 1px solid var(--card-border); padding: 20px; border-radius: var(--radius-lg);">
                    <span style="font-size: 0.85rem; color: var(--text-muted);">Tekil Ziyaretçi</span>
                    <h2 style="font-size: 2rem; color: #388bfd; margin-top: 4px;"><?php echo number_format($visitorStats['unique_visitors']); ?></h2>
                </div>

                <div style="background: var(--card-bg); border: 1px solid var(--card-border); padding: 20px; border-radius: var(--radius-lg);">
                    <span style="font-size: 0.85rem; color: var(--text-muted);">Gelen Mesajlar</span>
                    <h2 style="font-size: 2rem; color: var(--text-main); margin-top: 4px;"><?php echo $totalMessages; ?></h2>
                </div>

                <div style="background: var(--card-bg); border: 1px solid var(--card-border); padding: 20px; border-radius: var(--radius-lg);">
                    <span style="font-size: 0.85rem; color: var(--text-muted);">Dönüştürülen Medya</span>
                    <h2 style="font-size: 2rem; color: var(--accent-red); margin-top: 4px;"><?php echo $totalConvertedFiles; ?></h2>
                </div>

                <div style="background: var(--card-bg); border: 1px solid var(--card-border); padding: 20px; border-radius: var(--radius-lg);">
                    <span style="font-size: 0.85rem; color: var(--text-muted);">Disk Kullanımı</span>
                    <h2 style="font-size: 2rem; color: #2ea043; margin-top: 4px;"><?php echo $totalStorageMB; ?> <span style="font-size: 1rem; font-weight: normal;">MB</span></h2>
                </div>
            </div>


            <!-- GELEN MESAJLAR TABLOSU -->
            <section class="converter-card" style="padding: 24px; margin-bottom: 24px;">
                <h3 style="font-size: 1.2rem; margin-bottom: 20px;">Gelen İletişim Mesajları</h3>

                <?php if (empty($messages)): ?>
                    <p style="text-align: center; color: var(--text-muted); padding: 30px 0;">Henüz kaydedilmiş iletişim mesajı bulunmuyor.</p>
                <?php else: ?>
                    <div style="overflow-x: auto;">
                        <table style="width: 100%; border-collapse: collapse; text-align: left; font-size: 0.9rem;">
                            <thead>
                                <tr style="border-bottom: 1px solid var(--card-border); color: var(--text-muted);">
                                    <th style="padding: 12px 10px;">ID</th>
                                    <th style="padding: 12px 10px;">Ad Soyad</th>
                                    <th style="padding: 12px 10px;">E-Posta / Tel</th>
                                    <th style="padding: 12px 10px;">Mesaj</th>
                                    <th style="padding: 12px 10px; text-align: right;">İşlem</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($messages as $msg): ?>
                                    <tr style="border-bottom: 1px solid rgba(255,255,255,0.05);">
                                        <td style="padding: 12px 10px; color: var(--text-muted);"><?php echo $msg['id']; ?></td>
                                        <td style="padding: 12px 10px; font-weight: 500;">
                                            <?php echo htmlspecialchars(($msg['isim'] ?? '') . ' ' . ($msg['soyisim'] ?? '')); ?>
                                        </td>
                                        <td style="padding: 12px 10px;">
                                            <div><?php echo htmlspecialchars($msg['email'] ?? ''); ?></div>
                                            <small style="color: var(--text-muted);"><?php echo htmlspecialchars($msg['tel'] ?? $msg['telefon'] ?? '-'); ?></small>
                                        </td>
                                        <td style="padding: 12px 10px; max-width: 300px;">
                                            <?php echo nl2br(htmlspecialchars($msg['mesaj'] ?? '')); ?>
                                        </td>
                                        <td style="padding: 12px 10px; text-align: right;">
                                            <form action="admin" method="POST" onsubmit="return confirm('Bu mesajı silmek istediğinize emin misiniz?');" style="display: inline;">
                                                <input type="hidden" name="action" value="delete_message">
                                                <input type="hidden" name="id" value="<?php echo $msg['id']; ?>">
                                                <button type="submit" style="background: #da3633; color: white; border: none; padding: 6px 12px; border-radius: 4px; font-size: 0.8rem; cursor: pointer;">Sil</button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>

            <!-- SİSTEM ÇALIŞMA AYARLARI -->
            <section class="converter-card" style="padding: 24px; max-width: 500px; margin-bottom: 24px;">
                <h3 style="font-size: 1.1rem; margin-bottom: 16px;">Sistem Çalışma Ayarları</h3>
                <form action="admin" method="POST" class="url-form">
                    <input type="hidden" name="action" value="update_settings">
                    
                    <div>
                        <label style="display: block; font-size: 0.85rem; color: var(--text-muted); margin-bottom: 6px;">Dönüştürücü Çalışma Modu</label>
                        <?php $currentMode = getAdminConfig()['system_mode'] ?? 'original'; ?>
                        <select name="system_mode" class="select-custom" style="width: 100%; background: var(--card-bg); color: var(--text-main); border: 1px solid var(--card-border); padding: 12px; border-radius: var(--radius-md); font-family: inherit; font-size: 0.95rem; outline: none; margin-bottom: 16px; -webkit-appearance: none;">
                            <option value="original" <?php echo $currentMode === 'original' ? 'selected' : ''; ?>>Orijinal Mod (Sunucudan İndirme - yt-dlp)</option>
                            <option value="api" <?php echo $currentMode === 'api' ? 'selected' : ''; ?>>API Proxy Modu (Hızlı Bulut Akışı - Sıfır CPU/Disk)</option>
                        </select>
                    </div>

                    <button type="submit" class="btn-submit" style="width: 100%; margin-top: 6px;">
                        Ayarları Kaydet
                    </button>
                </form>
            </section>

            <!-- ŞİFRE DEĞİŞTİRME FORMU -->
            <section class="converter-card" style="padding: 24px; max-width: 500px;">
                <h3 style="font-size: 1.1rem; margin-bottom: 16px;">Admin Şifresini Değiştir</h3>
                <form action="admin" method="POST" class="url-form">

                    <input type="hidden" name="action" value="change_password">

                    <div>
                        <label style="display: block; font-size: 0.85rem; color: var(--text-muted); margin-bottom: 6px;">Mevcut Şifre</label>
                        <input type="password" name="current_password" class="url-input" style="padding-left: 16px;" placeholder="Mevcut Şifreniz" required>
                    </div>

                    <div>
                        <label style="display: block; font-size: 0.85rem; color: var(--text-muted); margin-bottom: 6px;">Yeni Şifre</label>
                        <input type="password" name="new_password" class="url-input" style="padding-left: 16px;" placeholder="En az 6 karakter" required>
                    </div>

                    <div>
                        <label style="display: block; font-size: 0.85rem; color: var(--text-muted); margin-bottom: 6px;">Yeni Şifre Tekrarı</label>
                        <input type="password" name="confirm_password" class="url-input" style="padding-left: 16px;" placeholder="Yeni Şifre Tekrarı" required>
                    </div>

                    <button type="submit" class="btn-submit" style="width: 100%; margin-top: 6px;">
                        Şifreyi Güncelle
                    </button>
                </form>
            </section>

        <?php endif; ?>

        <footer class="app-footer">
            <p>YouTube MP3 & MP4 Converter Admin &copy; <?php echo date('Y'); ?> | Altyapı ve Yazılım: <a href="https://osirisbilisim.com" title="Antalya Web Tasarım ve Yazılım Ajansı" target="_blank" rel="dofollow noopener noreferrer" style="color: var(--text-muted); text-decoration: underline;">Antalya Web Tasarım - Osiris Bilişim</a></p>
        </footer>

    </main>

    <script src="js/theme.js"></script>
</body>

</html>
