<?php
/*
|--------------------------------------------------------------------------
| RadyoHost.BiZ / Okey Platformu
|--------------------------------------------------------------------------
| Sayfa Adı : Premium Profil Yönetimi
| Dosya     : customer/profile.php
|--------------------------------------------------------------------------
| Açıklama:
| Üyenin profil bilgilerini, profil resmini ve kendi şifresini
| güvenli şekilde değiştirdiği premium müşteri panel sayfasıdır.
|--------------------------------------------------------------------------
| Modül     : Müşteri Paneli
| Yetki     : Üye
| Sürüm     : V1.2
|--------------------------------------------------------------------------
| 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 $value): string
{
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function check_password_compat(string $plain, string $hash): bool
{
    if ($hash === '') {
        return false;
    }

    if (password_verify($plain, $hash)) {
        return true;
    }

    if (strlen($hash) === 32 && hash_equals($hash, md5($plain))) {
        return true;
    }

    return hash_equals($hash, $plain);
}

$uploadDir = __DIR__ . '/../uploads/user/';
$uploadUrl = '../uploads/user/';

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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string)($_POST['action'] ?? 'profile');

    if ($action === 'profile') {
        $name  = trim((string)($_POST['name'] ?? ''));
        $phone = trim((string)($_POST['phone'] ?? ''));

        if ($name === '') {
            $error = 'Ad soyad alanı boş bırakılamaz.';
        } else {
            $imageName = (string)($user['image'] ?? '');

            if (!empty($_FILES['image']['name'])) {
                $allowed = ['jpg', 'jpeg', 'png', 'webp'];
                $ext = strtolower(pathinfo((string)$_FILES['image']['name'], PATHINFO_EXTENSION));

                if (!in_array($ext, $allowed, true)) {
                    $error = 'Sadece JPG, PNG veya WEBP resim yükleyebilirsiniz.';
                } elseif ((int)$_FILES['image']['size'] > 3 * 1024 * 1024) {
                    $error = 'Profil resmi en fazla 3 MB olabilir.';
                } else {
                    $imageName = 'user_' . $userId . '_' . time() . '.' . $ext;
                    $target = $uploadDir . $imageName;

                    if (!move_uploaded_file((string)$_FILES['image']['tmp_name'], $target)) {
                        $error = 'Profil resmi yüklenirken hata oluştu.';
                    }
                }
            }

            if ($error === '') {
                $update = $pdo->prepare("
                    UPDATE users
                    SET name = :name,
                        phone = :phone,
                        image = :image,
                        updated_at = NOW()
                    WHERE id = :id
                    LIMIT 1
                ");

                $update->execute([
                    'name'  => $name,
                    'phone' => $phone,
                    'image' => $imageName,
                    'id'    => $userId
                ]);

                $success = 'Profil bilgileriniz başarıyla güncellendi.';
            }
        }
    }

    if ($action === 'password') {
        $currentPassword = trim((string)($_POST['current_password'] ?? ''));
        $newPassword     = trim((string)($_POST['new_password'] ?? ''));
        $newPassword2    = trim((string)($_POST['new_password_confirm'] ?? ''));

        $oldHash = (string)($user['password'] ?? '');

        if ($currentPassword === '' || $newPassword === '' || $newPassword2 === '') {
            $error = 'Şifre alanları boş bırakılamaz.';
        } elseif (!check_password_compat($currentPassword, $oldHash)) {
            $error = 'Mevcut şifreniz hatalı.';
        } elseif (strlen($newPassword) < 6) {
            $error = 'Yeni şifre en az 6 karakter olmalıdır.';
        } elseif ($newPassword !== $newPassword2) {
            $error = 'Yeni şifreler birbiriyle uyuşmuyor.';
        } else {
            $newHash = password_hash($newPassword, PASSWORD_DEFAULT);

            $update = $pdo->prepare("
                UPDATE users
                SET password = :password,
                    updated_at = NOW()
                WHERE id = :id
                LIMIT 1
            ");

            $update->execute([
                'password' => $newHash,
                'id'       => $userId
            ]);

            $success = 'Şifreniz başarıyla değiştirildi.';
        }
    }

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

$name       = $user['name'] ?? $user['username'] ?? 'Üye';
$email      = $user['email'] ?? '-';
$phone      = $user['phone'] ?? '';
$status     = $user['status'] ?? 'active';
$createdAt  = $user['created_at'] ?? '-';
$updatedAt  = $user['updated_at'] ?? '-';
$package    = $user['package_name'] ?? $user['membership_name'] ?? 'Standart Üyelik';
$packageEnd = $user['package_end'] ?? $user['membership_end'] ?? 'Belirtilmemiş';
$image      = !empty($user['image']) ? $uploadUrl . $user['image'] : '../assets/img/default-user.png';
?>
<!DOCTYPE html>
<html lang="tr">
<head>
<meta charset="UTF-8">
<title>Profil Yönetimi | 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;
    background:
        radial-gradient(circle at 12% 10%,#f5b64255,transparent 28%),
        radial-gradient(circle at 88% 22%,#ff5db155,transparent 26%),
        radial-gradient(circle at 48% 92%,#3b82f655,transparent 32%),
        linear-gradient(135deg,#070914,#111827 55%,#090b16);
    z-index:-2;
}
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:.25;
    z-index:-1;
}
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,#f5b642,#ff5d5d,#ff5db1);
    color:#fff;
    font-size:15px;
    font-weight:900;
    box-shadow:0 15px 35px rgba(255,93,93,.38);
    transition:.25s;
}
.dashboard-btn:hover{
    transform:translateY(-3px);
    box-shadow:0 22px 48px rgba(255,93,177,.48);
}
.hero{
    position:relative;
    overflow:hidden;
    border-radius:34px;
    padding:34px;
    margin-bottom:24px;
    background:linear-gradient(135deg,#151b31dd,#0d1224ee);
    border:1px solid rgba(255,255,255,.12);
    box-shadow:0 25px 80px #0009;
}
.hero:before{
    content:"";
    position:absolute;
    width:360px;
    height:360px;
    right:-120px;
    top:-140px;
    border-radius:50%;
    background:linear-gradient(135deg,#f5b64255,#ff5db155);
    filter:blur(6px);
}
.hero-inner{
    position:relative;
    display:flex;
    align-items:center;
    gap:25px;
}
.avatar{
    position:relative;
    width:150px;
    height:150px;
    flex:0 0 auto;
}
.avatar img{
    width:150px;
    height:150px;
    border-radius:50%;
    object-fit:cover;
    border:5px solid #f5b642;
    box-shadow:0 0 55px #f5b64277;
}
.live-dot{
    position:absolute;
    right:14px;
    bottom:14px;
    width:24px;
    height:24px;
    border-radius:50%;
    background:#22c55e;
    border:4px solid #111827;
    box-shadow:0 0 20px #22c55e;
}
.hero h2{margin:0 0 8px;font-size:34px}
.hero p{margin:0;color:#c6cdec;line-height:1.6}
.badges{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-top:18px;
}
.badge{
    padding:10px 14px;
    border-radius:999px;
    background:#ffffff12;
    border:1px solid #ffffff18;
    color:#fff;
    font-size:13px;
    font-weight:900;
}
.badge.gold{
    background:#f5b64222;
    border-color:#f5b64266;
    color:#ffd37a;
}
.stats{
    display:grid;
    grid-template-columns:repeat(4,1fr);
    gap:16px;
    margin-bottom:24px;
}
.stat{
    padding:20px;
    border-radius:22px;
    background:linear-gradient(145deg,#151b31cc,#0d1224dd);
    border:1px solid #ffffff14;
    box-shadow:0 18px 55px #0006;
}
.stat span{
    display:block;
    color:#aeb7d4;
    font-size:13px;
    margin-bottom:8px;
}
.stat strong{
    display:block;
    font-size:18px;
    line-height:1.4;
}
.main-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:24px;
}
.card{
    background:linear-gradient(145deg,#151b31cc,#0d1224dd);
    border:1px solid #ffffff18;
    border-radius:30px;
    box-shadow:0 25px 80px #0009;
    backdrop-filter:blur(14px);
}
.form-card{padding:30px}
.form-card h2{
    margin:0 0 8px;
    font-size:24px;
}
.desc{
    margin:0 0 22px;
    color:#b8c1df;
    line-height:1.6;
    font-size:14px;
}
.alert{
    padding:16px 19px;
    border-radius:18px;
    margin-bottom:20px;
    font-weight:900;
    font-size:14px;
}
.success{background:#158553}
.error{background:#b82845}
.field{margin-bottom:17px}
label{
    display:block;
    margin-bottom:8px;
    color:#d8def5;
    font-weight:900;
    font-size:14px;
}
input{
    width:100%;
    padding:15px 16px;
    border:1px solid #ffffff18;
    background:#070d1d;
    color:#fff;
    border-radius:16px;
    outline:none;
    font-size:15px;
}
input:focus{
    border-color:#f5b642;
    box-shadow:0 0 0 4px #f5b64225;
}
input[readonly]{
    opacity:.65;
    cursor:not-allowed;
}
.upload{
    border:1px dashed #f5b64299;
    background:#f5b64210;
    padding:18px;
    border-radius:20px;
}
button{
    border:0;
    cursor:pointer;
    padding:15px 22px;
    border-radius:17px;
    font-weight:900;
    font-size:15px;
    background:linear-gradient(135deg,#f5b642,#ff5d5d);
    color:#fff;
    box-shadow:0 15px 35px rgba(255,93,93,.35);
}
.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:#f5b64288;
}
.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;
    justify-content:flex-start;
    gap:6px;
    min-width:0;
    white-space:nowrap;
}
.footer-left span,
.footer-left a{
    display:inline-flex;
    align-items:center;
    white-space:nowrap;
}
.footer-link{
    color:#f5b642;
    text-decoration:none;
    font-weight:900;
    transition:.25s;
}
.footer-link:hover{color:#ffffff}
.footer-tech{
    color:#9aa3b2;
    font-weight:800;
}
.footer-center{
    text-align:center;
    color:#f5b642;
    font-size:13px;
    font-weight:900;
    letter-spacing:.4px;
    white-space:nowrap;
    overflow:hidden;
    text-overflow:ellipsis;
}
.footer-right{
    display:flex;
    align-items:center;
    justify-content:flex-end;
    gap:0;
    min-width:0;
    white-space:nowrap;
}
.footer-signature{
    color:#ff5db1;
    font-size:14px;
    font-weight:900;
    white-space:nowrap;
}
.footer-whatsapp{
    display:flex;
    align-items:center;
    justify-content:center;
    margin-left:-3px;
    flex:0 0 auto;
}
.footer-whatsapp img{
    width:52px;
    height:52px;
    object-fit:contain;
    filter:drop-shadow(0 0 10px rgba(37,211,102,.8));
    transition:.25s;
}
.footer-whatsapp:hover img{transform:scale(1.12)}
@media(max-width:1100px){
    .main-grid{grid-template-columns:1fr}
    .stats{grid-template-columns:repeat(2,1fr)}
    .quick-actions{grid-template-columns:repeat(2,1fr)}
}
@media(max-width:900px){
    .hero-inner{flex-direction:column;text-align:center}
    .badges{justify-content:center}
    .admin-footer{
        grid-template-columns:1fr;
        justify-items:center;
        text-align:center;
        gap:10px;
    }
    .footer-left,.footer-center,.footer-right{
        justify-content:center;
        text-align:center;
        width:100%;
    }
    .footer-left{flex-wrap:wrap}
}
@media(max-width:600px){
    .wrap{padding:18px}
    .topbar{flex-direction:column;align-items:flex-start}
    .stats,.quick-actions{grid-template-columns:1fr}
    .hero,.form-card{padding:22px}
    .hero h2{font-size:27px}
    .footer-left{white-space:normal;line-height:1.6}
    .footer-center,.footer-right{white-space:normal}
    .footer-whatsapp img{width:46px;height:46px}
}
</style>
</head>
<body>

<div class="wrap">

    <div class="topbar">
        <div>
            <h1>Premium Profil Yönetimi</h1>
            <p>Profil bilgileri, profil resmi, paket özeti ve güvenli şifre değiştirme alanı.</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">
                <span class="live-dot"></span>
            </div>

            <div>
                <h2><?= e((string)$name) ?></h2>
                <p><?= e((string)$email) ?></p>
                <p>RadyoHost Okey üyelik merkezinden hesabını güvenli şekilde yönetebilirsin.</p>

                <div class="badges">
                    <span class="badge gold">🏆 <?= e((string)$package) ?></span>
                    <span class="badge">🛡️ Hesap Durumu: <?= $status === 'active' ? 'Aktif' : e((string)$status) ?></span>
                    <span class="badge">🎮 Premium Üye Paneli</span>
                </div>
            </div>
        </div>
    </section>

    <section class="stats">
        <div class="stat">
            <span>Kayıt Tarihi</span>
            <strong><?= e((string)$createdAt) ?></strong>
        </div>
        <div class="stat">
            <span>Son Güncelleme</span>
            <strong><?= e((string)$updatedAt) ?></strong>
        </div>
        <div class="stat">
            <span>Aktif Paket</span>
            <strong><?= e((string)$package) ?></strong>
        </div>
        <div class="stat">
            <span>Paket Bitiş</span>
            <strong><?= e((string)$packageEnd) ?></strong>
        </div>
    </section>

    <section class="main-grid">

        <div class="card form-card">
            <h2>Profil Bilgileri</h2>
            <p class="desc">Ad soyad, telefon ve profil resmini buradan güncelle.</p>

            <form method="post" enctype="multipart/form-data">
                <input type="hidden" name="action" value="profile">

                <div class="field">
                    <label>Ad Soyad</label>
                    <input type="text" name="name" value="<?= e((string)$name) ?>" required>
                </div>

                <div class="field">
                    <label>E-posta</label>
                    <input type="email" value="<?= e((string)$email) ?>" readonly>
                </div>

                <div class="field">
                    <label>Telefon</label>
                    <input type="text" name="phone" value="<?= e((string)$phone) ?>" placeholder="Telefon numaranız">
                </div>

                <div class="field upload">
                    <label>Profil Resmi</label>
                    <input type="file" name="image" accept=".jpg,.jpeg,.png,.webp">
                </div>

                <button type="submit">Profili Güncelle</button>
            </form>
        </div>

        <div class="card form-card">
            <h2>Güvenlik Merkezi</h2>
            <p class="desc">Üye kendi şifresini buradan güvenli şekilde değiştirebilir.</p>

            <form method="post">
                <input type="hidden" name="action" value="password">

                <div class="field">
                    <label>Mevcut Şifre</label>
                    <input type="password" name="current_password" placeholder="Mevcut şifreniz" required>
                </div>

                <div class="field">
                    <label>Yeni Şifre</label>
                    <input type="password" name="new_password" placeholder="Yeni şifreniz" required>
                </div>

                <div class="field">
                    <label>Yeni Şifre Tekrar</label>
                    <input type="password" name="new_password_confirm" placeholder="Yeni şifre tekrar" required>
                </div>

                <button type="submit">Şifreyi Değiştir</button>
            </form>
        </div>

    </section>

    <section class="quick-actions">
        <a class="quick" href="my-package.php">
            <b>🎁 Paketim</b>
            <span>Aktif paket detaylarını görüntüle.</span>
        </a>

        <a class="quick" href="renew-package.php">
            <b>🔄 Paket Yenile</b>
            <span>Paket yenileme talebi gönder.</span>
        </a>

        <a class="quick" href="support.php">
            <b>💬 Admin Destek</b>
            <span>Yönetim ekibiyle iletişim kur.</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 class="footer-tech">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>