<?php
/*
|--------------------------------------------------------------------------
| RadyoHost.BiZ / Okey Platformu
|--------------------------------------------------------------------------
| Sayfa Adı : Premium Admin Destek Merkezi
| Dosya     : customer/support.php
|--------------------------------------------------------------------------
| Açıklama:
| Üyenin aktif Gold / Premium / VIP paketine göre renk değiştiren,
| paket bilgisini destek talebine otomatik ekleyen premium iletişim sayfasıdır.
|--------------------------------------------------------------------------
| Modül     : Müşteri Paneli
| Yetki     : Üye
| Sürüm     : V2.0
|--------------------------------------------------------------------------
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

require_once __DIR__ . '/../config/db.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$pdo = $pdo ?? $db ?? null;

if (!$pdo instanceof PDO) {
    die('Veritabanı bağlantısı bulunamadı.');
}

if (empty($_SESSION['user_id']) && empty($_SESSION['customer_id'])) {
    header('Location: ../login.php');
    exit;
}

$userId = (int)($_SESSION['user_id'] ?? $_SESSION['customer_id']);

function e(string $v): string
{
    return htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
}

function tr_date(?string $date): string
{
    if (!$date || $date === '0000-00-00' || $date === '0000-00-00 00:00:00') {
        return 'Belirtilmemiş';
    }

    try {
        return (new DateTime($date))->format('d.m.Y H:i');
    } catch (Throwable $e) {
        return $date;
    }
}

$success = '';
$error   = '';

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

if (!$user) {
    session_destroy();
    header('Location: ../login.php');
    exit;
}

$name  = $user['name'] ?? $user['username'] ?? 'Üye';
$email = $user['email'] ?? '-';
$phone = $user['phone'] ?? '-';
$image = !empty($user['image']) ? '../uploads/user/' . $user['image'] : '../assets/img/default-user.png';

$stmtPackage = $pdo->prepare("
    SELECT up.*, p.title, p.amount, p.price, p.duration, p.description
    FROM user_packages up
    LEFT JOIN packages p ON p.id = up.package_id
    WHERE up.user_id = :user_id AND up.status = 'active'
    ORDER BY FIELD(up.package_type,'vip','premium','gold'), up.id DESC
    LIMIT 1
");
$stmtPackage->execute(['user_id' => $userId]);
$activePackage = $stmtPackage->fetch(PDO::FETCH_ASSOC);

$packageType = strtolower((string)($activePackage['package_type'] ?? 'gold'));
if (!in_array($packageType, ['gold', 'premium', 'vip'], true)) {
    $packageType = 'gold';
}

$themeMap = [
    'gold' => [
        'class' => 'theme-gold',
        'icon' => '🪙',
        'label' => 'Gold Destek',
        'title' => 'Gold Üye Destek Merkezi',
        'desc'  => 'Gold üyeliğine özel hızlı ve sade destek alanı.'
    ],
    'premium' => [
        'class' => 'theme-premium',
        'icon' => '👑',
        'label' => 'Premium Destek',
        'title' => 'Premium Üye Destek Merkezi',
        'desc'  => 'Premium üyeliğine özel güçlü ve öncelikli destek alanı.'
    ],
    'vip' => [
        'class' => 'theme-vip',
        'icon' => '💎',
        'label' => 'VIP Destek',
        'title' => 'VIP Üye Destek Merkezi',
        'desc'  => 'VIP üyeliğine özel en üst seviye yönetim iletişim alanı.'
    ],
];

$theme = $themeMap[$packageType];

$packageName   = $activePackage['title'] ?? $activePackage['package_name'] ?? 'Aktif Paket Yok';
$packageAmount = $activePackage['amount'] ?? '-';
$packageEnd    = $activePackage['end_date'] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject  = trim((string)($_POST['subject'] ?? ''));
    $message  = trim((string)($_POST['message'] ?? ''));
    $priority = trim((string)($_POST['priority'] ?? 'medium'));

    if ($subject === '' || $message === '') {
        $error = 'Konu ve mesaj alanı boş bırakılamaz.';
    } else {
        try {
            $ticketNo = 'DST-' . date('Ymd') . '-' . strtoupper(substr(md5((string)microtime(true) . $userId), 0, 6));

            $fullMessage  = "Üye Destek Mesajı\n\n";
            $fullMessage .= "Üye Bilgileri\n";
            $fullMessage .= "Ad Soyad: {$name}\n";
            $fullMessage .= "E-Posta: {$email}\n";
            $fullMessage .= "Telefon: {$phone}\n\n";

            $fullMessage .= "Aktif Paket Bilgisi\n";
            $fullMessage .= "Paket Türü: " . strtoupper($packageType) . "\n";
            $fullMessage .= "Paket Adı: {$packageName}\n";
            $fullMessage .= "Miktar: {$packageAmount}\n";
            $fullMessage .= "Paket Bitiş: " . tr_date($packageEnd) . "\n\n";

            $fullMessage .= "Konu: {$subject}\n\n";
            $fullMessage .= "Mesaj:\n{$message}";

            $insert = $pdo->prepare("
                INSERT INTO tickets
                (ticket_no, user_id, department, subject, message, priority, status, last_reply_by, last_reply_at, created_at, updated_at)
                VALUES
                (:ticket_no, :user_id, 'Müşteri Destek', :subject, :message, :priority, 'open', 'customer', NOW(), NOW(), NOW())
            ");

            $insert->execute([
                'ticket_no' => $ticketNo,
                'user_id'   => $userId,
                'subject'   => $subject,
                'message'   => $fullMessage,
                'priority'  => in_array($priority, ['low', 'medium', 'high', 'urgent'], true) ? $priority : 'medium'
            ]);

            $success = 'Mesajınız başarıyla yönetim ekibine gönderildi.';
            $subject = '';
            $message = '';
        } catch (Throwable $e) {
            $error = 'Mesaj gönderilirken sistem hatası oluştu.';
        }
    }
}

$recentTickets = [];

try {
    $stmtRecent = $pdo->prepare("
        SELECT *
        FROM tickets
        WHERE user_id = :user_id
        ORDER BY id DESC
        LIMIT 4
    ");
    $stmtRecent->execute(['user_id' => $userId]);
    $recentTickets = $stmtRecent->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $recentTickets = [];
}
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<title>Admin Destek | RadyoHost Okey</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<style>
*{box-sizing:border-box}
body{
    margin:0;
    font-family:Arial,Helvetica,sans-serif;
    color:#fff;
    background:#070914;
    overflow-x:hidden;
}
body:before{
    content:"";
    position:fixed;
    inset:0;
    z-index:-2;
    background:
        radial-gradient(circle at 12% 10%,var(--glow1),transparent 28%),
        radial-gradient(circle at 88% 22%,var(--glow2),transparent 27%),
        radial-gradient(circle at 50% 92%,#3b82f655,transparent 32%),
        linear-gradient(135deg,#070914,#111827 55%,#090b16);
}
body:after{
    content:"";
    position:fixed;
    inset:0;
    background-image:
        linear-gradient(#ffffff08 1px,transparent 1px),
        linear-gradient(90deg,#ffffff08 1px,transparent 1px);
    background-size:42px 42px;
    opacity:.24;
    z-index:-1;
}
.theme-gold{
    --main:#f5b642;
    --main2:#ff8a00;
    --glow1:#f5b64266;
    --glow2:#ff8a0060;
    --soft:#f5b64218;
}
.theme-premium{
    --main:#38bdf8;
    --main2:#8b5cf6;
    --glow1:#38bdf866;
    --glow2:#8b5cf666;
    --soft:#38bdf818;
}
.theme-vip{
    --main:#ff5db1;
    --main2:#a855f7;
    --glow1:#ff5db166;
    --glow2:#a855f766;
    --soft:#ff5db118;
}
a{text-decoration:none;color:inherit}
.wrap{min-height:100vh;padding:28px}
.topbar{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:18px;
    margin-bottom:25px;
}
.topbar h1{margin:0;font-size:31px}
.topbar p{margin:8px 0 0;color:#c6cdec;font-size:14px}
.dashboard-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    gap:10px;
    padding:15px 24px;
    border-radius:18px;
    background:linear-gradient(135deg,var(--main),var(--main2));
    color:#fff;
    font-size:15px;
    font-weight:900;
    box-shadow:0 15px 35px var(--glow1);
}
.alert{
    padding:16px 19px;
    border-radius:18px;
    margin-bottom:20px;
    font-weight:900;
}
.success{background:#158553}
.error{background:#b82845}
.hero{
    position:relative;
    overflow:hidden;
    border-radius:36px;
    padding:36px;
    margin-bottom:24px;
    background:linear-gradient(135deg,#151b31dd,#0d1224ee);
    border:1px solid rgba(255,255,255,.12);
    box-shadow:0 25px 90px #0009;
}
.hero:before{
    content:"";
    position:absolute;
    width:430px;
    height:430px;
    right:-145px;
    top:-165px;
    border-radius:50%;
    background:linear-gradient(135deg,var(--glow1),var(--glow2));
    filter:blur(8px);
}
.hero-inner{
    position:relative;
    display:grid;
    grid-template-columns:150px 1fr 300px;
    gap:26px;
    align-items:center;
}
.avatar img{
    width:150px;
    height:150px;
    border-radius:50%;
    object-fit:cover;
    border:5px solid var(--main);
    box-shadow:0 0 58px var(--glow1);
}
.hero h2{margin:0 0 8px;font-size:36px}
.hero p{margin:0;color:#c6cdec;line-height:1.7}
.badges{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-top:18px;
}
.badge{
    padding:10px 14px;
    border-radius:999px;
    background:#ffffff12;
    border:1px solid #ffffff18;
    font-size:13px;
    font-weight:900;
}
.badge.hot{
    color:var(--main);
    background:var(--soft);
    border-color:var(--main);
}
.package-box{
    padding:24px;
    border-radius:30px;
    background:linear-gradient(135deg,var(--soft),#ffffff08);
    border:1px solid var(--main);
    text-align:center;
    box-shadow:0 20px 65px var(--glow1);
}
.package-box b{display:block;font-size:22px}
.package-box span{display:block;margin-top:8px;color:var(--main);font-weight:900}
.main-grid{
    display:grid;
    grid-template-columns:1fr 390px;
    gap:24px;
}
.card{
    background:linear-gradient(145deg,#151b31cc,#0d1224dd);
    border:1px solid #ffffff18;
    border-radius:32px;
    box-shadow:0 25px 80px #0009;
    padding:30px;
    position:relative;
    overflow:hidden;
}
.card:before{
    content:"";
    position:absolute;
    width:260px;
    height:260px;
    right:-120px;
    bottom:-120px;
    border-radius:50%;
    background:var(--soft);
}
.card-inner{position:relative}
.card h2{margin:0 0 10px;font-size:27px}
.card p{color:#b8c1df;line-height:1.7;margin:0 0 20px}
.form-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:16px;
    margin-bottom:17px;
}
label{
    display:block;
    color:#d8def5;
    font-size:14px;
    font-weight:900;
    margin-bottom:8px;
}
input,select,textarea{
    width:100%;
    border:1px solid #ffffff18;
    background:#070d1d;
    color:#fff;
    border-radius:18px;
    padding:15px 16px;
    outline:none;
    font-size:15px;
    font-family:Arial,Helvetica,sans-serif;
}
textarea{
    min-height:190px;
    resize:vertical;
}
input:focus,select:focus,textarea:focus{
    border-color:var(--main);
    box-shadow:0 0 0 4px var(--soft);
}
.submit-btn{
    width:100%;
    margin-top:18px;
    border:0;
    cursor:pointer;
    padding:17px 22px;
    border-radius:20px;
    background:linear-gradient(135deg,var(--main),var(--main2));
    color:#fff;
    font-weight:900;
    font-size:16px;
    box-shadow:0 18px 42px var(--glow1);
}
.ticket-list{
    display:grid;
    gap:13px;
}
.ticket{
    padding:16px;
    border-radius:20px;
    background:#ffffff0c;
    border:1px solid #ffffff14;
}
.ticket b{
    display:block;
    margin-bottom:8px;
}
.ticket span{
    color:#aeb7d4;
    font-size:13px;
}
.status{
    display:inline-flex;
    margin-top:10px;
    padding:8px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:900;
    color:#86efac;
    background:#22c55e22;
    border:1px solid #22c55e66;
}
.status.closed{
    color:#ffb4b4;
    background:#ef444422;
    border-color:#ef444466;
}
.empty{
    padding:18px;
    border-radius:20px;
    background:#ffffff0c;
    border:1px dashed #ffffff26;
    color:#cbd5e1;
    line-height:1.7;
}
.process{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:12px;
    margin-top:20px;
}
.step{
    padding:15px;
    border-radius:18px;
    background:#ffffff0c;
    border:1px solid #ffffff14;
    text-align:center;
}
.step b{display:block;font-size:20px;margin-bottom:6px;color:var(--main)}
.step span{font-size:12px;color:#aeb7d4}
.quick-actions{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:16px;
    margin-top:24px;
}
.quick{
    padding:20px;
    border-radius:24px;
    background:linear-gradient(145deg,#151b31cc,#0d1224dd);
    border:1px solid #ffffff14;
    box-shadow:0 18px 55px #0006;
    transition:.25s;
}
.quick:hover{transform:translateY(-5px);border-color:var(--main)}
.quick b{display:block;font-size:17px;margin-bottom:8px}
.quick span{color:#aeb7d4;font-size:13px}
.admin-footer{
    margin-top:30px;
    padding:18px 24px;
    width:100%;
    display:grid;
    grid-template-columns:minmax(280px,1.25fr) minmax(220px,.9fr) minmax(260px,1fr);
    align-items:center;
    gap:18px;
    border-top:1px solid rgba(255,255,255,.08);
    background:linear-gradient(180deg,rgba(255,255,255,.04),rgba(255,255,255,.015));
    color:#9aa3b2;
    font-size:12px;
    font-weight:800;
    border-radius:24px;
}
.footer-left{display:flex;align-items:center;gap:6px;white-space:nowrap}
.footer-link{color:var(--main);font-weight:900}
.footer-center{text-align:center;color:var(--main);font-size:13px;font-weight:900}
.footer-right{display:flex;align-items:center;justify-content:flex-end;white-space:nowrap}
.footer-signature{color:#ff5db1;font-size:14px;font-weight:900}
.footer-whatsapp img{width:52px;height:52px;object-fit:contain;filter:drop-shadow(0 0 10px rgba(37,211,102,.8))}
@media(max-width:1200px){
    .hero-inner{grid-template-columns:150px 1fr}
    .package-box{grid-column:1 / -1}
    .main-grid{grid-template-columns:1fr}
}
@media(max-width:900px){
    .hero-inner{display:flex;flex-direction:column;text-align:center}
    .badges{justify-content:center}
    .quick-actions{grid-template-columns:repeat(2,1fr)}
    .admin-footer{grid-template-columns:1fr;text-align:center;justify-items:center}
    .footer-left,.footer-right{justify-content:center;flex-wrap:wrap}
}
@media(max-width:600px){
    .wrap{padding:18px}
    .topbar{flex-direction:column;align-items:flex-start}
    .form-grid,.process,.quick-actions{grid-template-columns:1fr}
    .hero,.card{padding:22px}
    .hero h2{font-size:28px}
}
</style>
</head>
<body class="<?= e($theme['class']) ?>">

<div class="wrap">

    <div class="topbar">
        <div>
            <h1><?= e($theme['icon'] . ' ' . $theme['title']) ?></h1>
            <p><?= e($theme['desc']) ?></p>
        </div>
        <a class="dashboard-btn" href="index.php">⚡ Kontrol Merkezine Dön</a>
    </div>

    <?php if ($success !== ''): ?>
        <div class="alert success"><?= e($success) ?></div>
    <?php endif; ?>

    <?php if ($error !== ''): ?>
        <div class="alert error"><?= e($error) ?></div>
    <?php endif; ?>

    <section class="hero">
        <div class="hero-inner">

            <div class="avatar">
                <img src="<?= e((string)$image) ?>" alt="Profil Resmi">
            </div>

            <div>
                <h2><?= e((string)$name) ?></h2>
                <p><?= e((string)$email) ?></p>
                <p>
                    Mesajların aktif paket bilgilerinle birlikte yönetim ekibine iletilir.
                    Böylece admin hangi paketle destek istediğini direkt görür.
                </p>

                <div class="badges">
                    <span class="badge hot"><?= e($theme['icon'] . ' ' . $theme['label']) ?></span>
                    <span class="badge">🛡️ Güvenli Destek Alanı</span>
                    <span class="badge">🎮 Okey Üye Paneli</span>
                </div>
            </div>

            <div class="package-box">
                <b><?= e((string)$packageName) ?></b>
                <span><?= e(strtoupper($packageType)) ?> • Bitiş: <?= e(tr_date($packageEnd)) ?></span>
            </div>

        </div>
    </section>

    <section class="main-grid">

        <div class="card">
            <div class="card-inner">
                <h2>Yeni Destek Mesajı</h2>
                <p>
                    Paket, ödeme, üyelik, giriş veya hesap işlemleri için yönetime detaylı mesaj gönderebilirsin.
                </p>

                <form method="post">

                    <div class="form-grid">
                        <div>
                            <label>Konu</label>
                            <input
                                type="text"
                                name="subject"
                                value="<?= e((string)($subject ?? '')) ?>"
                                placeholder="Örn: Paket yenileme hakkında"
                                required
                            >
                        </div>

                        <div>
                            <label>Öncelik</label>
                            <select name="priority">
                                <option value="low">Düşük</option>
                                <option value="medium" selected>Normal</option>
                                <option value="high">Yüksek</option>
                                <option value="urgent">Acil</option>
                            </select>
                        </div>
                    </div>

                    <label>Mesajınız</label>
                    <textarea
                        name="message"
                        placeholder="Mesajınızı buraya yazınız..."
                        required
                    ><?= e((string)($message ?? '')) ?></textarea>

                    <div class="process">
                        <div class="step"><b>1</b><span>Mesaj Yaz</span></div>
                        <div class="step"><b>2</b><span>Pakete Bağlanır</span></div>
                        <div class="step"><b>3</b><span>Admin İnceler</span></div>
                        <div class="step"><b>4</b><span>Çözüm Sağlanır</span></div>
                    </div>

                    <button class="submit-btn" type="submit">🚀 Mesajı Yönetim Ekibine Gönder</button>

                </form>
            </div>
        </div>

        <div class="card">
            <div class="card-inner">
                <h2>Son Destek Taleplerim</h2>
                <p>Son gönderdiğin destek mesajları burada görünür.</p>

                <?php if (empty($recentTickets)): ?>
                    <div class="empty">
                        Henüz destek talebin bulunmuyor.
                    </div>
                <?php else: ?>
                    <div class="ticket-list">
                        <?php foreach ($recentTickets as $ticket): ?>
                            <?php $ticketStatus = strtolower((string)($ticket['status'] ?? 'open')); ?>

                            <div class="ticket">
                                <b><?= e((string)($ticket['subject'] ?? 'Destek Talebi')) ?></b>
                                <span><?= e(tr_date($ticket['created_at'] ?? null)) ?></span>
                                <br>
                                <span class="status <?= $ticketStatus === 'closed' ? 'closed' : '' ?>">
                                    <?= e((string)($ticket['status'] ?? 'open')) ?>
                                </span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>

            </div>
        </div>

    </section>

    <section class="quick-actions">
        <a class="quick" href="profile.php">
            <b>👤 Profilim</b>
            <span>Profil ve şifre bilgilerini yönet.</span>
        </a>

        <a class="quick" href="my-package.php">
            <b>🎁 Paketlerim</b>
            <span>Aktif ve kapalı paket geçmişini gör.</span>
        </a>

        <a class="quick" href="renew-package.php">
            <b>🔄 Paket Talep Et</b>
            <span>Gold, Premium veya VIP paket seç.</span>
        </a>

        <a class="quick" href="logout.php">
            <b>🚪 Güvenli Çıkış</b>
            <span>Hesabından güvenli şekilde çık.</span>
        </a>
    </section>

    <footer class="admin-footer">
        <div class="footer-left">
            <span>Powered By <?= date('Y') ?></span>
            <a href="https://www.radyohost.biz" target="_blank" rel="noopener" class="footer-link">🌐 RadyoHost.BiZ</a>
            <span>Web Teknolojileri</span>
        </div>

        <div class="footer-center">Premium Okey Üye Paneli</div>

        <div class="footer-right">
            <span class="footer-signature">Developed By VoLKaN75</span>
            <a href="https://wa.me/905415917536" target="_blank" rel="noopener" class="footer-whatsapp">
                <img src="../uploads/footer/whatsapp.png" alt="WhatsApp">
            </a>
        </div>
    </footer>

</div>

</body>
</html>