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

/*
|--------------------------------------------------------------------------
| ÜYE YÖNETİMİ
|--------------------------------------------------------------------------
| users.php
| Okey Platformu Üye Listeleme ve Paket Durumu Yönetimi
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Üye Yönetimi';
$pageDescription = 'Okey Platformu kullanıcılarını ve atanmış paket durumlarını yönetin.';

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

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

function users_table_exists(PDO $pdo, string $table): bool
{
    try {
        $stmt = $pdo->prepare("SHOW TABLES LIKE ?");
        $stmt->execute([$table]);
        return (bool)$stmt->fetchColumn();
    } catch (Throwable $e) {
        return false;
    }
}

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

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

try {
    if (isset($pdo) && $pdo instanceof PDO) {
        if (users_table_exists($pdo, 'user_packages')) {
            $stmt = $pdo->query("
                SELECT
                    u.*,
                    up.package_type,
                    up.package_name,
                    up.start_date,
                    up.end_date,
                    up.status AS package_status
                FROM users u
                LEFT JOIN user_packages up
                    ON up.user_id = u.id
                    AND up.id = (
                        SELECT up2.id
                        FROM user_packages up2
                        WHERE up2.user_id = u.id
                        ORDER BY up2.id DESC
                        LIMIT 1
                    )
                ORDER BY u.id DESC
            ");
        } else {
            $stmt = $pdo->query("
                SELECT
                    u.*,
                    NULL AS package_type,
                    NULL AS package_name,
                    NULL AS start_date,
                    NULL AS end_date,
                    NULL AS package_status
                FROM users u
                ORDER BY u.id DESC
            ");
        }

        $users = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    }
} catch (Throwable $e) {
    $message = 'Üye listesi alınırken sistem hatası oluştu.';
    $messageType = 'error';
}
?>

<style>
.users-page{
    display:grid;
    gap:22px;
}

.users-hero{
    padding:28px;
    border-radius:32px;
    background:
        radial-gradient(circle at top left,rgba(245,182,66,.18),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);
}

.users-hero h2{
    margin:0 0 8px;
    color:#f5b642;
    font-size:28px;
}

.users-hero p{
    margin:0;
    color:#aeb7c7;
    font-weight:700;
    line-height:1.6;
}

.users-actions{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:14px;
    flex-wrap:wrap;
}

.users-card{
    overflow:hidden;
    border-radius:30px;
    background:rgba(255,255,255,.055);
    border:1px solid rgba(255,255,255,.09);
}

.users-table-wrap{
    width:100%;
    overflow-x:auto;
}

.users-table{
    width:100%;
    border-collapse:collapse;
    min-width:1050px;
}

.users-table th,
.users-table td{
    padding:16px;
    border-bottom:1px solid rgba(255,255,255,.07);
    text-align:left;
    vertical-align:middle;
    color:#dce3ef;
    font-size:14px;
}

.users-table th{
    color:#f5b642;
    font-weight:900;
    background:rgba(0,0,0,.18);
}

.users-table tr:hover td{
    background:rgba(255,255,255,.035);
}

.user-info{
    display:flex;
    align-items:center;
    gap:12px;
    min-width:220px;
}

.user-avatar{
    width:46px;
    height:46px;
    border-radius:16px;
    overflow:hidden;
    background:linear-gradient(135deg,#f5b642,#b90000);
    display:flex;
    align-items:center;
    justify-content:center;
    color:#111;
    font-weight:900;
    flex:0 0 auto;
}

.user-avatar img{
    width:100%;
    height:100%;
    object-fit:cover;
}

.user-info strong{
    display:block;
    color:#fff;
    margin-bottom:4px;
}

.user-info span{
    display:block;
    color:#9aa3b2;
    font-size:12px;
    font-weight:700;
}

.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-height:30px;
    padding:0 11px;
    border-radius:999px;
    font-size:12px;
    font-weight:900;
    white-space:nowrap;
}

.badge-active{
    background:rgba(0,150,70,.18);
    color:#d8ffe8;
    border:1px solid rgba(0,255,120,.25);
}

.badge-passive{
    background:rgba(185,0,0,.18);
    color:#ffdede;
    border:1px solid rgba(255,80,80,.25);
}

.badge-package{
    background:rgba(245,182,66,.13);
    color:#f5b642;
    border:1px solid rgba(245,182,66,.22);
}

.badge-empty{
    background:rgba(255,255,255,.07);
    color:#9aa3b2;
    border:1px solid rgba(255,255,255,.10);
}

.action-group{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
}

.small-btn{
    min-height:36px;
    padding:0 12px;
    border-radius:12px;
    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;
}

.empty-state{
    padding:28px;
    text-align:center;
    color:#aeb7c7;
    font-weight:700;
}

.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;
}

@media(max-width:760px){
    .users-actions{
        display:block;
    }

    .users-actions .admin-btn{
        margin-top:12px;
    }
}
</style>

<section class="users-page">

    <div class="users-hero">
        <h2>Üye Yönetimi</h2>
        <p>Kullanıcıları listeleyin, düzenleyin ve Gold / Premium / VIP paket durumlarını takip edin.</p>
    </div>

    <div class="users-actions">
        <div>
            <strong style="color:#fff;">Toplam Üye: <?= users_e((string)count($users)) ?></strong>
        </div>

        <a href="user-view.php" class="admin-btn">Yeni Üye Oluştur</a>
    </div>

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

    <div class="users-card">
        <div class="users-table-wrap">
            <table class="users-table">
                <thead>
                    <tr>
                        <th>Üye</th>
                        <th>E-Posta</th>
                        <th>Telefon</th>
                        <th>Rol</th>
                        <th>Durum</th>
                        <th>Paket</th>
                        <th>Paket Bitiş</th>
                        <th>İşlem</th>
                    </tr>
                </thead>

                <tbody>
                <?php if ($users): ?>
                    <?php foreach ($users as $user): ?>
                        <?php
                            $image = trim((string)($user['image'] ?? ''));
                            $imagePath = '';

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

                            $packageType = trim((string)($user['package_type'] ?? ''));
                            $packageName = trim((string)($user['package_name'] ?? ''));
                            $packageStatus = trim((string)($user['package_status'] ?? ''));
                            $endDate = trim((string)($user['end_date'] ?? ''));
                        ?>
                        <tr>
                            <td>
                                <div class="user-info">
                                    <div class="user-avatar">
                                        <?php if ($imagePath !== ''): ?>
                                            <img src="<?= users_e($imagePath) ?>" alt="">
                                        <?php else: ?>
                                            <?= users_e(mb_substr((string)($user['name'] ?? $user['username'] ?? 'U'), 0, 1, 'UTF-8')) ?>
                                        <?php endif; ?>
                                    </div>

                                    <div>
                                        <strong><?= users_e($user['name'] ?? '-') ?></strong>
                                        <span>@<?= users_e($user['username'] ?? '-') ?></span>
                                    </div>
                                </div>
                            </td>

                            <td><?= users_e($user['email'] ?? '-') ?></td>
                            <td><?= users_e($user['phone'] ?? '-') ?></td>
                            <td><?= users_e($user['role'] ?? 'user') ?></td>

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

                            <td>
                                <?php if ($packageType !== ''): ?>
                                    <span class="badge badge-package">
                                        <?= users_e(strtoupper($packageType)) ?>
                                        <?= $packageName !== '' ? ' / ' . users_e($packageName) : '' ?>
                                    </span>
                                <?php else: ?>
                                    <span class="badge badge-empty">Paket Yok</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?= $endDate !== '' ? users_e($endDate) : '-' ?>
                                <?php if ($packageStatus !== ''): ?>
                                    <br>
                                    <small style="color:#9aa3b2;font-weight:800;">
                                        <?= users_e($packageStatus) ?>
                                    </small>
                                <?php endif; ?>
                            </td>

                            <td>
                                <div class="action-group">
                                    <a href="user-edit.php?id=<?= users_e($user['id'] ?? '') ?>" class="small-btn">Düzenle</a>
                                    <a href="user-detail.php?id=<?= users_e($user['id'] ?? '') ?>" class="small-btn">Detay</a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="8">
                            <div class="empty-state">
                                Henüz kayıtlı üye bulunamadı.
                            </div>
                        </td>
                    </tr>
                <?php endif; ?>
                </tbody>

            </table>
        </div>
    </div>

</section>

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