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

/*
|--------------------------------------------------------------------------
| YENİ REKLAM VE SPONSOR OLUŞTURMA EKRANI
|--------------------------------------------------------------------------
| ad-view.php
| Okey Platformu Reklam ve Sponsor Oluşturma Modülü
| Developed By VoLKaN75
|--------------------------------------------------------------------------
*/

declare(strict_types=1);

$pageTitle = 'Yeni Reklam Oluştur';
$pageDescription = 'Ana sayfa reklam ve sponsor alanı için yeni reklam kaydı oluşturun.';

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');
    }
}

$message = '';
$error = '';
$success = false;

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

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

$form = [
    'title'              => '',
    'description'        => '',
    'button_text'        => 'Oyunu İndir',
    'button_url'         => 'downloads.php',
    'second_button_text' => 'Üye Ol',
    'second_button_url'  => 'register.php',
    'sort_order'         => '1',
    'status'             => 'active',
];

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $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 {
            $imagePath = '';

            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)) {
                        $imagePath = $uploadUrl . $newFileName;
                    } else {
                        $error = 'Görsel yüklenirken hata oluştu.';
                    }
                }
            }

            if ($error === '') {
                $stmt = $pdo->prepare("
                    INSERT INTO site_ads
                    (
                        title,
                        description,
                        image,
                        button_text,
                        button_url,
                        second_button_text,
                        second_button_url,
                        sort_order,
                        status,
                        created_at,
                        updated_at
                    )
                    VALUES
                    (
                        :title,
                        :description,
                        :image,
                        :button_text,
                        :button_url,
                        :second_button_text,
                        :second_button_url,
                        :sort_order,
                        :status,
                        NOW(),
                        NOW()
                    )
                ");

                $stmt->execute([
                    'title'              => $form['title'],
                    'description'        => $form['description'],
                    'image'              => $imagePath,
                    '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'],
                ]);

                $success = true;
                $message = 'Reklam başarıyla oluşturuldu. 10 saniye sonra listeye yönlendiriliyorsunuz.';
                header('Refresh: 10; URL=ads.php');
            }
        }
    }
} catch (Throwable $e) {
    error_log('Reklam oluşturma hatası: ' . $e->getMessage());
    $error = 'Reklam oluşturulurken sistem hatası oluştu.';
}
?>

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

.ad-form-card,
.ad-info-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-form-card:after,
.ad-info-card:after{
    content:attr(data-icon);
    position:absolute;
    right:20px;
    bottom:8px;
    font-size:80px;
    opacity:.08;
    pointer-events:none;
}

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

.ad-form-card p,
.ad-info-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);
}

.preview-box{
    min-height:250px;
    border-radius:24px;
    border:1px dashed rgba(245,182,66,.35);
    background:
        linear-gradient(90deg,rgba(0,0,0,.90),rgba(0,0,0,.45)),
        radial-gradient(circle at top right,rgba(245,182,66,.20),transparent 45%),
        #070911;
    display:flex;
    align-items:center;
    justify-content:center;
    text-align:center;
    padding:26px;
    margin-bottom:20px;
}

.preview-box strong{
    display:block;
    color:#f5b642;
    font-size:22px;
    margin-bottom:8px;
}

.preview-box span{
    display:block;
    color:#d7dce6;
    font-size:13px;
    font-weight:800;
    line-height:1.7;
}

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

.info-list li{
    padding:14px;
    border-radius:18px;
    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-form-wrap{
        grid-template-columns:1fr;
    }
}

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

    .ad-form-card,
    .ad-info-card{
        padding:20px;
    }
}
</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; ?>

<section class="ad-form-wrap">
    <div class="ad-form-card" data-icon="📣">
        <h2>Reklam Bilgileri</h2>
        <p>Ana sayfadaki “Reklam ve Sponsorlarımız” bölümünde gösterilecek reklam içeriğini oluşturun.</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']) ?>" placeholder="Türkiye’nin En Keyifli Okey Platformu" required>
                </div>

                <div class="form-group full">
                    <label>Reklam Açıklaması</label>
                    <textarea name="description" placeholder="Gerçek oyuncular • Akıcı oyun • Premium deneyim" required><?= admin_e($form['description']) ?></textarea>
                </div>

                <div class="form-group full">
                    <label>Reklam Görseli</label>
                    <input type="file" name="image" accept=".jpg,.jpeg,.png,.webp,.gif">
                    <div class="form-help">Önerilen ölçü: 1920x700 px. Yükleme yolu: uploads/ads/</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">Reklamı Oluştur</button>
                <a href="ads.php" class="admin-btn passive">Listeye Dön</a>
            </div>
        </form>
    </div>

    <aside class="ad-info-card" data-icon="🖼️">
        <h2>Görsel Önizleme Alanı</h2>
        <p>Bu alan ana sayfadaki reklam banner mantığına göre hazırlanmıştır.</p>

        <div class="preview-box">
            <div>
                <strong>Reklam Banner</strong>
                <span>Yüklediğiniz görsel ana sayfada koyu degrade ile birlikte gösterilecektir.</span>
            </div>
        </div>

        <ul class="info-list">
            <li><b>Başlık:</b> Ana reklam sloganı olarak görünür.</li>
            <li><b>Açıklama:</b> Başlığın altında kısa tanıtım metni olarak görünür.</li>
            <li><b>Butonlar:</b> Oyunu indir, üye ol veya sponsor linkleri için kullanılabilir.</li>
            <li><b>Durum:</b> Sadece aktif reklamlar ana sayfada görünür.</li>
        </ul>
    </aside>
</section>

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