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

/*
|--------------------------------------------------------------------------
| ÜYE DETAY EKRANI
|--------------------------------------------------------------------------
| user-detail.php
| Okey Platformu Premium Üye Detay ve Paket Geçmişi Sayfası
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Üye Detayı';
$pageDescription = 'Üye profilini, aktif paketini ve paket geçmişini görüntüleyin.';

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

$userId = (int)($_GET['id'] ?? 0);
$user = [];
$activePackage = [];
$packageHistory = [];
$message = '';
$messageType = '';

function user_detail_e($value): string
{
    return function_exists('admin_e')
        ? admin_e($value)
        : htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function package_emoji(string $type): string
{
    return match ($type) {
        'gold' => '🥇',
        'premium' => '👑',
        'vip' => '💎',
        default => '🎮',
    };
}

function package_badge(string $type): string
{
    return match ($type) {
        'gold' => 'badge-gold',
        'premium' => 'badge-premium',
        'vip' => 'badge-vip',
        default => 'badge-empty',
    };
}

if ($userId <= 0) {
    $message = 'Geçersiz üye ID.';
    $messageType = 'error';
} else {
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        if (!$user) {
            throw new RuntimeException('Üye kaydı bulunamadı.');
        }

        $stmt = $pdo->prepare("
            SELECT
                up.*,
                p.title AS package_title,
                p.amount AS package_amount,
                p.duration AS package_duration,
                p.price AS package_price,
                p.description AS package_description
            FROM user_packages up
            LEFT JOIN packages p ON p.id = up.package_id
            WHERE up.user_id = ?
            ORDER BY up.id DESC
            LIMIT 1
        ");
        $stmt->execute([$userId]);
        $activePackage = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        $stmt = $pdo->prepare("
            SELECT
                up.*,
                p.title AS package_title,
                p.amount AS package_amount,
                p.duration AS package_duration,
                p.price AS package_price
            FROM user_packages up
            LEFT JOIN packages p ON p.id = up.package_id
            WHERE up.user_id = ?
            ORDER BY up.id DESC
        ");
        $stmt->execute([$userId]);
        $packageHistory = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        $message = $e->getMessage();
        $messageType = 'error';
    }
}

$image = trim((string)($user['image'] ?? ''));
$imagePath = '';

if ($image !== '') {
    $imagePath = str_starts_with($image, 'uploads/')
        ? '../' . $image
        : '../uploads/users/' . $image;
}

$type = strtolower((string)($activePackage['package_type'] ?? ''));
$status = strtolower((string)($activePackage['status'] ?? ''));
$packageName = $activePackage['package_name'] ?? ($activePackage['package_title'] ?? 'Paket Yok');

$remaining = 'Paket Yok';
if (!empty($activePackage['end_date'])) {
    $endTime = strtotime((string)$activePackage['end_date']);
    if ($endTime !== false) {
        $days = (int)ceil(($endTime - time()) / 86400);
        $remaining = $days <= 0 ? 'Bitti' : $days . ' Gün';
    }
} elseif ($activePackage) {
    $remaining = 'Süresiz';
}
?>

<style>
.user-detail-page{display:grid;gap:24px}
.detail-hero{position:relative;overflow:hidden;padding:34px;border-radius:36px;background:radial-gradient(circle at top right,rgba(245,182,66,.28),transparent 35%),radial-gradient(circle at bottom left,rgba(185,0,0,.22),transparent 38%),linear-gradient(135deg,rgba(255,255,255,.08),rgba(255,255,255,.035));border:1px solid rgba(255,255,255,.10);box-shadow:0 28px 80px rgba(0,0,0,.22)}
.detail-hero-inner{display:flex;align-items:center;justify-content:space-between;gap:28px;flex-wrap:wrap;position:relative;z-index:2}
.profile-main{display:flex;align-items:center;gap:22px}
.profile-avatar{width:150px;height:150px;border-radius:42px;padding:5px;background:linear-gradient(135deg,#f5b642,#b90000);box-shadow:0 25px 55px rgba(0,0,0,.38)}
.profile-avatar img{width:100%;height:100%;object-fit:cover;border-radius:38px;background:#111}
.avatar-letter{width:100%;height:100%;border-radius:38px;display:flex;align-items:center;justify-content:center;background:#111;color:#f5b642;font-size:62px;font-weight:1000}
.profile-title h2{margin:0 0 8px;color:#fff;font-size:40px;line-height:1}
.profile-title p{margin:0;color:#aeb7c7;font-weight:800}
.hero-badges{display:flex;gap:10px;flex-wrap:wrap;margin-top:16px}
.big-package{min-width:280px;padding:24px;border-radius:30px;background:rgba(0,0,0,.26);border:1px solid rgba(255,255,255,.10)}
.big-package .emoji{font-size:42px;margin-bottom:10px}
.big-package strong{display:block;color:#f5b642;font-size:24px;margin-bottom:8px}
.big-package span{color:#dce3ef;font-weight:800}
.stats-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}
.stat-card{padding:22px;border-radius:26px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.09)}
.stat-card small{display:block;color:#9aa3b2;font-weight:900;margin-bottom:8px}
.stat-card strong{display:block;color:#fff;font-size:21px}
.detail-grid{display:grid;grid-template-columns:.42fr 1fr;gap:22px}
.detail-card{padding:26px;border-radius:30px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.09);box-shadow:0 22px 65px rgba(0,0,0,.16)}
.detail-card h3{margin:0 0 18px;color:#f5b642;font-size:23px}
.info-list{display:grid;gap:12px}
.info-row{display:flex;justify-content:space-between;gap:12px;padding:14px;border-radius:17px;background:rgba(0,0,0,.22);border:1px solid rgba(255,255,255,.07)}
.info-row small{color:#9aa3b2;font-weight:900}
.info-row b{color:#dce3ef;text-align:right}
.package-panel{display:grid;grid-template-columns:repeat(2,1fr);gap:14px}
.package-box{padding:18px;border-radius:20px;background:rgba(0,0,0,.22);border:1px solid rgba(255,255,255,.07)}
.package-box small{display:block;color:#9aa3b2;font-weight:900;margin-bottom:8px}
.package-box b{color:#fff;font-size:16px}
.history-table-wrap{width:100%;overflow-x:auto}
.history-table{width:100%;min-width:900px;border-collapse:collapse}
.history-table th,.history-table td{padding:15px;border-bottom:1px solid rgba(255,255,255,.07);text-align:left;color:#dce3ef;font-size:14px}
.history-table th{color:#f5b642;background:rgba(0,0,0,.18);font-weight:900}
.badge{display:inline-flex;min-height:30px;padding:0 12px;border-radius:999px;align-items:center;justify-content:center;font-size:12px;font-weight:900;white-space:nowrap}
.badge-gold{background:rgba(245,182,66,.14);color:#f5b642;border:1px solid rgba(245,182,66,.25)}
.badge-premium{background:rgba(100,180,255,.14);color:#9fd0ff;border:1px solid rgba(100,180,255,.25)}
.badge-vip{background:rgba(255,93,177,.14);color:#ff8fcb;border:1px solid rgba(255,93,177,.25)}
.badge-active{background:rgba(0,150,70,.18);color:#d8ffe8;border:1px solid rgba(0,255,120,.25)}
.badge-expired{background:rgba(255,180,0,.14);color:#f5b642;border:1px solid rgba(245,182,66,.24)}
.badge-cancelled,.badge-passive{background:rgba(185,0,0,.18);color:#ffdede;border:1px solid rgba(255,80,80,.25)}
.badge-empty{background:rgba(255,255,255,.08);color:#9aa3b2;border:1px solid rgba(255,255,255,.12)}
.action-row{display:flex;gap:10px;flex-wrap:wrap;margin-top:18px}
.form-alert{padding:15px 18px;border-radius:16px;font-weight:800}
.form-alert.error{background:rgba(185,0,0,.20);border:1px solid rgba(255,80,80,.30);color:#ffdede}
.empty-state{padding:25px;text-align:center;color:#aeb7c7;font-weight:800}
@media(max-width:1100px){.detail-grid{grid-template-columns:1fr}.stats-grid,.package-panel{grid-template-columns:repeat(2,1fr)}}
@media(max-width:700px){.profile-main{display:block;text-align:center}.profile-avatar{margin:0 auto 18px}.stats-grid,.package-panel{grid-template-columns:1fr}.big-package{min-width:100%}}
</style>

<section class="user-detail-page">

    <?php if ($message !== ''): ?>
        <div class="form-alert <?= user_detail_e($messageType) ?>">
            <?= user_detail_e($message) ?>
        </div>
    <?php endif; ?>

    <?php if ($user): ?>
        <div class="detail-hero">
            <div class="detail-hero-inner">
                <div class="profile-main">
                    <div class="profile-avatar">
                        <?php if ($imagePath !== ''): ?>
                            <img src="<?= user_detail_e($imagePath) ?>" alt="<?= user_detail_e($user['name'] ?? 'Üye') ?>">
                        <?php else: ?>
                            <div class="avatar-letter">
                                <?= user_detail_e(mb_substr((string)($user['name'] ?? $user['username'] ?? 'U'), 0, 1, 'UTF-8')) ?>
                            </div>
                        <?php endif; ?>
                    </div>

                    <div class="profile-title">
                        <h2><?= user_detail_e($user['name'] ?? '-') ?></h2>
                        <p>@<?= user_detail_e($user['username'] ?? '-') ?> · <?= user_detail_e($user['email'] ?? '-') ?></p>

                        <div class="hero-badges">
                            <span class="badge <?= user_detail_e(package_badge($type)) ?>">
                                <?= user_detail_e(strtoupper($type ?: 'PAKET YOK')) ?>
                            </span>

                            <?php if (($user['status'] ?? '') === 'active'): ?>
                                <span class="badge badge-active">Üye Aktif</span>
                            <?php else: ?>
                                <span class="badge badge-passive"><?= user_detail_e($user['status'] ?? 'Pasif') ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="big-package">
                    <div class="emoji"><?= user_detail_e(package_emoji($type)) ?></div>
                    <strong><?= user_detail_e($packageName) ?></strong>
                    <span><?= user_detail_e($remaining) ?> kalan üyelik durumu.</span>
                </div>
            </div>
        </div>

        <div class="stats-grid">
            <div class="stat-card">
                <small>Paket Fiyatı</small>
                <strong><?= !empty($activePackage['package_price']) ? user_detail_e(number_format((float)$activePackage['package_price'], 2, ',', '.')) . ' ₺' : '-' ?></strong>
            </div>

            <div class="stat-card">
                <small>Paket Miktarı</small>
                <strong><?= user_detail_e($activePackage['package_amount'] ?? '0') ?></strong>
            </div>

            <div class="stat-card">
                <small>Kalan Süre</small>
                <strong><?= user_detail_e($remaining) ?></strong>
            </div>

            <div class="stat-card">
                <small>Paket Durumu</small>
                <strong><?= user_detail_e($status ?: 'Yok') ?></strong>
            </div>
        </div>

        <div class="detail-grid">
            <aside class="detail-card">
                <h3>Üye Bilgileri</h3>

                <div class="info-list">
                    <div class="info-row"><small>Ad Soyad</small><b><?= user_detail_e($user['name'] ?? '-') ?></b></div>
                    <div class="info-row"><small>Kullanıcı Adı</small><b>@<?= user_detail_e($user['username'] ?? '-') ?></b></div>
                    <div class="info-row"><small>E-Posta</small><b><?= user_detail_e($user['email'] ?? '-') ?></b></div>
                    <div class="info-row"><small>Telefon</small><b><?= user_detail_e($user['phone'] ?? '-') ?></b></div>
                    <div class="info-row"><small>Rol</small><b><?= user_detail_e($user['role'] ?? 'user') ?></b></div>
                    <div class="info-row"><small>Kayıt Tarihi</small><b><?= user_detail_e($user['created_at'] ?? '-') ?></b></div>
                </div>

                <div class="action-row">
                    <a href="user-edit.php?id=<?= user_detail_e($userId) ?>" class="admin-btn">Üye Düzenle</a>
                    <a href="memberships.php" class="admin-btn admin-btn-dark">Üyeliklere Dön</a>
                </div>
            </aside>

            <div class="detail-card">
                <h3>Aktif Paket Detayı</h3>

                <?php if ($activePackage): ?>
                    <div class="package-panel">
                        <div class="package-box"><small>Paket Türü</small><b><?= user_detail_e(strtoupper($type)) ?></b></div>
                        <div class="package-box"><small>Paket Adı</small><b><?= user_detail_e($packageName) ?></b></div>
                        <div class="package-box"><small>Süre</small><b><?= user_detail_e($activePackage['package_duration'] ?? '-') ?></b></div>
                        <div class="package-box"><small>Başlangıç</small><b><?= user_detail_e($activePackage['start_date'] ?? '-') ?></b></div>
                        <div class="package-box"><small>Bitiş</small><b><?= user_detail_e($activePackage['end_date'] ?? '-') ?></b></div>
                        <div class="package-box"><small>Atanma Tarihi</small><b><?= user_detail_e($activePackage['created_at'] ?? '-') ?></b></div>
                    </div>

                    <div class="action-row">
                        <a href="membership-edit.php?id=<?= user_detail_e($activePackage['id'] ?? '') ?>" class="admin-btn">Üyelik Düzenle</a>
                        <a href="membership-view.php?user_id=<?= user_detail_e($userId) ?>" class="admin-btn admin-btn-dark">Yeni Paket Tanımla</a>
                    </div>
                <?php else: ?>
                    <div class="empty-state">Bu üyeye henüz paket tanımlanmamış.</div>
                    <div class="action-row">
                        <a href="membership-view.php?user_id=<?= user_detail_e($userId) ?>" class="admin-btn">Paket Tanımla</a>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="detail-card">
            <h3>Paket Geçmişi</h3>

            <div class="history-table-wrap">
                <table class="history-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 if ($packageHistory): ?>
                        <?php foreach ($packageHistory as $package): ?>
                            <?php
                                $historyType = strtolower((string)($package['package_type'] ?? ''));
                                $historyStatus = strtolower((string)($package['status'] ?? ''));
                            ?>
                            <tr>
                                <td><span class="badge <?= user_detail_e(package_badge($historyType)) ?>"><?= user_detail_e(strtoupper($historyType ?: '-')) ?></span></td>
                                <td><?= user_detail_e($package['package_name'] ?: ($package['package_title'] ?? '-')) ?></td>
                                <td><?= user_detail_e($package['package_amount'] ?? '0') ?></td>
                                <td><?= !empty($package['package_price']) ? user_detail_e(number_format((float)$package['package_price'], 2, ',', '.')) . ' ₺' : '-' ?></td>
                                <td><?= user_detail_e($package['start_date'] ?? '-') ?></td>
                                <td><?= user_detail_e($package['end_date'] ?? '-') ?></td>
                                <td><span class="badge badge-<?= user_detail_e($historyStatus ?: 'empty') ?>"><?= user_detail_e($historyStatus ?: '-') ?></span></td>
                                <td><?= user_detail_e($package['created_at'] ?? '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8">
                                <div class="empty-state">Paket geçmişi bulunamadı.</div>
                            </td>
                        </tr>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>

</section>

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