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

/*
|--------------------------------------------------------------------------
| REKLAM VE SPONSOR DÜZENLEME EKRANI
|--------------------------------------------------------------------------
| ad-edit.php
| Okey Platformu Reklam ve Sponsor Düzenleme Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Reklam Düzenle';
$pageDescription = 'Ana sayfa reklam ve sponsor alanındaki mevcut reklam kaydını düzenleyin.';

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

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

function edit_ad_value(array $ad, array $keys, string $default = ''): string
{
    foreach ($keys as $key) {
        if (isset($ad[$key]) && trim((string)$ad[$key]) !== '') {
            return (string)$ad[$key];
        }
    }

    return $default;
}

function edit_ad_image_url(string $image): string
{
    $image = trim(str_replace('\\', '/', $image));

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

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

    $imageName = basename($image);

    $paths = [
        [
            'disk' => __DIR__ . '/../uploads/ads/' . $imageName,
            'url'  => '../uploads/ads/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/site/' . $imageName,
            'url'  => '../uploads/site/' . $imageName,
        ],
        [
            'disk' => __DIR__ . '/../uploads/' . $imageName,
            'url'  => '../uploads/' . $imageName,
        ],
    ];

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

    return '../assets/images/no-image.png';
}

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

$message = '';
$error = '';
$success = false;
$ad = [];

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

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

if ($id <= 0) {
    $error = 'Geçersiz reklam kaydı.';
} else {
    try {
        $stmt = $pdo->prepare("SELECT * FROM site_ads WHERE id = :id LIMIT 1");
        $stmt->execute(['id' => $id]);
        $ad = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

        if (!$ad) {
            $error = 'Reklam kaydı bulunamadı.';
        }
    } catch (Throwable $e) {
        error_log('Reklam bulma hatası: ' . $e->getMessage());
        $error = 'Reklam kaydı alınırken sistem hatası oluştu.';
    }
}

$form = [
    'title'              => edit_ad_value($ad, ['title'], ''),
    'description'        => edit_ad_value($ad, ['description', 'summary'], ''),
    'image'              => edit_ad_value($ad, ['image', 'image_path', 'banner'], ''),
    'button_text'        => edit_ad_value($ad, ['button_text', 'btn_text'], 'Oyunu İndir'),
    'button_url'         => edit_ad_value($ad, ['button_url', 'btn_url', 'url'], 'downloads.php'),
    'second_button_text' => edit_ad_value($ad, ['second_button_text'], 'Üye Ol'),
    'second_button_url'  => edit_ad_value($ad, ['second_button_url'], 'register.php'),
    'sort_order'         => edit_ad_value($ad, ['sort_order'], '0'),
    'status'             => edit_ad_value($ad, ['status'], 'active'),
];

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && $id > 0 && $ad) {
        $form['title']              = trim((string)($_POST['title'] ?? ''));
        $form['description']        = trim((string)($_POST['description'] ?? ''));
        $form['button_text']        = trim((string)($_POST['button_text'] ?? ''));
        $form['button_url']         = trim((string)($_POST['button_url'] ?? ''));
        $form['second_button_text'] = trim((string)($_POST['second_button_text'] ?? ''));
        $form['second_button_url']  = trim((string)($_POST['second_button_url'] ?? ''));
        $form['sort_order']         = trim((string)($_POST['sort_order'] ?? '0'));
        $form['status']             = trim((string)($_POST['status'] ?? 'active'));

        if ($form['title'] === '') {
            $error = 'Reklam başlığı boş bırakılamaz.';
        } elseif ($form['description'] === '') {
            $error = 'Reklam açıklaması boş bırakılamaz.';
        } elseif (!in_array($form['status'], ['active', 'passive'], true)) {
            $error = 'Geçersiz durum seçildi.';
        } else {
            $newImagePath = $form['image'];

            if (!empty($_FILES['image']['name'])) {
                $allowedExtensions = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
                $fileName = (string)$_FILES['image']['name'];
                $fileTmp  = (string)$_FILES['image']['tmp_name'];
                $fileExt  = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

                if (!in_array($fileExt, $allowedExtensions, true)) {
                    $error = 'Sadece JPG, JPEG, PNG, WEBP veya GIF görsel yükleyebilirsiniz.';
                } else {
                    $newFileName = 'ad-' . date('YmdHis') . '-' . bin2hex(random_bytes(4)) . '.' . $fileExt;
                    $targetFile = $uploadDir . $newFileName;

                    if (move_uploaded_file($fileTmp, $targetFile)) {
                        $newImagePath = $uploadUrl . $newFileName;
                    } else {
                        $error = 'Yeni görsel yüklenirken hata oluştu.';
                    }
                }
            }

            if ($error === '') {
                $stmt = $pdo->prepare("
                    UPDATE site_ads
                    SET
                        title = :title,
                        description = :description,
                        image = :image,
                        button_text = :button_text,
                        button_url = :button_url,
                        second_button_text = :second_button_text,
                        second_button_url = :second_button_url,
                        sort_order = :sort_order,
                        status = :status,
                        updated_at = NOW()
                    WHERE id = :id
                    LIMIT 1
                ");

                $stmt->execute([
                    'title'              => $form['title'],
                    'description'        => $form['description'],
                    'image'              => $newImagePath,
                    'button_text'        => $form['button_text'] !== '' ? $form['button_text'] : 'Oyunu İndir',
                    'button_url'         => $form['button_url'] !== '' ? $form['button_url'] : 'downloads.php',
                    'second_button_text' => $form['second_button_text'] !== '' ? $form['second_button_text'] : 'Üye Ol',
                    'second_button_url'  => $form['second_button_url'] !== '' ? $form['second_button_url'] : 'register.php',
                    'sort_order'         => (int)$form['sort_order'],
                    'status'             => $form['status'],
                    'id'                 => $id,
                ]);

                $form['image'] = $newImagePath;
                $success = true;
                $message = 'Reklam başarıyla güncellendi. 10 saniye sonra listeye yönlendiriliyorsunuz.';
                header('Refresh: 10; URL=ads.php');
            }
        }
    }
} catch (Throwable $e) {
    error_log('Reklam güncelleme hatası: ' . $e->getMessage());
    $error = 'Reklam güncellenirken sistem hatası oluştu.';
}
?>

<style>
.ad-edit-wrap{
    display:grid;
    grid-template-columns:1.15fr .85fr;
    gap:22px;
}

.ad-edit-card,
.ad-preview-card{
    position:relative;
    overflow:hidden;
    padding:26px;
    border-radius:28px;
    background:rgba(255,255,255,.052);
    border:1px solid rgba(255,255,255,.09);
    box-shadow:0 24px 70px rgba(0,0,0,.18);
}

.ad-edit-card:after,
.ad-preview-card:after{
    content:attr(data-icon);
    position:absolute;
    right:20px;
    bottom:8px;
    font-size:80px;
    opacity:.08;
    pointer-events:none;
}

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

.ad-edit-card p,
.ad-preview-card p{
    margin:0 0 22px;
    color:#9aa3b2;
    font-size:13px;
    line-height:1.7;
    font-weight:700;
}

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

.form-group{
    display:flex;
    flex-direction:column;
    gap:8px;
}

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

.form-group label{
    color:#d7dce6;
    font-size:13px;
    font-weight:900;
}

.form-group input,
.form-group textarea,
.form-group select{
    width:100%;
    min-height:48px;
    border-radius:15px;
    border:1px solid rgba(255,255,255,.11);
    background:rgba(0,0,0,.22);
    color:#fff;
    padding:0 15px;
    outline:none;
    font-size:14px;
    font-weight:700;
}

.form-group textarea{
    min-height:130px;
    padding:15px;
    resize:vertical;
    line-height:1.6;
}

.form-group input:focus,
.form-group textarea:focus,
.form-group select:focus{
    border-color:#f5b642;
    box-shadow:0 0 0 3px rgba(245,182,66,.12);
}

.form-help{
    color:#9aa3b2;
    font-size:12px;
    font-weight:700;
    line-height:1.5;
}

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

.admin-btn.passive{
    background:rgba(255,255,255,.07);
    color:#fff;
    border:1px solid rgba(255,255,255,.12);
}

.alert{
    margin-bottom:20px;
    padding:16px 18px;
    border-radius:20px;
    font-weight:900;
    line-height:1.6;
}

.alert.success{
    color:#b8ffd7;
    background:rgba(0,170,80,.14);
    border:1px solid rgba(0,255,140,.22);
}

.alert.error{
    color:#ffdada;
    background:rgba(185,0,0,.16);
    border:1px solid rgba(255,80,80,.26);
}

.current-image{
    overflow:hidden;
    border-radius:24px;
    border:1px solid rgba(245,182,66,.28);
    background:#070911;
    margin-bottom:20px;
    box-shadow:0 22px 55px rgba(0,0,0,.24);
}

.current-image img{
    display:block;
    width:100%;
    height:230px;
    object-fit:cover;
}

.current-image-info{
    padding:14px 16px;
    color:#9aa3b2;
    font-size:12px;
    font-weight:800;
    border-top:1px solid rgba(255,255,255,.08);
}

.preview-live{
    position:relative;
    overflow:hidden;
    min-height:250px;
    border-radius:24px;
    padding:26px;
    border:1px solid rgba(245,182,66,.26);
    background:
        linear-gradient(90deg,rgba(0,0,0,.94),rgba(0,0,0,.55)),
        url('<?= admin_e(edit_ad_image_url($form['image'])) ?>') center/cover no-repeat;
    display:flex;
    align-items:center;
}

.preview-live:before{
    content:"";
    position:absolute;
    inset:0;
    background:radial-gradient(circle at top left,rgba(245,182,66,.16),transparent 44%);
}

.preview-live-content{
    position:relative;
    z-index:2;
    max-width:420px;
}

.preview-live-content h3{
    margin:0;
    color:#fff;
    font-size:32px;
    line-height:1.05;
    text-transform:uppercase;
}

.preview-live-content p{
    margin:14px 0 20px;
    color:#dce3ef;
    font-size:15px;
}

.preview-actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}

.preview-btn{
    min-height:42px;
    padding:0 14px;
    border-radius:12px;
    display:inline-flex;
    align-items:center;
    justify-content:center;
    font-size:12px;
    font-weight:1000;
    text-transform:uppercase;
    color:#111;
    background:linear-gradient(135deg,#f5b642,#ffcf6a);
}

.preview-btn.red{
    color:#fff;
    background:linear-gradient(135deg,#a70000,#e91515);
}

.info-list{
    margin:18px 0 0;
    padding:0;
    list-style:none;
    display:grid;
    gap:12px;
}

.info-list li{
    padding:13px;
    border-radius:17px;
    color:#d7dce6;
    background:rgba(255,255,255,.045);
    border:1px solid rgba(255,255,255,.08);
    font-size:13px;
    font-weight:800;
    line-height:1.6;
}

.info-list li b{
    color:#f5b642;
}

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

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

    .ad-edit-card,
    .ad-preview-card{
        padding:20px;
    }

    .preview-live-content h3{
        font-size:25px;
    }
}
</style>

<?php if ($message): ?>
    <section class="alert success">
        <?= admin_e($message) ?>
    </section>
<?php endif; ?>

<?php if ($error): ?>
    <section class="alert error">
        <?= admin_e($error) ?>
    </section>
<?php endif; ?>

<?php if ($ad): ?>
<section class="ad-edit-wrap">
    <div class="ad-edit-card" data-icon="✏️">
        <h2>Reklam Bilgilerini Düzenle</h2>
        <p>Ana sayfada yayınlanan reklam ve sponsor kaydının içeriğini buradan güncelleyebilirsiniz.</p>

        <form method="post" enctype="multipart/form-data">
            <div class="form-grid">
                <div class="form-group full">
                    <label>Reklam Başlığı</label>
                    <input type="text" name="title" value="<?= admin_e($form['title']) ?>" required>
                </div>

                <div class="form-group full">
                    <label>Reklam Açıklaması</label>
                    <textarea name="description" required><?= admin_e($form['description']) ?></textarea>
                </div>

                <div class="form-group full">
                    <label>Yeni Reklam Görseli</label>
                    <input type="file" name="image" accept=".jpg,.jpeg,.png,.webp,.gif">
                    <div class="form-help">Yeni görsel yüklerseniz mevcut görsel değişir. Önerilen ölçü: 1920x700 px.</div>
                </div>

                <div class="form-group">
                    <label>1. Buton Yazısı</label>
                    <input type="text" name="button_text" value="<?= admin_e($form['button_text']) ?>">
                </div>

                <div class="form-group">
                    <label>1. Buton Linki</label>
                    <input type="text" name="button_url" value="<?= admin_e($form['button_url']) ?>">
                </div>

                <div class="form-group">
                    <label>2. Buton Yazısı</label>
                    <input type="text" name="second_button_text" value="<?= admin_e($form['second_button_text']) ?>">
                </div>

                <div class="form-group">
                    <label>2. Buton Linki</label>
                    <input type="text" name="second_button_url" value="<?= admin_e($form['second_button_url']) ?>">
                </div>

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

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

            <div class="form-actions">
                <button type="submit" class="admin-btn">Değişiklikleri Kaydet</button>
                <a href="ads.php" class="admin-btn passive">Listeye Dön</a>
            </div>
        </form>
    </div>

    <aside class="ad-preview-card" data-icon="🖼️">
        <h2>Mevcut Görsel ve Önizleme</h2>
        <p>Yayınlanan reklamın ana sayfadaki yaklaşık görünümünü buradan kontrol edebilirsiniz.</p>

        <div class="current-image">
            <img src="<?= admin_e(edit_ad_image_url($form['image'])) ?>" alt="Reklam Görseli">
            <div class="current-image-info">
                Görsel yolu: <?= admin_e($form['image'] !== '' ? $form['image'] : 'Görsel bulunamadı') ?>
            </div>
        </div>

        <div class="preview-live">
            <div class="preview-live-content">
                <h3><?= admin_e($form['title']) ?></h3>
                <p><?= admin_e($form['description']) ?></p>

                <div class="preview-actions">
                    <span class="preview-btn red"><?= admin_e($form['button_text']) ?></span>
                    <span class="preview-btn"><?= admin_e($form['second_button_text']) ?></span>
                </div>
            </div>
        </div>

        <ul class="info-list">
            <li><b>Durum:</b> Aktif olan reklamlar ana sayfada görünür.</li>
            <li><b>Sıralama:</b> Düşük sıra numarası önce gösterilir.</li>
            <li><b>Görsel:</b> Yeni görsel yüklerseniz kayıt otomatik olarak yeni yola bağlanır.</li>
        </ul>
    </aside>
</section>
<?php endif; ?>

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