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

/*
|--------------------------------------------------------------------------
| OKEY YÖNETİCİSİ DÜZENLEME EKRANI
|--------------------------------------------------------------------------
| okey-manager-edit.php
| Ana Sayfa Okey Yönetim Kadrosu Düzenleme Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Okey Yöneticisi Düzenle';
$pageDescription = 'Ana sayfada görünecek okey yöneticisi bilgilerini düzenleyin.';

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

$message = '';
$messageType = '';

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

$titles = [];
$manager = null;

$form = [
    'title_id'     => '',
    'username'     => '',
    'display_name' => '',
    'image'        => '',
    'verified'     => '1',
    'status'       => 'active',
    'sort_order'   => '0',
];

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

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

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

function okey_edit_image_url(?string $image): string
{
    $image = trim((string)$image);

    if ($image === '') {
        return '../assets/images/admin-default.png';
    }

    $image = str_replace('\\', '/', $image);

    if (str_starts_with($image, 'http://') || str_starts_with($image, 'https://')) {
        return $image;
    }

    $imageName = basename($image);

    $paths = [
        [
            'disk' => __DIR__ . '/../uploads/managers/' . $imageName,
            'url'  => '../uploads/managers/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/manager/' . $imageName,
            'url'  => '../uploads/manager/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/users/' . $imageName,
            'url'  => '../uploads/users/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/user/' . $imageName,
            'url'  => '../uploads/user/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/' . $imageName,
            'url'  => '../uploads/' . $imageName,
        ],
    ];

    foreach ($paths as $path) {
        if (is_file($path['disk'])) {
            return $path['url'];
        }
    }

    return '../assets/images/admin-default.png';
}

function okey_edit_upload_image(string $fieldName, string $uploadDir, string $uploadUrl): string
{
    if (
        empty($_FILES[$fieldName]) ||
        !isset($_FILES[$fieldName]['error']) ||
        (int)$_FILES[$fieldName]['error'] === UPLOAD_ERR_NO_FILE
    ) {
        return '';
    }

    if ((int)$_FILES[$fieldName]['error'] !== UPLOAD_ERR_OK) {
        throw new RuntimeException('Resim yüklenirken hata oluştu.');
    }

    $tmpName = (string)$_FILES[$fieldName]['tmp_name'];
    $size    = (int)$_FILES[$fieldName]['size'];

    if ($size <= 0) {
        throw new RuntimeException('Yüklenen resim geçersiz.');
    }

    if ($size > 5 * 1024 * 1024) {
        throw new RuntimeException('Resim boyutu en fazla 5MB olabilir.');
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime  = (string)$finfo->file($tmpName);

    $allowed = [
        'image/jpeg' => 'jpg',
        'image/png'  => 'png',
        'image/webp' => 'webp',
        'image/gif'  => 'gif',
    ];

    if (!array_key_exists($mime, $allowed)) {
        throw new RuntimeException('Sadece JPG, PNG, WEBP veya GIF resim yükleyebilirsiniz.');
    }

    $fileName = 'manager-' . date('YmdHis') . '-' . bin2hex(random_bytes(5)) . '.' . $allowed[$mime];
    $target   = rtrim($uploadDir, '/') . '/' . $fileName;

    if (!move_uploaded_file($tmpName, $target)) {
        throw new RuntimeException('Resim uploads/managers klasörüne taşınamadı.');
    }

    return rtrim($uploadUrl, '/') . '/' . $fileName;
}

try {
    if (isset($pdo) && $pdo instanceof PDO) {
        $titleStmt = $pdo->query("
            SELECT *
            FROM okey_manager_titles
            WHERE status IN ('active','aktif','1')
            ORDER BY sort_order ASC, id ASC
        ");

        $titles = $titleStmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        if ($id > 0) {
            $stmt = $pdo->prepare("
                SELECT *
                FROM okey_managers
                WHERE id = ?
                LIMIT 1
            ");
            $stmt->execute([$id]);
            $manager = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

            if ($manager) {
                $form = [
                    'title_id'     => (string)($manager['title_id'] ?? ''),
                    'username'     => (string)($manager['username'] ?? ''),
                    'display_name' => (string)($manager['display_name'] ?? ''),
                    'image'        => (string)($manager['image'] ?? ''),
                    'verified'     => (string)((int)($manager['verified'] ?? 1)),
                    'status'       => (string)($manager['status'] ?? 'active'),
                    'sort_order'   => (string)($manager['sort_order'] ?? '0'),
                ];
            }
        }
    }
} catch (Throwable $e) {
    error_log('Okey yöneticisi düzenleme yükleme hatası: ' . $e->getMessage());
}

if ($id <= 0) {
    $message = 'Düzenlenecek okey yöneticisi bulunamadı.';
    $messageType = 'error';
} elseif (!$manager) {
    $message = 'Okey yöneticisi kaydı bulunamadı.';
    $messageType = 'error';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($pdo) && $pdo instanceof PDO && $id > 0 && $manager) {
    $form['title_id']     = trim((string)($_POST['title_id'] ?? ''));
    $form['username']     = trim((string)($_POST['username'] ?? ''));
    $form['display_name'] = trim((string)($_POST['display_name'] ?? ''));
    $form['verified']     = isset($_POST['verified']) ? '1' : '0';
    $form['status']       = trim((string)($_POST['status'] ?? 'active'));
    $form['sort_order']   = trim((string)($_POST['sort_order'] ?? '0'));

    if ($form['username'] === '') {
        $message = 'Rumuz alanı zorunludur.';
        $messageType = 'error';
    } elseif ($form['display_name'] === '') {
        $message = 'Okey yönetim adı zorunludur.';
        $messageType = 'error';
    } elseif ($form['title_id'] === '') {
        $message = 'Görev ünvanı seçmelisiniz.';
        $messageType = 'error';
    } else {
        try {
            $newImage = okey_edit_upload_image('image', $uploadDir, $uploadUrl);

            if ($newImage !== '') {
                $form['image'] = $newImage;
            }

            $stmt = $pdo->prepare("
                UPDATE okey_managers
                SET
                    title_id = :title_id,
                    username = :username,
                    display_name = :display_name,
                    image = :image,
                    verified = :verified,
                    status = :status,
                    sort_order = :sort_order,
                    updated_at = NOW()
                WHERE id = :id
                LIMIT 1
            ");

            $stmt->execute([
                ':title_id'     => (int)$form['title_id'],
                ':username'     => $form['username'],
                ':display_name' => $form['display_name'],
                ':image'        => $form['image'] !== '' ? $form['image'] : null,
                ':verified'     => (int)$form['verified'],
                ':status'       => $form['status'] === 'passive' ? 'passive' : 'active',
                ':sort_order'   => (int)$form['sort_order'],
                ':id'           => $id,
            ]);

            $message = 'Okey yöneticisi başarıyla güncellendi.';
            $messageType = 'success';
        } catch (Throwable $e) {
            $message = $e->getMessage();
            $messageType = 'error';
        }
    }
}
?>

<style>
.okey-edit-wrap{
    display:grid;
    grid-template-columns:.92fr 1.08fr;
    gap:24px;
    align-items:start;
}

.okey-info-card,
.okey-form-card{
    position:relative;
    overflow:hidden;
    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,.18);
}

.okey-info-card:before,
.okey-form-card:before{
    content:"";
    position:absolute;
    width:240px;
    height:240px;
    right:-120px;
    top:-120px;
    border-radius:50%;
    background:rgba(245,182,66,.12);
}

.okey-info-card h2,
.okey-form-card h2{
    position:relative;
    margin:0 0 10px;
    color:#f5b642;
    font-size:26px;
}

.okey-info-card p,
.okey-form-card p{
    position:relative;
    margin:0 0 22px;
    color:#9aa3b2;
    font-weight:800;
    line-height:1.7;
}

.okey-preview-box{
    position:relative;
    margin-top:24px;
    padding:24px;
    border-radius:28px;
    background:linear-gradient(145deg,rgba(245,182,66,.12),rgba(185,0,0,.08)),rgba(0,0,0,.22);
    border:1px solid rgba(245,182,66,.18);
}

.okey-preview-avatar{
    position:relative;
    width:104px;
    height:104px;
    border-radius:50%;
    padding:3px;
    background:linear-gradient(135deg,#f5b642,#b90000);
    margin-bottom:18px;
}

.okey-preview-avatar img{
    width:100%;
    height:100%;
    border-radius:50%;
    object-fit:cover;
    background:#111;
}

.okey-preview-tick{
    position:absolute;
    right:0;
    bottom:3px;
    width:28px;
    height:28px;
    display:grid;
    place-items:center;
    border-radius:50%;
    background:#00b66a;
    color:#fff;
    border:3px solid #111520;
    font-weight:1000;
    box-shadow:0 0 18px rgba(0,255,140,.35);
}

.okey-preview-box strong{
    display:block;
    color:#fff;
    font-size:24px;
    margin-bottom:7px;
}

.okey-preview-box span{
    display:inline-flex;
    padding:8px 12px;
    border-radius:999px;
    color:#ffd47d;
    background:rgba(245,182,66,.13);
    border:1px solid rgba(245,182,66,.26);
    font-size:12px;
    font-weight:1000;
}

.okey-rule-list{
    position:relative;
    display:grid;
    gap:12px;
    margin-top:22px;
}

.okey-rule-item{
    padding:15px;
    border-radius:18px;
    background:rgba(0,0,0,.22);
    border:1px solid rgba(255,255,255,.08);
    color:#d7dce6;
    font-weight:800;
    line-height:1.5;
}

.okey-alert{
    position:relative;
    padding:15px 17px;
    border-radius:17px;
    font-weight:900;
    margin-bottom:18px;
}

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

.okey-alert.error{
    background:rgba(185,0,0,.20);
    border:1px solid rgba(255,80,80,.30);
    color:#ffdede;
}

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

.okey-form-group.full{
    grid-column:1/-1;
}

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

.okey-form-control{
    width:100%;
    height:54px;
    border:1px solid rgba(255,255,255,.12);
    border-radius:18px;
    background:rgba(0,0,0,.26);
    color:#fff;
    padding:0 16px;
    outline:none;
    font-weight:800;
}

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

.okey-form-control.file{
    padding:14px 16px;
    height:auto;
}

.okey-check-row{
    display:flex;
    align-items:flex-start;
    gap:10px;
    color:#dce3ef;
    font-weight:900;
    line-height:1.5;
    margin-top:4px;
}

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

.okey-submit{
    border:0;
    cursor:pointer;
}

.current-image-box{
    position:relative;
    margin-bottom:14px;
    padding:14px;
    border-radius:20px;
    background:rgba(0,0,0,.22);
    border:1px solid rgba(255,255,255,.08);
    display:flex;
    align-items:center;
    gap:14px;
}

.current-image-box img{
    width:72px;
    height:72px;
    border-radius:18px;
    object-fit:cover;
    background:#111;
    border:1px solid rgba(245,182,66,.25);
}

.current-image-box strong{
    display:block;
    color:#fff;
    margin-bottom:5px;
}

.current-image-box span{
    display:block;
    color:#9aa3b2;
    font-size:12px;
    font-weight:800;
}

@media(max-width:980px){
    .okey-edit-wrap{
        grid-template-columns:1fr;
    }
}

@media(max-width:620px){
    .okey-form-grid{
        grid-template-columns:1fr;
    }
}
</style>

<section class="okey-edit-wrap">
    <aside class="okey-info-card">
        <h2>👑 Okey Yöneticisi Önizleme</h2>
        <p>Bu kayıt ana sayfadaki yöneticiler alanında resimli şekilde gösterilir.</p>

        <div class="okey-preview-box">
            <div class="okey-preview-avatar">
                <img src="<?= admin_e(okey_edit_image_url($form['image'])) ?>" alt="Önizleme">
                <?php if ($form['verified'] === '1'): ?>
                    <span class="okey-preview-tick">✓</span>
                <?php endif; ?>
            </div>

            <strong><?= admin_e($form['display_name'] !== '' ? $form['display_name'] : 'Okey Yöneticisi') ?></strong>

            <?php
            $selectedTitleText = 'Görev Ünvanı';
            foreach ($titles as $title) {
                if ((string)$title['id'] === (string)$form['title_id']) {
                    $selectedTitleText = (string)($title['icon'] ?? '👑') . ' ' . (string)($title['title_name'] ?? 'Görev Ünvanı');
                    break;
                }
            }
            ?>
            <span><?= admin_e($selectedTitleText) ?></span>
        </div>

        <div class="okey-rule-list">
            <div class="okey-rule-item">✅ Yeni resim yüklersen eski resim yerine yeni resim kullanılır.</div>
            <div class="okey-rule-item">✅ Tik kapatılırsa ana sayfadaki doğrulama işareti gizlenir.</div>
            <div class="okey-rule-item">✅ Pasif yapılan yöneticiler ana sayfada gösterilmez.</div>
            <div class="okey-rule-item">✅ Liste sıralaması küçük sayıdan büyüğe doğru yapılır.</div>
        </div>
    </aside>

    <section class="okey-form-card">
        <h2>Okey Yöneticisi Düzenle</h2>
        <p>Mevcut okey yöneticisi bilgilerini güncelleyin.</p>

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

        <?php if ($manager): ?>
            <form method="post" enctype="multipart/form-data">
                <div class="okey-form-grid">
                    <div class="okey-form-group full">
                        <label>Mevcut Resim</label>
                        <div class="current-image-box">
                            <img src="<?= admin_e(okey_edit_image_url($form['image'])) ?>" alt="Mevcut Resim">
                            <div>
                                <strong>Yönetici resmi</strong>
                                <span>Yeni resim yüklemezsen mevcut resim korunur.</span>
                            </div>
                        </div>

                        <label>Yeni Resim Yükle</label>
                        <input type="file" name="image" class="okey-form-control file" accept="image/*">
                    </div>

                    <div class="okey-form-group">
                        <label>Rumuz</label>
                        <input type="text" name="username" class="okey-form-control" value="<?= admin_e($form['username']) ?>" placeholder="Örn: VoLKaN75" required>
                    </div>

                    <div class="okey-form-group">
                        <label>Okey Yönetim Adı</label>
                        <input type="text" name="display_name" class="okey-form-control" value="<?= admin_e($form['display_name']) ?>" placeholder="Örn: VoLKaN75" required>
                    </div>

                    <div class="okey-form-group">
                        <label>Görev Ünvanı</label>
                        <select name="title_id" class="okey-form-control" required>
                            <option value="">Görev ünvanı seçin</option>
                            <?php foreach ($titles as $title): ?>
                                <option value="<?= (int)$title['id'] ?>" <?= (string)$form['title_id'] === (string)$title['id'] ? 'selected' : '' ?>>
                                    <?= admin_e((string)($title['icon'] ?? '👑')) ?> <?= admin_e((string)($title['title_name'] ?? 'Ünvan')) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="okey-form-group">
                        <label>Sıralama</label>
                        <input type="number" name="sort_order" class="okey-form-control" value="<?= admin_e($form['sort_order']) ?>" min="0">
                    </div>

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

                    <div class="okey-form-group">
                        <label>Tik Göster</label>
                        <label class="okey-check-row">
                            <input type="checkbox" name="verified" value="1" <?= $form['verified'] === '1' ? 'checked' : '' ?>>
                            Ana sayfa kartında doğrulama tiki göster.
                        </label>
                    </div>
                </div>

                <div class="okey-form-actions">
                    <button type="submit" class="admin-btn okey-submit">Güncelle</button>
                    <a href="okey-managers.php" class="admin-btn secondary">Listeye Dön</a>
                </div>
            </form>
        <?php else: ?>
            <div class="okey-alert error">
                Düzenlenecek kayıt bulunamadığı için form gösterilemiyor.
            </div>

            <a href="okey-managers.php" class="admin-btn">Listeye Dön</a>
        <?php endif; ?>
    </section>
</section>

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