<?php
/*
|--------------------------------------------------------------------------
| RadyoHost.BiZ / Profesyonel Radyo Hosting ve Web Tasarım Hizmetleri
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| Okey Platformu / Premium Okey ve Sohbet Platformu
|--------------------------------------------------------------------------
*/

/*
|--------------------------------------------------------------------------
| ADMİN ANA PANEL EKRANI
|--------------------------------------------------------------------------
| index.php
| Okey Platformu Premium Yönetim Merkezi Dashboard Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle       = 'Ana Panel';
$pageDescription = 'Okey Platformu Premium Yönetim Merkezi';

require_once __DIR__ . '/includes/admin-layout.php';

$adminData = function_exists('admin') ? admin() : null;
$adminName = $adminData['name'] ?? $_SESSION['admin_name'] ?? 'Yönetici';

$siteName    = defined('SITE_NAME') ? SITE_NAME : 'Okey Platformu';
$siteUrl     = defined('SITE_URL') ? SITE_URL : '../';
$downloadExe = defined('DOWNLOAD_EXE') ? DOWNLOAD_EXE : 'downloads/okey-platformu.exe';

$tables = [];

$stats = [
    'users'         => 0,
    'admins'        => 0,
    'today_users'   => 0,
    'announcements' => 0,
    'downloads'     => 0,
    'messages'      => 0,
    'packages'      => 0,
    'ads'           => 0,
    'okey_managers' => 0,
    'titles'        => 0,
];

$recentUsers = [];
$recentAnnouncements = [];
$recentDownloads = [];
$recentMessages = [];
$okeyManagers = [];

function dashboard_table_exists(array $tables, string $table): bool
{
    return in_array($table, $tables, true);
}

function dashboard_columns(PDO $pdo, string $table): array
{
    try {
        $columns = [];
        $query = $pdo->query("SHOW COLUMNS FROM `{$table}`");

        while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
            $columns[] = (string)$row['Field'];
        }

        return $columns;
    } catch (Throwable $e) {
        return [];
    }
}

function dashboard_val(array $row, array $keys, string $default = '-'): string
{
    foreach ($keys as $key) {
        if (isset($row[$key]) && trim((string)$row[$key]) !== '') {
            return (string)$row[$key];
        }
    }

    return $default;
}

function dashboard_image(array $row): string
{
    $image = dashboard_val($row, ['image', 'avatar', 'photo'], '');

    if ($image === '' || $image === '-') {
        return '../assets/images/admin-default.png';
    }

    $image = trim(str_replace('\\', '/', $image));

    if (str_starts_with($image, 'http://') || str_starts_with($image, 'https://')) {
        return $image;
    }

    $imageName = basename($image);

    $paths = [
        ['disk' => __DIR__ . '/../uploads/managers/' . $imageName, 'url' => '../uploads/managers/' . $imageName],
        ['disk' => __DIR__ . '/../uploads/user/' . $imageName,     'url' => '../uploads/user/' . $imageName],
        ['disk' => __DIR__ . '/../uploads/users/' . $imageName,    'url' => '../uploads/users/' . $imageName],
        ['disk' => __DIR__ . '/../uploads/' . $imageName,          'url' => '../uploads/' . $imageName],
    ];

    foreach ($paths as $path) {
        if (is_file($path['disk'])) {
            return $path['url'];
        }
    }

    return '../assets/images/admin-default.png';
}

try {
    if (isset($pdo) && $pdo instanceof PDO) {
        $tableQuery = $pdo->query("SHOW TABLES");

        while ($row = $tableQuery->fetch(PDO::FETCH_NUM)) {
            $tables[] = (string)$row[0];
        }

        if (dashboard_table_exists($tables, 'users')) {
            $userColumns = dashboard_columns($pdo, 'users');

            $stats['users'] = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();

            if (in_array('role', $userColumns, true)) {
                $stats['admins'] = (int)$pdo->query("
                    SELECT COUNT(*)
                    FROM users
                    WHERE role IN ('admin','superadmin','super_admin','owner')
                ")->fetchColumn();
            }

            if (in_array('created_at', $userColumns, true)) {
                $stats['today_users'] = (int)$pdo->query("
                    SELECT COUNT(*)
                    FROM users
                    WHERE DATE(created_at) = CURDATE()
                ")->fetchColumn();
            }

            $recentUsers = $pdo->query("
                SELECT *
                FROM users
                ORDER BY id DESC
                LIMIT 5
            ")->fetchAll(PDO::FETCH_ASSOC);
        }

        if (dashboard_table_exists($tables, 'announcements')) {
            $stats['announcements'] = (int)$pdo->query("SELECT COUNT(*) FROM announcements")->fetchColumn();

            $recentAnnouncements = $pdo->query("
                SELECT *
                FROM announcements
                ORDER BY id DESC
                LIMIT 5
            ")->fetchAll(PDO::FETCH_ASSOC);
        }

        if (dashboard_table_exists($tables, 'downloads')) {
            $stats['downloads'] = (int)$pdo->query("SELECT COUNT(*) FROM downloads")->fetchColumn();

            $recentDownloads = $pdo->query("
                SELECT *
                FROM downloads
                ORDER BY id DESC
                LIMIT 5
            ")->fetchAll(PDO::FETCH_ASSOC);
        }

        if (dashboard_table_exists($tables, 'contact_messages')) {
            $stats['messages'] = (int)$pdo->query("SELECT COUNT(*) FROM contact_messages")->fetchColumn();

            $recentMessages = $pdo->query("
                SELECT *
                FROM contact_messages
                ORDER BY id DESC
                LIMIT 5
            ")->fetchAll(PDO::FETCH_ASSOC);
        }

        if (dashboard_table_exists($tables, 'packages')) {
            $stats['packages'] += (int)$pdo->query("SELECT COUNT(*) FROM packages")->fetchColumn();
        }

        if (dashboard_table_exists($tables, 'memberships')) {
            $stats['packages'] += (int)$pdo->query("SELECT COUNT(*) FROM memberships")->fetchColumn();
        }

        if (dashboard_table_exists($tables, 'site_ads')) {
            $stats['ads'] = (int)$pdo->query("SELECT COUNT(*) FROM site_ads")->fetchColumn();
        }

        if (dashboard_table_exists($tables, 'okey_managers')) {
            $stats['okey_managers'] = (int)$pdo->query("SELECT COUNT(*) FROM okey_managers")->fetchColumn();

            $okeyManagers = $pdo->query("
                SELECT 
                    m.*,
                    t.title_name,
                    t.icon AS title_icon
                FROM okey_managers m
                LEFT JOIN okey_manager_titles t ON t.id = m.title_id
                WHERE m.status IN ('active','aktif','1')
                ORDER BY m.sort_order ASC, m.id DESC
                LIMIT 8
            ")->fetchAll(PDO::FETCH_ASSOC);
        }

        if (dashboard_table_exists($tables, 'okey_manager_titles')) {
            $stats['titles'] = (int)$pdo->query("SELECT COUNT(*) FROM okey_manager_titles")->fetchColumn();
        }
    }
} catch (Throwable $e) {
    error_log('Admin dashboard hatası: ' . $e->getMessage());
}

$systemStatus = (isset($pdo) && $pdo instanceof PDO) ? 'Aktif' : 'Kontrol Et';
?>

<style>
.dashboard-hero{
    position:relative;
    overflow:hidden;
    padding:38px;
    margin-bottom:24px;
    border-radius:36px;
    background:
        radial-gradient(circle at 10% 15%,rgba(245,182,66,.30),transparent 34%),
        radial-gradient(circle at 88% 18%,rgba(185,0,0,.30),transparent 34%),
        linear-gradient(135deg,rgba(255,255,255,.09),rgba(255,255,255,.025));
    border:1px solid rgba(245,182,66,.18);
    box-shadow:0 32px 100px rgba(0,0,0,.34);
}
.dashboard-hero:after{
    content:"♠";
    position:absolute;
    right:34px;
    bottom:-42px;
    font-size:190px;
    color:rgba(245,182,66,.08);
    font-weight:900;
}
.hero-badge{
    display:inline-flex;
    padding:9px 15px;
    border-radius:999px;
    background:rgba(245,182,66,.14);
    border:1px solid rgba(245,182,66,.32);
    color:#ffd47d;
    font-size:12px;
    font-weight:1000;
}
.dashboard-hero h2{
    position:relative;
    z-index:2;
    margin:22px 0 12px;
    color:#fff;
    font-size:42px;
    line-height:1.1;
}
.dashboard-hero h2 span{color:#f5b642}
.dashboard-hero p{
    position:relative;
    z-index:2;
    max-width:820px;
    margin:0;
    color:#cfd5df;
    line-height:1.8;
    font-weight:800;
}
.hero-actions{
    position:relative;
    z-index:2;
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    margin-top:24px;
}

.dashboard-stats{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:18px;
    margin-bottom:24px;
}
.stat-card{
    position:relative;
    overflow:hidden;
    min-height:155px;
    padding:24px;
    border-radius:28px;
    background:rgba(255,255,255,.055);
    border:1px solid rgba(255,255,255,.09);
    box-shadow:0 22px 64px rgba(0,0,0,.20);
}
.stat-card:after{
    content:attr(data-icon);
    position:absolute;
    right:18px;
    bottom:8px;
    font-size:56px;
    opacity:.12;
}
.stat-card small{
    display:block;
    color:#9aa3b2;
    font-size:13px;
    font-weight:900;
}
.stat-card strong{
    display:block;
    margin-top:12px;
    color:#f5b642;
    font-size:40px;
    line-height:1;
}
.stat-card span{
    display:block;
    margin-top:12px;
    color:#cbd2df;
    font-size:13px;
    font-weight:700;
}

.dashboard-main{
    display:grid;
    grid-template-columns:1.12fr .88fr;
    gap:20px;
    margin-bottom:24px;
}
.premium-box{
    padding:26px;
    border-radius:30px;
    background:rgba(255,255,255,.052);
    border:1px solid rgba(255,255,255,.09);
    box-shadow:0 22px 64px rgba(0,0,0,.18);
}
.box-title{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:14px;
    margin-bottom:18px;
}
.box-title h3{
    margin:0;
    color:#f5b642;
    font-size:21px;
}
.box-title span{
    color:#9aa3b2;
    font-size:12px;
    font-weight:900;
}

.quick-list{
    display:grid;
    grid-template-columns:repeat(2,1fr);
    gap:12px;
}
.quick-item{
    min-height:98px;
    padding:18px;
    border-radius:22px;
    text-decoration:none;
    color:#fff;
    background:rgba(0,0,0,.22);
    border:1px solid rgba(255,255,255,.08);
    transition:.2s;
}
.quick-item:hover{
    transform:translateY(-3px);
    border-color:rgba(245,182,66,.55);
    background:rgba(245,182,66,.08);
}
.quick-item b{
    display:block;
    color:#fff;
    margin-bottom:8px;
}
.quick-item small{
    color:#9aa3b2;
    font-weight:800;
    line-height:1.5;
}

.system-list{display:grid;gap:12px}
.system-row{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:16px;
    padding:14px 0;
    border-bottom:1px solid rgba(255,255,255,.08);
}
.system-row span{
    color:#cbd2df;
    font-weight:800;
}
.system-row strong{
    color:#70e000;
    text-align:right;
    word-break:break-all;
}

.manager-preview-list{
    display:grid;
    gap:12px;
}
.manager-preview{
    display:flex;
    align-items:center;
    gap:12px;
    padding:13px;
    border-radius:20px;
    background:rgba(0,0,0,.22);
    border:1px solid rgba(255,255,255,.08);
}
.manager-preview img{
    width:58px;
    height:58px;
    border-radius:50%;
    object-fit:cover;
    padding:2px;
    background:linear-gradient(135deg,#f5b642,#b90000);
}
.manager-preview strong{
    display:block;
    color:#fff;
    margin-bottom:5px;
}
.manager-preview span{
    display:inline-flex;
    color:#f5b642;
    font-size:12px;
    font-weight:1000;
    padding:5px 9px;
    border-radius:999px;
    background:rgba(245,182,66,.10);
    border:1px solid rgba(245,182,66,.22);
}

.recent-grid{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:20px;
}
.recent-list{display:grid;gap:12px}
.recent-item{
    padding:14px;
    border-radius:18px;
    background:rgba(0,0,0,.20);
    border:1px solid rgba(255,255,255,.07);
}
.recent-item strong{
    display:block;
    color:#fff;
    margin-bottom:6px;
    font-size:14px;
}
.recent-item span{
    display:block;
    color:#9aa3b2;
    font-size:12px;
    font-weight:700;
}
.empty-box{
    padding:18px;
    border-radius:18px;
    color:#9aa3b2;
    background:rgba(0,0,0,.18);
    border:1px dashed rgba(255,255,255,.12);
    font-weight:800;
}

@media(max-width:1200px){
    .dashboard-stats{grid-template-columns:repeat(2,1fr)}
    .dashboard-main,.recent-grid{grid-template-columns:1fr}
}
@media(max-width:620px){
    .dashboard-stats,.quick-list{grid-template-columns:1fr}
    .dashboard-hero{padding:24px}
    .dashboard-hero h2{font-size:30px}
}
</style>

<section class="dashboard-hero">
    <div class="hero-badge">Premium Yönetim Merkezi</div>

    <h2>Hoş Geldin, <span><?= admin_e((string)$adminName) ?></span></h2>

    <p>
        <?= admin_e((string)$siteName) ?> yönetim paneli; üyeler, paketler, duyurular, reklamlar,
        indirmeler ve okey yönetim kadrosunu tek merkezden profesyonel şekilde kontrol etmen için hazırlandı.
    </p>

    <div class="hero-actions">
        <a href="users.php" class="admin-btn">👥 Üyeleri Yönet</a>
        <a href="okey-managers.php" class="admin-btn admin-btn-dark">👑 Okey Yöneticileri</a>
        <a href="../index.php" target="_blank" class="admin-btn admin-btn-dark">🌐 Siteyi Gör</a>
    </div>
</section>

<section class="dashboard-stats">
    <div class="stat-card" data-icon="👥"><small>Toplam Üye</small><strong><?= admin_e((string)$stats['users']) ?></strong><span>Sistemde kayıtlı oyuncular.</span></div>
    <div class="stat-card" data-icon="🆕"><small>Bugün Kayıt</small><strong><?= admin_e((string)$stats['today_users']) ?></strong><span>Bugün aramıza katılan üyeler.</span></div>
    <div class="stat-card" data-icon="👑"><small>Adminler</small><strong><?= admin_e((string)$stats['admins']) ?></strong><span>Panel yetkili hesapları.</span></div>
    <div class="stat-card" data-icon="🛡️"><small>Okey Yöneticileri</small><strong><?= admin_e((string)$stats['okey_managers']) ?></strong><span>Ana sayfada görünen yönetim kadrosu.</span></div>
    <div class="stat-card" data-icon="📢"><small>Duyurular</small><strong><?= admin_e((string)$stats['announcements']) ?></strong><span>Yayınlanan haber ve bildirimler.</span></div>
    <div class="stat-card" data-icon="🎫"><small>Paketler</small><strong><?= admin_e((string)$stats['packages']) ?></strong><span>Gold, Premium ve VIP paket kayıtları.</span></div>
    <div class="stat-card" data-icon="📣"><small>Reklamlar</small><strong><?= admin_e((string)$stats['ads']) ?></strong><span>Reklam ve sponsor alanları.</span></div>
    <div class="stat-card" data-icon="✉️"><small>Mesajlar</small><strong><?= admin_e((string)$stats['messages']) ?></strong><span>İletişim formu bildirimleri.</span></div>
</section>

<section class="dashboard-main">
    <div class="premium-box">
        <div class="box-title">
            <h3>Hızlı Yönetim Merkezi</h3>
            <span>Kırmızı çizgi yönetim alanı</span>
        </div>

        <div class="quick-list">
            <a href="users.php" class="quick-item"><b>👥 Üye Yönetimi</b><small>Kullanıcıları incele, düzenle ve yönet.</small></a>
            <a href="packages.php" class="quick-item"><b>👑 Paket Yönetimi</b><small>Gold, Premium ve VIP paketleri yönet.</small></a>
            <a href="announcements.php" class="quick-item"><b>📢 Duyurular</b><small>Oyunculara haber ve bildirim yayınla.</small></a>
            <a href="downloads.php" class="quick-item"><b>⬇️ İndirme Merkezi</b><small>Oyun EXE dosyalarını yönet.</small></a>
            <a href="ads.php" class="quick-item"><b>📣 Reklamlar</b><small>Ana sayfa reklam ve sponsor alanları.</small></a>
            <a href="okey-managers.php" class="quick-item"><b>🛡️ Okey Yöneticileri</b><small>Ana sayfa yönetim kadrosunu düzenle.</small></a>
        </div>
    </div>

    <div class="premium-box">
        <div class="box-title">
            <h3>Sistem Durumu</h3>
            <span>Canlı kontrol</span>
        </div>

        <div class="system-list">
            <div class="system-row"><span>Veritabanı</span><strong><?= admin_e($systemStatus) ?></strong></div>
            <div class="system-row"><span>Site URL</span><strong><?= admin_e((string)$siteUrl) ?></strong></div>
            <div class="system-row"><span>EXE Dosyası</span><strong><?= admin_e((string)$downloadExe) ?></strong></div>
            <div class="system-row"><span>Oturum</span><strong>Aktif</strong></div>
            <div class="system-row"><span>Yönetim Ünvanları</span><strong><?= admin_e((string)$stats['titles']) ?></strong></div>
        </div>
    </div>
</section>

<section class="dashboard-main">
    <div class="premium-box">
        <div class="box-title">
            <h3>Okey Yönetim Kadrosu</h3>
            <span>Ana sayfa önizleme</span>
        </div>

        <div class="manager-preview-list">
            <?php if ($okeyManagers): ?>
                <?php foreach ($okeyManagers as $manager): ?>
                    <?php
                    $managerName = dashboard_val($manager, ['display_name', 'username'], 'Okey Yöneticisi');
                    $managerTitle = trim(dashboard_val($manager, ['title_icon'], '👑') . ' ' . dashboard_val($manager, ['title_name'], 'Okey Yöneticisi'));
                    ?>
                    <div class="manager-preview">
                        <img src="<?= admin_e(dashboard_image($manager)) ?>" alt="<?= admin_e($managerName) ?>">
                        <div>
                            <strong><?= admin_e($managerName) ?></strong>
                            <span><?= admin_e($managerTitle) ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-box">Henüz okey yöneticisi eklenmedi.</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="premium-box">
        <div class="box-title">
            <h3>Panel Özeti</h3>
            <span>Yönetim vitrini</span>
        </div>

        <div class="system-list">
            <div class="system-row"><span>Toplam İçerik</span><strong><?= admin_e((string)($stats['announcements'] + $stats['downloads'] + $stats['ads'])) ?></strong></div>
            <div class="system-row"><span>Toplam Yönetim Gücü</span><strong><?= admin_e((string)($stats['admins'] + $stats['okey_managers'])) ?></strong></div>
            <div class="system-row"><span>Bugünkü Hareket</span><strong><?= admin_e((string)$stats['today_users']) ?></strong></div>
            <div class="system-row"><span>Platform Durumu</span><strong>Yayına Hazır</strong></div>
        </div>
    </div>
</section>

<section class="recent-grid">
    <div class="premium-box">
        <div class="box-title"><h3>Son Üyeler</h3><span>Yeni kayıtlar</span></div>
        <div class="recent-list">
            <?php if ($recentUsers): ?>
                <?php foreach ($recentUsers as $user): ?>
                    <div class="recent-item">
                        <strong><?= admin_e($user['name'] ?? $user['username'] ?? 'Kullanıcı') ?></strong>
                        <span><?= admin_e($user['email'] ?? $user['username'] ?? 'Bilgi yok') ?></span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-box">Henüz üye kaydı bulunamadı.</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="premium-box">
        <div class="box-title"><h3>Son Duyurular</h3><span>Güncel haberler</span></div>
        <div class="recent-list">
            <?php if ($recentAnnouncements): ?>
                <?php foreach ($recentAnnouncements as $announcement): ?>
                    <div class="recent-item">
                        <strong><?= admin_e($announcement['title'] ?? $announcement['subject'] ?? 'Duyuru') ?></strong>
                        <span><?= admin_e($announcement['status'] ?? $announcement['created_at'] ?? 'Yayınlandı') ?></span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-box">Henüz duyuru eklenmedi.</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="premium-box">
        <div class="box-title"><h3>Son İndirmeler</h3><span>Dosya merkezi</span></div>
        <div class="recent-list">
            <?php if ($recentDownloads): ?>
                <?php foreach ($recentDownloads as $download): ?>
                    <div class="recent-item">
                        <strong><?= admin_e($download['title'] ?? $download['name'] ?? 'İndirme Dosyası') ?></strong>
                        <span><?= admin_e($download['file_path'] ?? $download['version'] ?? 'EXE dosyası') ?></span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-box">Henüz indirme kaydı bulunamadı.</div>
            <?php endif; ?>
        </div>
    </div>

    <div class="premium-box">
        <div class="box-title"><h3>Son Mesajlar</h3><span>İletişim</span></div>
        <div class="recent-list">
            <?php if ($recentMessages): ?>
                <?php foreach ($recentMessages as $msg): ?>
                    <div class="recent-item">
                        <strong><?= admin_e($msg['name'] ?? $msg['subject'] ?? 'Mesaj') ?></strong>
                        <span><?= admin_e($msg['email'] ?? $msg['created_at'] ?? 'Yeni mesaj') ?></span>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-box">Henüz mesaj kaydı bulunmadı.</div>
            <?php endif; ?>
        </div>
    </div>
</section>

<?php require_once __DIR__ . '/includes/admin-footer.php'; ?>