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

/*
|--------------------------------------------------------------------------
| ÜYELİK YÖNETİMİ
|--------------------------------------------------------------------------
| memberships.php
| Paket satın almış / paket tanımlanmış üyeleri premium kartlı takip ekranı
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Üyelik Yönetimi';
$pageDescription = 'Sadece paket tanımlanmış üyeleri premium kart görünümünde yönetin.';

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

$memberships = [];
$message = '';
$messageType = '';

function memberships_e($value): string
{
    if (function_exists('admin_e')) {
        return admin_e($value);
    }

    return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

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

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

function membership_user_image(array $row): string
{
    $image = trim((string)($row['image'] ?? ''));

    if ($image === '') {
        return '';
    }

    if (str_starts_with($image, 'uploads/')) {
        return '../' . $image;
    }

    return '../uploads/users/' . $image;
}

try {
    if (!isset($pdo) || !$pdo instanceof PDO) {
        throw new RuntimeException('Veritabanı bağlantısı bulunamadı.');
    }

    $stmt = $pdo->query("
        SELECT
            up.id AS membership_id,
            up.user_id,
            up.package_id,
            up.package_type,
            up.package_name,
            up.start_date,
            up.end_date,
            up.status AS membership_status,
            up.created_at AS membership_created_at,

            u.name,
            u.username,
            u.email,
            u.phone,
            u.image,
            u.status AS user_status,

            p.title AS package_title,
            p.amount AS package_amount,
            p.duration AS package_duration,
            p.price AS package_price
        FROM user_packages up
        INNER JOIN users u ON u.id = up.user_id
        LEFT JOIN packages p ON p.id = up.package_id
        WHERE up.id = (
            SELECT up2.id
            FROM user_packages up2
            WHERE up2.user_id = up.user_id
            ORDER BY up2.id DESC
            LIMIT 1
        )
        ORDER BY up.id DESC
    ");

    $memberships = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    $message = 'Üyelik kayıtları okunamadı. Veritabanı bağlantısını ve tablo kolonlarını kontrol edin.';
    $messageType = 'error';
}

$totalPackageUsers = count($memberships);
$activePackage = 0;
$expiredPackage = 0;
$cancelledPackage = 0;

foreach ($memberships as $row) {
    $status = strtolower((string)($row['membership_status'] ?? ''));

    if ($status === 'active') {
        $activePackage++;
    } elseif ($status === 'expired') {
        $expiredPackage++;
    } elseif ($status === 'cancelled') {
        $cancelledPackage++;
    }
}
?>

<style>
.memberships-page{display:grid;gap:22px}
.memberships-hero{padding:28px;border-radius:32px;background:radial-gradient(circle at top left,rgba(245,182,66,.20),transparent 34%),linear-gradient(135deg,rgba(255,255,255,.075),rgba(255,255,255,.035));border:1px solid rgba(255,255,255,.09);box-shadow:0 24px 70px rgba(0,0,0,.18)}
.memberships-hero h2{margin:0 0 8px;color:#f5b642;font-size:28px}
.memberships-hero p{margin:0;color:#aeb7c7;font-weight:700;line-height:1.6}
.membership-actions{display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap}
.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 strong{display:block;color:#f5b642;font-size:28px;margin-bottom:6px}
.stat-card span{color:#9aa3b2;font-size:13px;font-weight:800}
.member-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:18px}
.member-card{overflow:hidden;border-radius:30px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.09);box-shadow:0 20px 60px rgba(0,0,0,.20);transition:.25s}
.member-card:hover{transform:translateY(-4px);border-color:rgba(245,182,66,.32)}
.member-top{min-height:150px;padding:22px;position:relative;background:radial-gradient(circle at top right,rgba(245,182,66,.22),transparent 38%),linear-gradient(135deg,rgba(0,0,0,.18),rgba(255,255,255,.04));display:flex;align-items:center;justify-content:center}
.member-avatar{width:92px;height:92px;border-radius:50%;padding:4px;background:linear-gradient(135deg,#f5b642,#b90000);box-shadow:0 18px 38px rgba(0,0,0,.35)}
.member-avatar img{width:100%;height:100%;object-fit:cover;border-radius:50%;background:#111}
.avatar-letter{width:100%;height:100%;border-radius:50%;display:flex;align-items:center;justify-content:center;background:#111;color:#f5b642;font-size:38px;font-weight:1000}
.package-emoji{position:absolute;right:22px;top:22px;width:46px;height:46px;border-radius:16px;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.32);border:1px solid rgba(255,255,255,.14);font-size:24px}
.member-body{padding:20px}
.member-head{display:flex;justify-content:space-between;gap:12px;align-items:flex-start;margin-bottom:14px}
.member-head strong{display:block;color:#fff;font-size:18px;margin-bottom:4px}
.member-head span{display:block;color:#9aa3b2;font-size:12px;font-weight:800}
.package-title{color:#f5b642;font-weight:1000;font-size:19px;margin:0 0 14px}
.short-info{display:grid;gap:10px;margin:14px 0}
.info-row{display:flex;justify-content:space-between;gap:12px;padding:11px 13px;border-radius:14px;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;font-size:12px;text-align:right}
.badge{display:inline-flex;min-height:28px;padding:0 10px;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)}
.card-actions{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin-top:14px}
.small-btn{min-height:38px;padding:0 10px;border-radius:13px;display:inline-flex;align-items:center;justify-content:center;background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.10);color:#fff;font-size:12px;font-weight:900;text-decoration:none}
.small-btn:hover{border-color:rgba(245,182,66,.35);color:#f5b642}
.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:30px;text-align:center;color:#aeb7c7;font-weight:800;border-radius:26px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.09)}
@media(max-width:1250px){.member-grid{grid-template-columns:repeat(3,1fr)}}
@media(max-width:980px){.member-grid,.stats-grid{grid-template-columns:repeat(2,1fr)}}
@media(max-width:620px){.member-grid,.stats-grid{grid-template-columns:1fr}.membership-actions{display:block}.membership-actions .admin-btn{margin-top:12px}}
</style>

<section class="memberships-page">

    <div class="memberships-hero">
        <h2>Üyelik Yönetimi</h2>
        <p>Sadece paket tanımlanmış üyeler burada görünür. Paketsiz üyeler için Üyeler bölümünden işlem yapabilirsiniz.</p>
    </div>

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

    <div class="membership-actions">
        <div style="color:#fff;font-weight:900;">
            Paketli Üye: <?= memberships_e((string)$totalPackageUsers) ?>
        </div>

        <a href="membership-view.php" class="admin-btn">Üyeye Paket Tanımla</a>
    </div>

    <div class="stats-grid">
        <div class="stat-card"><strong><?= memberships_e((string)$totalPackageUsers) ?></strong><span>Paketli Üye</span></div>
        <div class="stat-card"><strong><?= memberships_e((string)$activePackage) ?></strong><span>Aktif Paket</span></div>
        <div class="stat-card"><strong><?= memberships_e((string)$expiredPackage) ?></strong><span>Süresi Dolan</span></div>
        <div class="stat-card"><strong><?= memberships_e((string)$cancelledPackage) ?></strong><span>İptal Edilen</span></div>
    </div>

    <?php if ($memberships): ?>
        <div class="member-grid">
            <?php foreach ($memberships as $row): ?>
                <?php
                    $type = strtolower((string)($row['package_type'] ?? ''));
                    $status = strtolower((string)($row['membership_status'] ?? ''));

                    $typeClass = membership_package_badge($type);
                    $emoji = membership_package_emoji($type);

                    $statusClass = match ($status) {
                        'active' => 'badge-active',
                        'expired' => 'badge-expired',
                        'cancelled' => 'badge-cancelled',
                        default => 'badge-empty',
                    };

                    $packageName = $row['package_name'] ?: ($row['package_title'] ?? 'Paket Yok');
                    $userImage = membership_user_image($row);

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

                    $price = !empty($row['package_price'])
                        ? number_format((float)$row['package_price'], 2, ',', '.') . ' ₺'
                        : '-';

                    $startDate = !empty($row['start_date']) ? (string)$row['start_date'] : '-';
                    $nameFirstLetter = mb_substr((string)($row['name'] ?? $row['username'] ?? 'U'), 0, 1, 'UTF-8');
                ?>

                <div class="member-card">
                    <div class="member-top">
                        <div class="package-emoji"><?= memberships_e($emoji) ?></div>

                        <div class="member-avatar">
                            <?php if ($userImage !== ''): ?>
                                <img src="<?= memberships_e($userImage) ?>" alt="<?= memberships_e($row['name'] ?? 'Üye') ?>">
                            <?php else: ?>
                                <div class="avatar-letter"><?= memberships_e($nameFirstLetter) ?></div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="member-body">
                        <div class="member-head">
                            <div>
                                <strong><?= memberships_e($row['name'] ?? '-') ?></strong>
                                <span>@<?= memberships_e($row['username'] ?? '-') ?></span>
                            </div>

                            <span class="badge <?= memberships_e($typeClass) ?>">
                                <?= memberships_e(strtoupper($type ?: '-')) ?>
                            </span>
                        </div>

                        <div class="package-title"><?= memberships_e($packageName) ?></div>

                        <div class="short-info">
                            <div class="info-row"><small>Fiyat</small><b><?= memberships_e($price) ?></b></div>
                            <div class="info-row"><small>Başlangıç</small><b><?= memberships_e($startDate) ?></b></div>
                            <div class="info-row"><small>Kalan Gün</small><b><?= memberships_e($remaining) ?></b></div>
                        </div>

                        <span class="badge <?= memberships_e($statusClass) ?>">
                            <?= memberships_e($status ?: '-') ?>
                        </span>

                        <div class="card-actions">
                            <a href="user-detail.php?id=<?= memberships_e($row['user_id'] ?? '') ?>" class="small-btn">Üye Detay</a>
                            <a href="membership-edit.php?id=<?= memberships_e($row['membership_id'] ?? '') ?>" class="small-btn">Düzenle</a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="empty-state">
            Henüz paket tanımlanmış üye bulunamadı.
        </div>
    <?php endif; ?>

</section>

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