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

/*
|--------------------------------------------------------------------------
| ÜYE DÜZENLEME EKRANI
|--------------------------------------------------------------------------
| user-edit.php
| Okey Platformu Üye Bilgileri ve Premium Paket Atama Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Üye Düzenle';
$pageDescription = 'Üye bilgilerini düzenleyin ve oluşturulmuş paketlerden üyeye paket atayın.';

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

$message = '';
$messageType = '';
$user = [];
$currentPackage = [];
$packages = [];

$userId = (int)($_GET['id'] ?? 0);

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

function user_edit_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 user_edit_has(array $columns, string $column): bool
{
    return in_array($column, $columns, true);
}

function user_edit_upload_image(string $field): string
{
    if (empty($_FILES[$field]['name']) || empty($_FILES[$field]['tmp_name'])) {
        return '';
    }

    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $ext = strtolower(pathinfo((string)$_FILES[$field]['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
        return '';
    }

    $uploadDir = __DIR__ . '/../uploads/users/';

    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }

    $fileName = 'user-' . date('YmdHis') . '-' . bin2hex(random_bytes(5)) . '.' . $ext;
    $target = $uploadDir . $fileName;

    if (move_uploaded_file((string)$_FILES[$field]['tmp_name'], $target)) {
        return $fileName;
    }

    return '';
}

function user_edit_duration_to_days($duration): int
{
    $duration = trim((string)$duration);

    if ($duration === '') {
        return 30;
    }

    preg_match('/\d+/', $duration, $match);

    if (!empty($match[0])) {
        return max(1, (int)$match[0]);
    }

    return 30;
}

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

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) {
            $message = 'Üye kaydı bulunamadı.';
            $messageType = 'error';
        }

        $stmt = $pdo->query("
            SELECT
                id,
                package_type,
                title,
                amount,
                price,
                duration,
                description,
                status,
                created_at
            FROM packages
            WHERE status = 'active'
            ORDER BY FIELD(package_type, 'gold', 'premium', 'vip'), id DESC
        ");
        $packages = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $stmt = $pdo->prepare("
            SELECT
                up.*,
                p.title AS real_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
            LIMIT 1
        ");
        $stmt->execute([$userId]);
        $currentPackage = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
    } catch (Throwable $e) {
        $message = 'Üye veya paket bilgileri alınırken sistem hatası oluştu.';
        $messageType = 'error';
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $userId > 0 && $user) {
    $name     = trim((string)($_POST['name'] ?? ''));
    $username = trim((string)($_POST['username'] ?? ''));
    $email    = trim((string)($_POST['email'] ?? ''));
    $phone    = trim((string)($_POST['phone'] ?? ''));
    $password = trim((string)($_POST['password'] ?? ''));
    $role     = trim((string)($_POST['role'] ?? 'user'));
    $status   = trim((string)($_POST['status'] ?? 'active'));

    $packageId     = (int)($_POST['package_id'] ?? 0);
    $packageStart  = trim((string)($_POST['start_date'] ?? ''));
    $packageEnd    = trim((string)($_POST['end_date'] ?? ''));
    $packageStatus = trim((string)($_POST['package_status'] ?? 'active'));

    if ($name === '' || $username === '') {
        $message = 'Ad soyad ve kullanıcı adı zorunludur.';
        $messageType = 'error';
    } else {
        try {
            $userColumns = user_edit_columns($pdo, 'users');

            $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ? AND id != ?");
            $check->execute([$username, $userId]);

            if ((int)$check->fetchColumn() > 0) {
                throw new RuntimeException('Bu kullanıcı adı başka bir üyede kullanılıyor.');
            }

            if ($email !== '') {
                $check = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND id != ?");
                $check->execute([$email, $userId]);

                if ((int)$check->fetchColumn() > 0) {
                    throw new RuntimeException('Bu e-posta başka bir üyede kullanılıyor.');
                }
            }

            $image = user_edit_upload_image('image');

            $update = [];

            if (user_edit_has($userColumns, 'name')) {
                $update['name'] = $name;
            }

            if (user_edit_has($userColumns, 'username')) {
                $update['username'] = $username;
            }

            if (user_edit_has($userColumns, 'email')) {
                $update['email'] = $email;
            }

            if (user_edit_has($userColumns, 'phone')) {
                $update['phone'] = $phone;
            }

            if ($password !== '' && user_edit_has($userColumns, 'password')) {
                $update['password'] = password_hash($password, PASSWORD_DEFAULT);
            }

            if (user_edit_has($userColumns, 'role')) {
                $update['role'] = $role;
            }

            if (user_edit_has($userColumns, 'status')) {
                $update['status'] = $status;
            }

            if ($image !== '' && user_edit_has($userColumns, 'image')) {
                $update['image'] = $image;
            }

            if (user_edit_has($userColumns, 'updated_at')) {
                $update['updated_at'] = date('Y-m-d H:i:s');
            }

            if ($update) {
                $parts = [];

                foreach ($update as $field => $value) {
                    $parts[] = "`{$field}` = ?";
                }

                $sql = "UPDATE users SET " . implode(', ', $parts) . " WHERE id = ?";
                $values = array_values($update);
                $values[] = $userId;

                $stmt = $pdo->prepare($sql);
                $stmt->execute($values);
            }

            if ($packageId <= 0) {
                $pdo->prepare("UPDATE user_packages SET status = 'cancelled' WHERE user_id = ? AND status = 'active'")
                    ->execute([$userId]);
            } else {
                $stmt = $pdo->prepare("
                    SELECT
                        id,
                        package_type,
                        title,
                        amount,
                        price,
                        duration,
                        status
                    FROM packages
                    WHERE id = ? AND status = 'active'
                    LIMIT 1
                ");
                $stmt->execute([$packageId]);
                $selectedPackage = $stmt->fetch(PDO::FETCH_ASSOC);

                if (!$selectedPackage) {
                    throw new RuntimeException('Seçilen paket bulunamadı veya pasif durumda.');
                }

                $packageType = (string)$selectedPackage['package_type'];
                $packageName = (string)$selectedPackage['title'];

                $startDate = $packageStart !== ''
                    ? str_replace('T', ' ', $packageStart) . ':00'
                    : date('Y-m-d H:i:s');

                if ($packageEnd !== '') {
                    $endDate = str_replace('T', ' ', $packageEnd) . ':00';
                } else {
                    $durationDays = user_edit_duration_to_days($selectedPackage['duration'] ?? '30 Gün');
                    $endDate = date('Y-m-d H:i:s', strtotime('+' . $durationDays . ' days', strtotime($startDate)));
                }

                $pdo->prepare("UPDATE user_packages SET status = 'cancelled' WHERE user_id = ? AND status = 'active'")
                    ->execute([$userId]);

                $stmt = $pdo->prepare("
                    INSERT INTO user_packages
                    (user_id, package_id, package_type, package_name, start_date, end_date, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
                ");

                $stmt->execute([
                    $userId,
                    $packageId,
                    $packageType,
                    $packageName,
                    $startDate,
                    $endDate,
                    in_array($packageStatus, ['active', 'expired', 'cancelled'], true) ? $packageStatus : 'active'
                ]);
            }

            $message = 'Üye bilgileri ve paket ataması başarıyla güncellendi.';
            $messageType = 'success';

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

            $stmt = $pdo->prepare("
                SELECT
                    up.*,
                    p.title AS real_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
                LIMIT 1
            ");
            $stmt->execute([$userId]);
            $currentPackage = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        } catch (Throwable $e) {
            $message = $e->getMessage();
            $messageType = 'error';
        }
    }
}

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

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

$currentType = strtolower((string)($currentPackage['package_type'] ?? ''));
$currentEmoji = user_edit_package_emoji($currentType);
$currentPackageName = (string)($currentPackage['package_name'] ?? 'Paket Yok');
$currentAmount = (string)($currentPackage['package_amount'] ?? '0');
$currentDuration = (string)($currentPackage['package_duration'] ?? '-');
$currentPrice = !empty($currentPackage['package_price'])
    ? number_format((float)$currentPackage['package_price'], 2, ',', '.') . ' ₺'
    : '-';

$remainingText = 'Paket Yok';
$progress = 0;

if (!empty($currentPackage['start_date']) && !empty($currentPackage['end_date'])) {
    $startTime = strtotime((string)$currentPackage['start_date']);
    $endTime = strtotime((string)$currentPackage['end_date']);
    $nowTime = time();

    if ($startTime !== false && $endTime !== false && $endTime > $startTime) {
        $total = $endTime - $startTime;
        $left = max(0, $endTime - $nowTime);
        $days = (int)ceil($left / 86400);
        $remainingText = $days <= 0 ? 'Bitti' : $days . ' Gün Kaldı';
        $progress = (int)max(0, min(100, round(($left / $total) * 100)));
    }
} elseif ($currentPackage) {
    $remainingText = 'Süresiz';
    $progress = 100;
}

$packageThemeClass = match ($currentType) {
    'gold' => 'package-gold',
    'premium' => 'package-premium',
    'vip' => 'package-vip',
    default => 'package-empty',
};
?>

<style>
.user-edit-shell{
    display:grid;
    grid-template-columns:1fr .42fr;
    gap:22px;
}

.user-edit-card{
    padding:28px;
    border-radius:30px;
    background:rgba(255,255,255,.055);
    border:1px solid rgba(255,255,255,.09);
    box-shadow:0 24px 70px rgba(0,0,0,.20);
}

.user-edit-card h2{
    margin:0 0 8px;
    color:#f5b642;
    font-size:24px;
}

.user-edit-card p{
    margin:0 0 22px;
    color:#9aa3b2;
    font-weight:700;
    line-height:1.6;
}

.form-grid{
    display:grid;
    grid-template-columns:repeat(2,1fr);
    gap:18px;
}

.form-section-title{
    grid-column:1/-1;
    margin-top:8px;
    padding-top:18px;
    border-top:1px solid rgba(255,255,255,.08);
    color:#f5b642;
    font-size:18px;
    font-weight:900;
}

.form-group label{
    display:block;
    margin-bottom:8px;
    color:#dce3ef;
    font-size:14px;
    font-weight:900;
}

.form-control{
    width:100%;
    height:52px;
    border:1px solid rgba(255,255,255,.12);
    border-radius:16px;
    background:rgba(0,0,0,.25);
    color:#fff;
    padding:0 15px;
    outline:none;
}

.form-control:focus{
    border-color:#f5b642;
    box-shadow:0 0 0 4px rgba(245,182,66,.12);
}

input[type="file"].form-control{
    height:auto;
    padding:14px;
}

.form-actions{
    display:flex;
    gap:12px;
    flex-wrap:wrap;
    margin-top:22px;
}

.form-alert{
    margin-bottom:18px;
    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;
}

.form-alert.success{
    background:rgba(0,150,70,.20);
    border:1px solid rgba(0,255,120,.30);
    color:#d8ffe8;
}

.premium-side{
    display:grid;
    gap:18px;
}

.profile-showcase{
    position:relative;
    overflow:hidden;
    padding:28px;
    border-radius:32px;
    background:
        radial-gradient(circle at top right,rgba(245,182,66,.26),transparent 38%),
        linear-gradient(135deg,rgba(255,255,255,.075),rgba(255,255,255,.035));
    border:1px solid rgba(255,255,255,.10);
    box-shadow:0 24px 70px rgba(0,0,0,.22);
    text-align:center;
}

.profile-showcase:before{
    content:"";
    position:absolute;
    inset:-80px auto auto -80px;
    width:180px;
    height:180px;
    border-radius:50%;
    background:rgba(185,0,0,.20);
}

.profile-img{
    position:relative;
    width:122px;
    height:122px;
    margin:0 auto 16px;
    border-radius:38px;
    padding:5px;
    background:linear-gradient(135deg,#f5b642,#b90000);
    box-shadow:0 22px 45px rgba(0,0,0,.35);
}

.profile-img img{
    width:100%;
    height:100%;
    object-fit:cover;
    border-radius:33px;
    background:#111;
}

.profile-letter{
    width:100%;
    height:100%;
    border-radius:33px;
    background:#111;
    display:flex;
    align-items:center;
    justify-content:center;
    color:#f5b642;
    font-size:48px;
    font-weight:1000;
}

.profile-showcase h3{
    position:relative;
    margin:0 0 6px;
    color:#fff;
    font-size:25px;
}

.profile-showcase .username{
    position:relative;
    display:block;
    color:#aeb7c7;
    font-size:14px;
    font-weight:900;
}

.role-pill{
    position:relative;
    margin-top:14px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    padding:9px 14px;
    border-radius:999px;
    background:rgba(245,182,66,.14);
    border:1px solid rgba(245,182,66,.25);
    color:#f5b642;
    font-size:12px;
    font-weight:1000;
}

.package-showcase{
    position:relative;
    overflow:hidden;
    padding:26px;
    border-radius:34px;
    border:1px solid rgba(255,255,255,.12);
    box-shadow:0 24px 75px rgba(0,0,0,.28);
}

.package-showcase.package-gold{
    background:
        radial-gradient(circle at top right,rgba(245,182,66,.42),transparent 38%),
        radial-gradient(circle at bottom left,rgba(185,0,0,.18),transparent 40%),
        linear-gradient(135deg,#342611,#171a22);
}

.package-showcase.package-premium{
    background:
        radial-gradient(circle at top right,rgba(100,180,255,.38),transparent 38%),
        radial-gradient(circle at bottom left,rgba(245,182,66,.14),transparent 40%),
        linear-gradient(135deg,#14283f,#131a26);
}

.package-showcase.package-vip{
    background:
        radial-gradient(circle at top right,rgba(255,93,177,.38),transparent 38%),
        radial-gradient(circle at bottom left,rgba(130,90,255,.25),transparent 40%),
        linear-gradient(135deg,#291733,#151722);
}

.package-showcase.package-empty{
    background:
        radial-gradient(circle at top right,rgba(255,255,255,.12),transparent 38%),
        linear-gradient(135deg,#202733,#131820);
}

.package-icon{
    width:68px;
    height:68px;
    border-radius:24px;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:38px;
    background:rgba(0,0,0,.28);
    border:1px solid rgba(255,255,255,.16);
    box-shadow:0 18px 40px rgba(0,0,0,.22);
    margin-bottom:18px;
}

.package-showcase h3{
    margin:0 0 8px;
    color:#fff;
    font-size:30px;
    line-height:1.1;
}

.package-showcase .package-type{
    display:inline-flex;
    margin-bottom:18px;
    padding:8px 13px;
    border-radius:999px;
    background:rgba(255,255,255,.12);
    border:1px solid rgba(255,255,255,.16);
    color:#fff;
    font-size:12px;
    font-weight:1000;
}

.package-mini-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:10px;
    margin:18px 0;
}

.package-mini{
    padding:14px;
    border-radius:18px;
    background:rgba(0,0,0,.25);
    border:1px solid rgba(255,255,255,.10);
}

.package-mini small{
    display:block;
    color:#aeb7c7;
    font-weight:900;
    margin-bottom:6px;
    font-size:12px;
}

.package-mini b{
    display:block;
    color:#fff;
    font-size:15px;
}

.progress-box{
    margin-top:18px;
    padding:15px;
    border-radius:20px;
    background:rgba(0,0,0,.24);
    border:1px solid rgba(255,255,255,.10);
}

.progress-head{
    display:flex;
    justify-content:space-between;
    gap:12px;
    color:#fff;
    font-size:13px;
    font-weight:1000;
    margin-bottom:10px;
}

.progress-line{
    height:11px;
    border-radius:999px;
    background:rgba(255,255,255,.10);
    overflow:hidden;
}

.progress-fill{
    height:100%;
    width:<?= user_edit_e((string)$progress) ?>%;
    border-radius:999px;
    background:linear-gradient(90deg,#f5b642,#ff6b6b);
    box-shadow:0 0 18px rgba(245,182,66,.45);
}

.package-status{
    margin-top:15px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    min-height:34px;
    padding:0 14px;
    border-radius:999px;
    background:rgba(0,150,70,.20);
    border:1px solid rgba(0,255,120,.26);
    color:#d8ffe8;
    font-size:12px;
    font-weight:1000;
}

.package-status.passive{
    background:rgba(185,0,0,.20);
    border-color:rgba(255,80,80,.30);
    color:#ffdede;
}

.side-actions{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:10px;
}

.side-actions a{
    min-height:42px;
    padding:0 12px;
    border-radius:14px;
    display: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:1000;
    text-decoration:none;
}

.side-actions a:hover{
    color:#f5b642;
    border-color:rgba(245,182,66,.35);
}

@media(max-width:1000px){
    .user-edit-shell{
        grid-template-columns:1fr;
    }

    .form-grid{
        grid-template-columns:1fr;
    }
}

@media(max-width:560px){
    .package-mini-grid,
    .side-actions{
        grid-template-columns:1fr;
    }
}
</style>

<section class="user-edit-shell">

    <div class="user-edit-card">
        <h2>Üye Düzenle</h2>
        <p>Üye bilgilerini güncelleyin ve oluşturduğunuz hazır paketlerden üyeye paket atayın.</p>

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

        <?php if ($user): ?>
            <form method="post" enctype="multipart/form-data">
                <div class="form-grid">

                    <div class="form-section-title">Üye Bilgileri</div>

                    <div class="form-group">
                        <label>Ad Soyad</label>
                        <input type="text" name="name" class="form-control" value="<?= user_edit_e($user['name'] ?? '') ?>" required>
                    </div>

                    <div class="form-group">
                        <label>Kullanıcı Adı</label>
                        <input type="text" name="username" class="form-control" value="<?= user_edit_e($user['username'] ?? '') ?>" required>
                    </div>

                    <div class="form-group">
                        <label>E-Posta</label>
                        <input type="email" name="email" class="form-control" value="<?= user_edit_e($user['email'] ?? '') ?>">
                    </div>

                    <div class="form-group">
                        <label>Telefon</label>
                        <input type="text" name="phone" class="form-control" value="<?= user_edit_e($user['phone'] ?? '') ?>">
                    </div>

                    <div class="form-group">
                        <label>Yeni Şifre</label>
                        <input type="password" name="password" class="form-control" placeholder="Boş bırakılırsa değişmez">
                    </div>

                    <div class="form-group">
                        <label>Profil Resmi</label>
                        <input type="file" name="image" class="form-control" accept="image/*">
                    </div>

                    <div class="form-group">
                        <label>Rol</label>
                        <select name="role" class="form-control">
                            <option value="user" <?= (($user['role'] ?? 'user') === 'user') ? 'selected' : '' ?>>Üye</option>
                            <option value="admin" <?= (($user['role'] ?? '') === 'admin') ? 'selected' : '' ?>>Yönetici</option>
                            <option value="superadmin" <?= (($user['role'] ?? '') === 'superadmin') ? 'selected' : '' ?>>Süper Yönetici</option>
                            <option value="owner" <?= (($user['role'] ?? '') === 'owner') ? 'selected' : '' ?>>Kurucu</option>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Durum</label>
                        <select name="status" class="form-control">
                            <option value="active" <?= (($user['status'] ?? 'active') === 'active') ? 'selected' : '' ?>>Aktif</option>
                            <option value="passive" <?= (($user['status'] ?? '') === 'passive') ? 'selected' : '' ?>>Pasif</option>
                            <option value="banned" <?= (($user['status'] ?? '') === 'banned') ? 'selected' : '' ?>>Banlı</option>
                        </select>
                    </div>

                    <div class="form-section-title">Hazır Paket Atama</div>

                    <div class="form-group">
                        <label>Paket Seç</label>
                        <select name="package_id" class="form-control">
                            <option value="0">Paket Yok</option>

                            <?php foreach ($packages as $package): ?>
                                <option value="<?= user_edit_e($package['id']) ?>" <?= ((int)($currentPackage['package_id'] ?? 0) === (int)$package['id']) ? 'selected' : '' ?>>
                                    <?= user_edit_e(strtoupper((string)$package['package_type'])) ?>
                                    -
                                    <?= user_edit_e($package['title']) ?>
                                    /
                                    <?= user_edit_e($package['amount']) ?> Miktar
                                    /
                                    <?= user_edit_e($package['duration']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label>Başlangıç Tarihi</label>
                        <input type="datetime-local" name="start_date" class="form-control" value="<?= !empty($currentPackage['start_date']) ? user_edit_e(str_replace(' ', 'T', substr((string)$currentPackage['start_date'], 0, 16))) : '' ?>">
                    </div>

                    <div class="form-group">
                        <label>Bitiş Tarihi</label>
                        <input type="datetime-local" name="end_date" class="form-control" value="<?= !empty($currentPackage['end_date']) ? user_edit_e(str_replace(' ', 'T', substr((string)$currentPackage['end_date'], 0, 16))) : '' ?>">
                    </div>

                    <div class="form-group">
                        <label>Paket Durumu</label>
                        <select name="package_status" class="form-control">
                            <option value="active" <?= (($currentPackage['status'] ?? 'active') === 'active') ? 'selected' : '' ?>>Aktif</option>
                            <option value="expired" <?= (($currentPackage['status'] ?? '') === 'expired') ? 'selected' : '' ?>>Süresi Doldu</option>
                            <option value="cancelled" <?= (($currentPackage['status'] ?? '') === 'cancelled') ? 'selected' : '' ?>>İptal</option>
                        </select>
                    </div>

                </div>

                <div class="form-actions">
                    <button type="submit" class="admin-btn">Güncelle</button>
                    <a href="users.php" class="admin-btn admin-btn-dark">Listeye Dön</a>
                </div>
            </form>
        <?php endif; ?>
    </div>

    <aside class="premium-side">

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

            <h3><?= user_edit_e($user['name'] ?? 'Üye') ?></h3>
            <span class="username">@<?= user_edit_e($user['username'] ?? '-') ?></span>

            <div class="role-pill">
                <?= user_edit_e(strtoupper((string)($user['role'] ?? 'USER'))) ?>
            </div>
        </div>

        <div class="package-showcase <?= user_edit_e($packageThemeClass) ?>">
            <div class="package-icon"><?= user_edit_e($currentEmoji) ?></div>

            <span class="package-type">
                <?= $currentType !== '' ? user_edit_e(strtoupper($currentType)) : 'PAKET YOK' ?>
            </span>

            <h3><?= user_edit_e($currentPackageName) ?></h3>

            <div class="package-mini-grid">
                <div class="package-mini">
                    <small>Miktar</small>
                    <b><?= user_edit_e($currentAmount) ?></b>
                </div>

                <div class="package-mini">
                    <small>Fiyat</small>
                    <b><?= user_edit_e($currentPrice) ?></b>
                </div>

                <div class="package-mini">
                    <small>Süre</small>
                    <b><?= user_edit_e($currentDuration) ?></b>
                </div>

                <div class="package-mini">
                    <small>Bitiş</small>
                    <b><?= user_edit_e($currentPackage['end_date'] ?? '-') ?></b>
                </div>
            </div>

            <div class="progress-box">
                <div class="progress-head">
                    <span>Kalan Süre</span>
                    <span><?= user_edit_e($remainingText) ?></span>
                </div>

                <div class="progress-line">
                    <div class="progress-fill"></div>
                </div>
            </div>

            <div class="package-status <?= (($currentPackage['status'] ?? '') === 'active') ? '' : 'passive' ?>">
                <?= (($currentPackage['status'] ?? '') === 'active') ? '🟢 AKTİF ÜYELİK' : user_edit_e(strtoupper((string)($currentPackage['status'] ?? 'PAKET YOK'))) ?>
            </div>
        </div>

        <div class="side-actions">
            <a href="user-detail.php?id=<?= user_edit_e($userId) ?>">Üye Detay</a>
            <a href="memberships.php">Üyelikler</a>
        </div>

    </aside>

</section>

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