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

/*
|--------------------------------------------------------------------------
| ÜYELİK TANIMLAMA
|--------------------------------------------------------------------------
| membership-view.php
| Üyeye Gold / Premium / VIP paket tanımlama ekranı
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Üyelik Tanımla';
$pageDescription = 'Sistemdeki üyeye hazır paket tanımlayın.';

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

$message = '';
$messageType = '';
$isCreated = false;

$users = [];
$packages = [];
$selectedUserId = (int)($_GET['user_id'] ?? 0);

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

function mv_columns(PDO $pdo, string $table): array
{
    try {
        $cols = [];
        $q = $pdo->query("SHOW COLUMNS FROM `$table`");
        while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
            $cols[] = (string)$row['Field'];
        }
        return $cols;
    } catch (Throwable $e) {
        return [];
    }
}

function mv_has(array $columns, string $column): bool
{
    return in_array($column, $columns, true);
}

try {
    $users = $pdo->query("
        SELECT id, name, username, email, phone, status
        FROM users
        ORDER BY id DESC
    ")->fetchAll(PDO::FETCH_ASSOC) ?: [];

    $packages = $pdo->query("
        SELECT *
        FROM packages
        WHERE status = 'active'
        ORDER BY FIELD(package_type,'gold','premium','vip'), id DESC
    ")->fetchAll(PDO::FETCH_ASSOC) ?: [];
} catch (Throwable $e) {
    $message = 'Üye veya paket listesi alınırken sistem hatası oluştu.';
    $messageType = 'error';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userId = (int)($_POST['user_id'] ?? 0);
    $packageId = (int)($_POST['package_id'] ?? 0);
    $startDate = trim((string)($_POST['start_date'] ?? ''));
    $endDate = trim((string)($_POST['end_date'] ?? ''));
    $status = trim((string)($_POST['status'] ?? 'active'));

    if ($userId <= 0) {
        $message = 'Lütfen bir üye seçiniz.';
        $messageType = 'error';
    } elseif ($packageId <= 0) {
        $message = 'Lütfen bir paket seçiniz.';
        $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('Seçilen üye bulunamadı.');
            }

            $stmt = $pdo->prepare("SELECT * FROM packages WHERE id = ? AND status = 'active' LIMIT 1");
            $stmt->execute([$packageId]);
            $package = $stmt->fetch(PDO::FETCH_ASSOC);

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

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

            if ($endDate !== '') {
                $end = str_replace('T', ' ', $endDate) . ':00';
            } else {
                $duration = (int)($package['duration_days'] ?? 30);
                $end = date('Y-m-d H:i:s', strtotime('+' . $duration . ' days', strtotime($start)));
            }

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

            $cols = mv_columns($pdo, 'user_packages');

            $insert = [
                'user_id' => $userId,
                'package_type' => (string)$package['package_type'],
                'package_name' => (string)$package['title'],
                'start_date' => $start,
                'end_date' => $end,
                'status' => in_array($status, ['active','expired','cancelled'], true) ? $status : 'active',
                'created_at' => date('Y-m-d H:i:s'),
            ];

            if (mv_has($cols, 'package_id')) {
                $insert = ['package_id' => $packageId] + $insert;
            }

            $fields = array_keys($insert);
            $placeholders = array_fill(0, count($fields), '?');

            $sql = "INSERT INTO user_packages (`" . implode('`,`', $fields) . "`) VALUES (" . implode(',', $placeholders) . ")";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(array_values($insert));

            $message = 'Üyeye paket başarıyla tanımlandı. 10 saniye sonra üyelik yönetimine yönlendiriliyorsunuz.';
            $messageType = 'success';
            $isCreated = true;
            $_POST = [];
        } catch (Throwable $e) {
            $message = $e->getMessage();
            $messageType = 'error';
        }
    }
}
?>

<?php if ($isCreated): ?>
<meta http-equiv="refresh" content="10;url=memberships.php">
<?php endif; ?>

<style>
.membership-view-page{display:grid;grid-template-columns:1fr .38fr;gap:22px}
.mv-card{padding:28px;border-radius:30px;background:rgba(255,255,255,.055);border:1px solid rgba(255,255,255,.09)}
.mv-card h2{margin:0 0 8px;color:#f5b642;font-size:26px}
.mv-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-group.full{grid-column:1/-1}
.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)}
.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}
.side-box{padding:22px;border-radius:26px;background:linear-gradient(135deg,rgba(245,182,66,.13),rgba(185,0,0,.10));border:1px solid rgba(255,255,255,.09);margin-bottom:16px}
.side-box strong{display:block;color:#f5b642;font-size:18px;margin-bottom:8px}
.side-box span{color:#cbd2df;font-size:13px;font-weight:700;line-height:1.7}
@media(max-width:1000px){.membership-view-page{grid-template-columns:1fr}.form-grid{grid-template-columns:1fr}}
</style>

<section class="membership-view-page">

    <div class="mv-card">
        <h2>Üyeye Paket Tanımla</h2>
        <p>Sistemde kayıtlı üyeyi seçin, açılmış Gold / Premium / VIP paketlerden birini tanımlayın.</p>

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

        <?php if (!$isCreated): ?>
            <form method="post">
                <div class="form-grid">

                    <div class="form-group full">
                        <label>Üye Seç</label>
                        <select name="user_id" class="form-control" required>
                            <option value="">Üye seçiniz</option>
                            <?php foreach ($users as $user): ?>
                                <?php $uid = (int)$user['id']; ?>
                                <option value="<?= mv_e($uid) ?>" <?= ((int)($_POST['user_id'] ?? $selectedUserId) === $uid) ? 'selected' : '' ?>>
                                    <?= mv_e($user['name'] ?? '-') ?> / @<?= mv_e($user['username'] ?? '-') ?> / <?= mv_e($user['email'] ?? '-') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group full">
                        <label>Paket Seç</label>
                        <select name="package_id" class="form-control" required>
                            <option value="">Paket seçiniz</option>
                            <?php foreach ($packages as $package): ?>
                                <option value="<?= mv_e($package['id']) ?>" <?= ((int)($_POST['package_id'] ?? 0) === (int)$package['id']) ? 'selected' : '' ?>>
                                    <?= mv_e(strtoupper((string)$package['package_type'])) ?> - <?= mv_e($package['title']) ?> / <?= mv_e($package['duration_days']) ?> Gün / <?= mv_e($package['price']) ?> ₺
                                </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="<?= mv_e($_POST['start_date'] ?? '') ?>">
                    </div>

                    <div class="form-group">
                        <label>Bitiş Tarihi</label>
                        <input type="datetime-local" name="end_date" class="form-control" value="<?= mv_e($_POST['end_date'] ?? '') ?>">
                    </div>

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

                </div>

                <div class="form-actions">
                    <button type="submit" class="admin-btn">Paketi Tanımla</button>
                    <a href="memberships.php" class="admin-btn admin-btn-dark">Listeye Dön</a>
                </div>
            </form>
        <?php else: ?>
            <a href="memberships.php" class="admin-btn">Üyelik Yönetimine Dön</a>
        <?php endif; ?>
    </div>

    <aside>
        <div class="side-box">
            <strong>Üye + Paket Birleştirme</strong>
            <span>Bu ekrandan seçilen üye ile seçilen paket birleştirilir ve user_packages tablosuna kayıt edilir.</span>
        </div>

        <div class="side-box">
            <strong>Otomatik Bitiş Tarihi</strong>
            <span>Bitiş tarihi boş bırakılırsa, seçilen paketin duration_days değerine göre otomatik hesaplanır.</span>
        </div>

        <div class="side-box">
            <strong>Aktif Paket Kuralı</strong>
            <span>Yeni paket atanırken üyenin eski aktif paketi otomatik iptal edilir.</span>
        </div>
    </aside>

</section>

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