<?php
/*
|--------------------------------------------------------------------------
| RadyoHost.BiZ / Okey Platformu
|--------------------------------------------------------------------------
| Sayfa Adı : Dinamik Paket Bilgilerim
| Dosya     : customer/my-package.php
|--------------------------------------------------------------------------
| Açıklama:
| Üyenin aktif paketine göre Gold / Premium / VIP özel tasarım gösterir.
| Aktif paket üst kartta, paket geçmişi ise alt bölümde listelenir.
|--------------------------------------------------------------------------
| Modül     : Müşteri Paneli
| Yetki     : Üye
| Sürüm     : V3.0
|--------------------------------------------------------------------------
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

require_once __DIR__ . '/../config/db.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$pdo = $pdo ?? $db ?? null;

if (!$pdo instanceof PDO) {
    die('Veritabanı bağlantısı bulunamadı.');
}

if (empty($_SESSION['user_id']) && empty($_SESSION['customer_id'])) {
    header('Location: ../login.php');
    exit;
}

$userId = (int)($_SESSION['user_id'] ?? $_SESSION['customer_id']);

function e(string $v): string
{
    return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

function tr_date(?string $date): string
{
    if (!$date || $date === '0000-00-00' || $date === '0000-00-00 00:00:00') {
        return 'Belirtilmemiş';
    }

    try {
        return (new DateTime($date))->format('d.m.Y H:i');
    } catch (Throwable $e) {
        return $date;
    }
}

function kalan_gun(?string $endDate): array
{
    if (!$endDate || $endDate === '0000-00-00' || $endDate === '0000-00-00 00:00:00') {
        return ['text' => 'Süre Yok', 'class' => 'offline'];
    }

    try {
        $today = new DateTimeImmutable('today');
        $end = new DateTimeImmutable($endDate);
        $diff = (int)$today->diff($end)->format('%r%a');

        if ($diff < 0) {
            return ['text' => 'Süresi Doldu', 'class' => 'offline'];
        }

        if ($diff === 0) {
            return ['text' => 'Bugün Bitiyor', 'class' => 'warning'];
        }

        return ['text' => $diff . ' Gün Kaldı', 'class' => $diff <= 7 ? 'warning' : 'online'];
    } catch (Throwable $e) {
        return ['text' => 'Süre Yok', 'class' => 'offline'];
    }
}

$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id LIMIT 1");
$stmt->execute(['id' => $userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {
    session_destroy();
    header('Location: ../login.php');
    exit;
}

$name  = $user['name'] ?? $user['username'] ?? 'Üye';
$email = $user['email'] ?? '-';
$image = !empty($user['image']) ? '../uploads/user/' . $user['image'] : '../assets/img/default-user.png';

$stmtPackages = $pdo->prepare("
    SELECT
        up.id,
        up.package_id,
        up.package_type,
        up.package_name,
        up.start_date,
        up.end_date,
        up.status,
        up.created_at,

        p.title,
        p.amount,
        p.price,
        p.duration,
        p.description
    FROM user_packages up
    LEFT JOIN packages p ON p.id = up.package_id
    WHERE up.user_id = :user_id
    ORDER BY
        FIELD(up.status, 'active', 'expired', 'cancelled'),
        FIELD(up.package_type, 'vip', 'premium', 'gold'),
        up.id DESC
");
$stmtPackages->execute(['user_id' => $userId]);
$packages = $stmtPackages->fetchAll(PDO::FETCH_ASSOC);

$activePackage = null;

foreach ($packages as $pkg) {
    if (($pkg['status'] ?? '') === 'active') {
        $activePackage = $pkg;
        break;
    }
}

if (!$activePackage && !empty($packages)) {
    $activePackage = $packages[0];
}

$activeType = strtolower((string)($activePackage['package_type'] ?? 'gold'));

if (!in_array($activeType, ['gold', 'premium', 'vip'], true)) {
    $activeType = 'gold';
}

$themeMap = [
    'gold' => [
        'class' => 'theme-gold',
        'icon' => '🪙',
        'title' => 'Gold Üye Paketi',
        'label' => 'GOLD',
        'hero' => 'Gold gücün aktif. Okey masalarında parlayan üyelik deneyimi.',
    ],
    'premium' => [
        'class' => 'theme-premium',
        'icon' => '👑',
        'title' => 'Premium Üyelik Paketi',
        'label' => 'PREMIUM',
        'hero' => 'Premium ayrıcalıkların aktif. Daha güçlü, daha özel üye deneyimi.',
    ],
    'vip' => [
        'class' => 'theme-vip',
        'icon' => '💎',
        'title' => 'VIP Üyelik Paketi',
        'label' => 'VIP',
        'hero' => 'VIP statün aktif. En üst seviye üyelik görünümü ve ayrıcalıklar.',
    ],
];

$theme = $themeMap[$activeType];

$activeName = $activePackage['title'] ?? $activePackage['package_name'] ?? 'Aktif Paket Yok';
$activeAmount = $activePackage['amount'] ?? '0';
$activePrice = $activePackage['price'] ?? '-';
$activeDuration = $activePackage['duration'] ?? '-';
$activeDesc = $activePackage['description'] ?? 'Yönetim tarafından hesabınıza atanmış paket.';
$activeStart = $activePackage['start_date'] ?? null;
$activeEnd = $activePackage['end_date'] ?? null;
$activeRemain = kalan_gun($activeEnd);
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<title>Paket Bilgilerim | RadyoHost Okey</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
*{box-sizing:border-box}
body{
    margin:0;
    font-family:Arial,Helvetica,sans-serif;
    color:#fff;
    background:#070914;
    overflow-x:hidden;
}
body:before{
    content:"";
    position:fixed;
    inset:0;
    z-index:-2;
    background:
        radial-gradient(circle at 12% 10%,var(--glow1),transparent 28%),
        radial-gradient(circle at 88% 22%,var(--glow2),transparent 27%),
        radial-gradient(circle at 50% 92%,#3b82f655,transparent 32%),
        linear-gradient(135deg,#070914,#111827 55%,#090b16);
}
body:after{
    content:"";
    position:fixed;
    inset:0;
    background-image:
        linear-gradient(#ffffff08 1px,transparent 1px),
        linear-gradient(90deg,#ffffff08 1px,transparent 1px);
    background-size:42px 42px;
    opacity:.24;
    z-index:-1;
}
.theme-gold{
    --main:#f5b642;
    --main2:#ff8a00;
    --glow1:#f5b64266;
    --glow2:#ff8a0060;
    --soft:#f5b64218;
}
.theme-premium{
    --main:#38bdf8;
    --main2:#8b5cf6;
    --glow1:#38bdf866;
    --glow2:#8b5cf666;
    --soft:#38bdf818;
}
.theme-vip{
    --main:#ff5db1;
    --main2:#a855f7;
    --glow1:#ff5db166;
    --glow2:#a855f766;
    --soft:#ff5db118;
}
a{text-decoration:none;color:inherit}
.wrap{min-height:100vh;padding:28px}
.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:18px;
    margin-bottom:25px;
}
.topbar h1{margin:0;font-size:31px}
.topbar p{margin:8px 0 0;color:#c6cdec;font-size:14px}
.dashboard-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:10px;
    padding:15px 24px;
    border-radius:18px;
    background:linear-gradient(135deg,var(--main),var(--main2));
    color:#fff;
    font-size:15px;
    font-weight:900;
    box-shadow:0 15px 35px var(--glow1);
    transition:.25s;
}
.dashboard-btn:hover{transform:translateY(-3px)}
.hero{
    position:relative;
    overflow:hidden;
    border-radius:36px;
    padding:36px;
    margin-bottom:24px;
    background:linear-gradient(135deg,#151b31dd,#0d1224ee);
    border:1px solid rgba(255,255,255,.12);
    box-shadow:0 25px 90px #0009;
}
.hero:before{
    content:"";
    position:absolute;
    width:430px;
    height:430px;
    right:-145px;
    top:-165px;
    border-radius:50%;
    background:linear-gradient(135deg,var(--glow1),var(--glow2));
    filter:blur(8px);
}
.hero-inner{
    position:relative;
    display:grid;
    grid-template-columns:160px 1fr 310px;
    gap:28px;
    align-items:center;
}
.avatar{
    position:relative;
    width:160px;
    height:160px;
}
.avatar img{
    width:160px;
    height:160px;
    border-radius:50%;
    object-fit:cover;
    border:5px solid var(--main);
    box-shadow:0 0 58px var(--glow1);
}
.dot{
    position:absolute;
    right:14px;
    bottom:14px;
    width:25px;
    height:25px;
    border-radius:50%;
    background:#22c55e;
    border:4px solid #111827;
    box-shadow:0 0 20px #22c55e;
}
.hero h2{margin:0 0 8px;font-size:36px}
.hero p{margin:0;color:#c6cdec;line-height:1.7}
.badges{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-top:18px;
}
.badge{
    padding:10px 14px;
    border-radius:999px;
    background:#ffffff12;
    border:1px solid #ffffff18;
    font-size:13px;
    font-weight:900;
}
.badge.hot{
    color:var(--main);
    background:var(--soft);
    border-color:var(--main);
}
.active-card{
    padding:26px;
    border-radius:30px;
    background:linear-gradient(135deg,var(--soft),#ffffff08);
    border:1px solid var(--main);
    text-align:center;
    box-shadow:0 20px 65px var(--glow1);
}
.active-card .big-icon{font-size:50px;margin-bottom:8px}
.active-card b{display:block;font-size:23px}
.active-card span{display:block;margin-top:9px;color:var(--main);font-weight:900}
.stats{
    display:grid;
    grid-template-columns:repeat(5,1fr);
    gap:16px;
    margin-bottom:24px;
}
.stat{
    padding:20px;
    border-radius:24px;
    background:linear-gradient(145deg,#151b31cc,#0d1224dd);
    border:1px solid #ffffff14;
    box-shadow:0 18px 55px #0006;
}
.stat span{display:block;color:#aeb7d4;font-size:13px;margin-bottom:8px}
.stat strong{font-size:18px;line-height:1.4}
.stat.online strong{color:#22c55e}
.stat.warning strong{color:#f5b642}
.stat.offline strong{color:#ff5d5d}
.main-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:24px;
    margin-bottom:24px;
}
.panel{
    position:relative;
    overflow:hidden;
    padding:30px;
    border-radius:32px;
    background:linear-gradient(145deg,#151b31cc,#0d1224dd);
    border:1px solid #ffffff18;
    box-shadow:0 25px 80px #0009;
}
.panel:before{
    content:"";
    position:absolute;
    width:240px;
    height:240px;
    right:-110px;
    bottom:-110px;
    border-radius:50%;
    background:var(--soft);
}
.panel-inner{position:relative}
.panel h2{margin:0 0 10px;font-size:26px}
.panel p{margin:0 0 22px;color:#b8c1df;line-height:1.7}
.features{
    display:grid;
    grid-template-columns:repeat(2,1fr);
    gap:14px;
}
.feature{
    padding:18px;
    border-radius:22px;
    background:#ffffff0c;
    border:1px solid #ffffff14;
}
.feature b{display:block;margin-bottom:8px}
.feature span{color:#aeb7d4;font-size:13px;line-height:1.6}
.renew-btn{
    display:inline-flex;
    margin-top:24px;
    align-items:center;
    justify-content:center;
    gap:10px;
    padding:16px 24px;
    border-radius:18px;
    background:linear-gradient(135deg,var(--main),var(--main2));
    color:#fff;
    font-weight:900;
    box-shadow:0 18px 42px var(--glow1);
}
.history{
    padding:30px;
    border-radius:32px;
    background:linear-gradient(145deg,#151b31cc,#0d1224dd);
    border:1px solid #ffffff18;
    box-shadow:0 25px 80px #0009;
    overflow:auto;
}
.history h2{margin:0 0 20px;font-size:27px;color:var(--main)}
table{width:100%;border-collapse:collapse;min-width:980px}
th{
    text-align:left;
    color:var(--main);
    font-size:14px;
    padding:16px 14px;
    border-bottom:1px solid #ffffff12;
}
td{
    padding:17px 14px;
    border-bottom:1px solid #ffffff10;
    color:#f8fafc;
    vertical-align:middle;
}
.type-pill{
    display:inline-flex;
    padding:9px 13px;
    border-radius:999px;
    font-size:12px;
    font-weight:900;
    border:1px solid currentColor;
}
.type-gold{color:#f5b642;background:#f5b64218}
.type-premium{color:#38bdf8;background:#38bdf818}
.type-vip{color:#ff5db1;background:#ff5db118}
.status-pill{
    display:inline-flex;
    padding:9px 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:900;
}
.status-active{
    color:#86efac;
    background:#22c55e22;
    border:1px solid #22c55e66;
    box-shadow:0 0 22px #22c55e33;
}
.status-cancelled,
.status-expired{
    color:#ffb4b4;
    background:#ef444422;
    border:1px solid #ef444466;
    filter:grayscale(.15);
}
.offline-row{
    opacity:.55;
    filter:grayscale(.55);
}
.empty{
    padding:28px;
    border-radius:28px;
    background:#ffffff0c;
    border:1px dashed #ffffff28;
    color:#cbd5e1;
    line-height:1.7;
}
.quick-actions{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:16px;
    margin-top:24px;
}
.quick{
    padding:20px;
    border-radius:24px;
    background:linear-gradient(145deg,#151b31cc,#0d1224dd);
    border:1px solid #ffffff14;
    box-shadow:0 18px 55px #0006;
    transition:.25s;
}
.quick:hover{transform:translateY(-5px);border-color:var(--main)}
.quick b{display:block;font-size:17px;margin-bottom:8px}
.quick span{color:#aeb7d4;font-size:13px}
.admin-footer{
    margin-top:30px;
    padding:18px 24px;
    width:100%;
    display:grid;
    grid-template-columns:minmax(280px,1.25fr) minmax(220px,.9fr) minmax(260px,1fr);
    align-items:center;
    gap:18px;
    border-top:1px solid rgba(255,255,255,.08);
    background:linear-gradient(180deg,rgba(255,255,255,.04),rgba(255,255,255,.015));
    color:#9aa3b2;
    font-size:12px;
    font-weight:800;
    border-radius:24px;
}
.footer-left{display:flex;align-items:center;gap:6px;white-space:nowrap}
.footer-link{color:var(--main);font-weight:900}
.footer-center{text-align:center;color:var(--main);font-size:13px;font-weight:900}
.footer-right{display:flex;align-items:center;justify-content:flex-end;white-space:nowrap}
.footer-signature{color:#ff5db1;font-size:14px;font-weight:900}
.footer-whatsapp img{width:52px;height:52px;object-fit:contain;filter:drop-shadow(0 0 10px rgba(37,211,102,.8))}
@media(max-width:1200px){
    .hero-inner{grid-template-columns:150px 1fr}
    .active-card{grid-column:1 / -1}
    .stats{grid-template-columns:repeat(2,1fr)}
    .main-grid{grid-template-columns:1fr}
}
@media(max-width:900px){
    .hero-inner{display:flex;flex-direction:column;text-align:center}
    .badges{justify-content:center}
    .quick-actions{grid-template-columns:repeat(2,1fr)}
    .admin-footer{grid-template-columns:1fr;text-align:center;justify-items:center}
    .footer-left,.footer-right{justify-content:center;flex-wrap:wrap}
}
@media(max-width:600px){
    .wrap{padding:18px}
    .topbar{flex-direction:column;align-items:flex-start}
    .stats,.features,.quick-actions{grid-template-columns:1fr}
    .hero,.panel,.history{padding:22px}
    .hero h2{font-size:28px}
}
</style>
</head>
<body class="<?= e($theme['class']) ?>">

<div class="wrap">

    <div class="topbar">
        <div>
            <h1><?= e($theme['title']) ?></h1>
            <p>Aktif paketine göre özel hazırlanmış üyelik ekranın.</p>
        </div>
        <a class="dashboard-btn" href="index.php">⚡ Kontrol Merkezine Dön</a>
    </div>

    <section class="hero">
        <div class="hero-inner">

            <div class="avatar">
                <img src="<?= e((string)$image) ?>" alt="Profil Resmi">
                <span class="dot"></span>
            </div>

            <div>
                <h2><?= e((string)$name) ?></h2>
                <p><?= e((string)$email) ?></p>
                <p><?= e($theme['hero']) ?></p>

                <div class="badges">
                    <span class="badge hot"><?= e($theme['icon']) ?> <?= e($theme['label']) ?> AKTİF</span>
                    <span class="badge">🎮 Okey Üye Paneli</span>
                    <span class="badge">🛡️ Yönetim Onaylı Paket</span>
                </div>
            </div>

            <div class="active-card">
                <div class="big-icon"><?= e($theme['icon']) ?></div>
                <b><?= e((string)$activeName) ?></b>
                <span><?= e($activeRemain['text']) ?></span>
            </div>

        </div>
    </section>

    <section class="stats">
        <div class="stat">
            <span>Paket Türü</span>
            <strong><?= strtoupper(e($activeType)) ?></strong>
        </div>

        <div class="stat">
            <span>Paket Adı</span>
            <strong><?= e((string)$activeName) ?></strong>
        </div>

        <div class="stat">
            <span>Miktar</span>
            <strong><?= e((string)$activeAmount) ?></strong>
        </div>

        <div class="stat">
            <span>Fiyat</span>
            <strong><?= e((string)$activePrice) ?> ₺</strong>
        </div>

        <div class="stat <?= e($activeRemain['class']) ?>">
            <span>Kalan Süre</span>
            <strong><?= e($activeRemain['text']) ?></strong>
        </div>
    </section>

    <section class="main-grid">

        <div class="panel">
            <div class="panel-inner">
                <h2><?= e($theme['icon']) ?> Aktif Paket Kartı</h2>
                <p><?= e((string)$activeDesc) ?></p>

                <div class="features">
                    <div class="feature">
                        <b>Başlangıç</b>
                        <span><?= e(tr_date($activeStart)) ?></span>
                    </div>

                    <div class="feature">
                        <b>Bitiş</b>
                        <span><?= e(tr_date($activeEnd)) ?></span>
                    </div>

                    <div class="feature">
                        <b>Süre</b>
                        <span><?= e((string)$activeDuration) ?></span>
                    </div>

                    <div class="feature">
                        <b>Durum</b>
                        <span>Aktif / Kullanımda</span>
                    </div>
                </div>

                <a href="renew-package.php" class="renew-btn">🚀 Paket Talep Et / Yenile</a>
            </div>
        </div>

        <div class="panel">
            <div class="panel-inner">
                <h2>Üyelik Hissi</h2>
                <p>
                    Bu sayfa paketin türüne göre şekillenir. Gold, Premium ve VIP üyeler
                    farklı renk, farklı kart ve farklı görünümle karşılanır.
                </p>

                <div class="features">
                    <div class="feature">
                        <b>Gold</b>
                        <span>Altın renkli, parlak oyuncu paketi.</span>
                    </div>

                    <div class="feature">
                        <b>Premium</b>
                        <span>Mavi/mor özel üyelik görünümü.</span>
                    </div>

                    <div class="feature">
                        <b>VIP</b>
                        <span>Pembe/mor en üst seviye üyelik.</span>
                    </div>

                    <div class="feature">
                        <b>Offline</b>
                        <span>Kapalı paketler gri ve pasif görünür.</span>
                    </div>
                </div>
            </div>
        </div>

    </section>

    <section class="history">
        <h2>Paket Geçmişi</h2>

        <?php if (empty($packages)): ?>
            <div class="empty">
                Henüz hesabına atanmış paket bulunmuyor. Paket talebi göndermek için Paket Talep Et sayfasını kullanabilirsin.
            </div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>Paket Türü</th>
                        <th>Paket Adı</th>
                        <th>Miktar</th>
                        <th>Fiyat</th>
                        <th>Başlangıç</th>
                        <th>Bitiş</th>
                        <th>Durum</th>
                        <th>Atanma</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($packages as $pkg): ?>
                        <?php
                            $rowType = strtolower((string)($pkg['package_type'] ?? 'gold'));
                            $rowStatus = strtolower((string)($pkg['status'] ?? 'active'));
                            $isOffline = $rowStatus !== 'active';
                            $rowName = $pkg['title'] ?: $pkg['package_name'];
                        ?>
                        <tr class="<?= $isOffline ? 'offline-row' : '' ?>">
                            <td>
                                <span class="type-pill type-<?= e($rowType) ?>">
                                    <?= strtoupper(e($rowType)) ?>
                                </span>
                            </td>

                            <td><strong><?= e((string)$rowName) ?></strong></td>
                            <td><?= e((string)($pkg['amount'] ?? '0')) ?></td>
                            <td><?= e((string)($pkg['price'] ?? '-')) ?> ₺</td>
                            <td><?= e(tr_date($pkg['start_date'] ?? null)) ?></td>
                            <td><?= e(tr_date($pkg['end_date'] ?? null)) ?></td>

                            <td>
                                <span class="status-pill status-<?= e($rowStatus) ?>">
                                    <?= e($rowStatus) ?>
                                </span>
                            </td>

                            <td><?= e(tr_date($pkg['created_at'] ?? null)) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </section>

    <section class="quick-actions">
        <a class="quick" href="profile.php">
            <b>👤 Profilim</b>
            <span>Profil ve şifre bilgilerini yönet.</span>
        </a>

        <a class="quick" href="renew-package.php">
            <b>🔄 Paket Talep Et</b>
            <span>Aktif paketlerden seçim yap.</span>
        </a>

        <a class="quick" href="support.php">
            <b>💬 Admin Destek</b>
            <span>Yönetim ekibiyle iletişim kur.</span>
        </a>

        <a class="quick" href="logout.php">
            <b>🚪 Güvenli Çıkış</b>
            <span>Hesabından güvenli şekilde çık.</span>
        </a>
    </section>

    <footer class="admin-footer">
        <div class="footer-left">
            <span>Powered By <?= date('Y') ?></span>
            <a href="https://www.radyohost.biz" target="_blank" rel="noopener" class="footer-link">🌐 RadyoHost.BiZ</a>
            <span>Web Teknolojileri</span>
        </div>

        <div class="footer-center">
            Premium Okey Üye Paneli
        </div>

        <div class="footer-right">
            <span class="footer-signature">Developed By VoLKaN75</span>
            <a href="https://wa.me/905415917536" target="_blank" rel="noopener" class="footer-whatsapp">
                <img src="../uploads/footer/whatsapp.png" alt="WhatsApp">
            </a>
        </div>
    </footer>

</div>

</body>
</html>