<?php
declare(strict_types=1);
require __DIR__ . '/_bootstrap.php';

$type = ($_GET['type'] ?? 'post') === 'page' ? 'page' : 'post';
$table = $type === 'page' ? 'pages' : 'posts';
$id = (int) ($_GET['id'] ?? 0);
$item = null;

if ($id) {
    $stmt = db()->prepare("SELECT * FROM {$table} WHERE id=?");
    $stmt->execute([$id]);
    $item = $stmt->fetch();
    if (!$item) {
        flash('error', 'İçerik bulunamadı.');
        redirect('/admin/' . ($type === 'page' ? 'pages.php' : 'posts.php'));
    }
}

$services = db()->query('SELECT id,name FROM services WHERE is_active=1 ORDER BY sort_order,name')->fetchAll();

if (request_is_post()) {
    verify_csrf();
    try {
        $title = admin_post_string('title');
        $cleanContent = sanitize_rich_html((string) ($_POST['content'] ?? ''));
        if ($title === '' || $cleanContent === '') {
            throw new RuntimeException('Başlık ve içerik zorunludur.');
        }

        $slug = unique_slug($table, slugify(admin_post_string('slug', $title)), $id ?: null);
        $status = admin_post_string('status', 'draft');
        if (!in_array($status, ['draft', 'published'], true)) {
            throw new RuntimeException('Geçersiz yayın durumu.');
        }
        $published = $status === 'published' ? ($item['published_at'] ?? date('Y-m-d H:i:s')) : null;
        $bookingId = (int) ($_POST['booking_service_id'] ?? 0) ?: null;

        if ($type === 'post') {
            $image = upload_image('cover_image', 'posts') ?: admin_post_string('existing_image');
            $excerpt = admin_post_string('excerpt') ?: content_excerpt($cleanContent, 220);
            $values = [
                $title, $slug, $excerpt, $cleanContent, $image,
                admin_post_string('meta_title'), admin_post_string('meta_description'),
                $status, !empty($_POST['show_booking']) ? 1 : 0, $bookingId, $published,
            ];

            if ($id) {
                $values[] = $id;
                db()->prepare('UPDATE posts SET title=?,slug=?,excerpt=?,content=?,cover_image=?,meta_title=?,meta_description=?,status=?,show_booking=?,booking_service_id=?,published_at=?,updated_at=NOW() WHERE id=?')->execute($values);
            } else {
                db()->prepare("INSERT INTO posts(title,slug,excerpt,content,cover_image,meta_title,meta_description,status,show_booking,booking_service_id,language,author_id,published_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,'tr',?,?,NOW(),NOW())")->execute([
                    $values[0], $values[1], $values[2], $values[3], $values[4], $values[5], $values[6], $values[7], $values[8], $values[9],
                    $_SESSION['admin_id'] ?? 1, $values[10],
                ]);
                $id = (int) db()->lastInsertId();
            }
        } else {
            $menuGroup = admin_post_string('menu_group', 'none');
            if (!in_array($menuGroup, ['none', 'corporate', 'legal', 'footer'], true)) {
                throw new RuntimeException('Geçersiz menü grubu.');
            }
            $values = [
                $title, $slug, $cleanContent,
                admin_post_string('meta_title'), admin_post_string('meta_description'),
                $status, !empty($_POST['show_booking']) ? 1 : 0, $bookingId,
                $menuGroup, (int) ($_POST['sort_order'] ?? 0), $published,
            ];

            if ($id) {
                $values[] = $id;
                db()->prepare('UPDATE pages SET title=?,slug=?,content=?,meta_title=?,meta_description=?,status=?,show_booking=?,booking_service_id=?,menu_group=?,sort_order=?,published_at=?,updated_at=NOW() WHERE id=?')->execute($values);
            } else {
                db()->prepare("INSERT INTO pages(title,slug,content,meta_title,meta_description,status,show_booking,booking_service_id,menu_group,sort_order,language,published_at,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,'tr',?,NOW(),NOW())")->execute($values);
                $id = (int) db()->lastInsertId();
            }
        }

        audit_log($item ? 'update' : 'create', $table, $id);
        flash('success', 'İçerik kaydedildi.');
        redirect('/admin/content-edit.php?type=' . $type . '&id=' . $id);
    } catch (Throwable $e) {
        flash('error', $e->getMessage());
    }
}

$initialContent = sanitize_rich_html((string) ($item['content'] ?? ''));
admin_header($item ? 'İçeriği Düzenle' : 'Yeni İçerik');
?>

<?php if ($type === 'post'): ?>
<div class="panel ai-writer-panel" style="margin-top:0" data-ai-writer
     data-endpoint="<?= e(url('/admin/article-generate.php')) ?>"
     data-csrf="<?= e(csrf_token()) ?>">
    <div class="panel-head">
        <div>
            <h2>Yapay Zekâ ile Makale Yazdır</h2>
            <p class="help" style="margin-bottom:0">Kayıtlı Gemini API kullanılır. Üretilen içerik otomatik yayımlanmaz; önce editöre aktarılır.</p>
        </div>
        <span class="badge <?= gemini_api_key() !== '' ? 'active' : 'inactive' ?>"><?= gemini_api_key() !== '' ? 'API hazır' : 'API anahtarı yok' ?></span>
    </div>
    <div class="panel-body">
        <div class="ai-mode-tabs" role="tablist" aria-label="Makale üretim şekli">
            <button class="active" type="button" data-ai-mode="keyword">Anahtar kelime ile</button>
            <button type="button" data-ai-mode="prompt">Özel prompt ile</button>
        </div>
        <div data-ai-pane="keyword">
            <label for="ai-keyword">Anahtar kelime veya konu</label>
            <input id="ai-keyword" data-ai-keyword placeholder="Örnek: Ümraniye spa merkezi" maxlength="300">
            <p class="help">Tek bir konu yazın; sistem kurumsal makale yapısını, meta alanlarını ve başlıkları kendi hazırlar.</p>
        </div>
        <div data-ai-pane="prompt" hidden>
            <label for="ai-prompt">Özel makale promptu</label>
            <textarea id="ai-prompt" data-ai-prompt rows="7" maxlength="6000" placeholder="Örnek: İstanbul'da iş seyahati yapan misafirlere yönelik, sakin ve kurumsal tonda 1000 kelimelik bir wellness rehberi yaz. Hazırlık, hizmet seçimi ve online rezervasyon bölümleri olsun."></textarea>
            <p class="help">Konu, hedef kitle, anlatım tonu, bölüm planı ve istediğiniz ayrıntıları yazabilirsiniz. Doğrulanmamış kurumsal veya sağlık iddiaları yine kullanılmaz.</p>
        </div>
        <div class="actions ai-writer-actions">
            <button class="button" type="button" data-ai-generate>Yapay Zekâya Yazdır</button>
            <span class="ai-writer-status muted" data-ai-status></span>
        </div>
    </div>
</div>
<?php endif; ?>

<form id="content-form" method="post" enctype="multipart/form-data">
    <div class="panel">
        <div class="panel-head">
            <h2><?= $type === 'page' ? 'Kurumsal sayfa' : 'Wellness makalesi' ?></h2>
            <div class="actions">
                <a class="button secondary" href="<?= url('/admin/' . ($type === 'page' ? 'pages.php' : 'posts.php')) ?>">Listeye Dön</a>
                <button class="button" type="submit">Kaydet</button>
            </div>
        </div>
        <div class="panel-body form-grid">
            <?= csrf_field() ?>
            <div>
                <label>Başlık</label>
                <input id="content-title" name="title" value="<?= e($item['title'] ?? '') ?>" required>
            </div>
            <div>
                <label>URL</label>
                <input id="content-slug" name="slug" value="<?= e($item['slug'] ?? '') ?>">
            </div>

            <?php if ($type === 'post'): ?>
                <div class="full">
                    <label>Kısa özet</label>
                    <textarea id="content-excerpt" name="excerpt"><?= e($item['excerpt'] ?? '') ?></textarea>
                </div>
                <div>
                    <label>Kapak görseli</label>
                    <input type="file" name="cover_image" accept="image/*">
                    <input type="hidden" name="existing_image" value="<?= e($item['cover_image'] ?? '') ?>">
                </div>
            <?php else: ?>
                <div>
                    <label>Menü grubu</label>
                    <select name="menu_group">
                        <?php foreach (['none' => 'Menüde yok', 'corporate' => 'Kurumsal', 'legal' => 'Yasal', 'footer' => 'Footer'] as $key => $value): ?>
                            <option value="<?= $key ?>" <?= ($item['menu_group'] ?? 'none') === $key ? 'selected' : '' ?>><?= $value ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label>Sıralama</label>
                    <input type="number" name="sort_order" value="<?= e($item['sort_order'] ?? 0) ?>">
                </div>
            <?php endif; ?>

            <div class="full">
                <label>İçerik editörü</label>
                <div class="rich-editor" data-rich-editor>
                    <div class="rich-editor-toolbar" role="toolbar" aria-label="Metin biçimlendirme araçları">
                        <select data-editor-block title="Paragraf biçimi" aria-label="Paragraf biçimi">
                            <option value="p">Paragraf</option>
                            <option value="h2">Başlık 2</option>
                            <option value="h3">Başlık 3</option>
                            <option value="blockquote">Alıntı</option>
                        </select>
                        <button type="button" data-editor-command="bold" title="Kalın"><b>K</b></button>
                        <button type="button" data-editor-command="italic" title="İtalik"><i>İ</i></button>
                        <button type="button" data-editor-command="insertUnorderedList" title="Madde listesi">• Liste</button>
                        <button type="button" data-editor-command="insertOrderedList" title="Numaralı liste">1. Liste</button>
                        <button type="button" data-editor-link title="Bağlantı ekle">🔗 Bağlantı</button>
                        <button type="button" data-editor-command="unlink" title="Bağlantıyı kaldır">Bağlantıyı kaldır</button>
                        <button type="button" data-editor-command="removeFormat" title="Biçimi temizle">Biçimi temizle</button>
                        <button type="button" data-editor-command="undo" title="Geri al">↶</button>
                        <button type="button" data-editor-command="redo" title="Yinele">↷</button>
                        <button type="button" class="source-toggle" data-editor-source-toggle>HTML Görünümü</button>
                    </div>
                    <div class="rich-editor-area" data-editor-area contenteditable="true" spellcheck="true"><?= $initialContent ?></div>
                    <textarea class="rich-editor-source" name="content" rows="22" data-editor-source hidden><?= e($initialContent) ?></textarea>
                </div>
                <p class="help">Normal editörde yazabilirsiniz. İhtiyaç halinde “HTML Görünümü” ile kaynak koduna geçebilirsiniz.</p>
            </div>

            <div>
                <label>Meta başlığı</label>
                <input id="content-meta-title" name="meta_title" value="<?= e($item['meta_title'] ?? '') ?>">
            </div>
            <div>
                <label>Meta açıklaması</label>
                <textarea id="content-meta-description" name="meta_description"><?= e($item['meta_description'] ?? '') ?></textarea>
            </div>
            <div>
                <label>Durum</label>
                <select name="status">
                    <option value="draft" <?= ($item['status'] ?? 'draft') === 'draft' ? 'selected' : '' ?>>Taslak</option>
                    <option value="published" <?= ($item['status'] ?? '') === 'published' ? 'selected' : '' ?>>Yayında</option>
                </select>
            </div>
            <div>
                <label>Rezervasyon alanında seçili hizmet</label>
                <select name="booking_service_id">
                    <option value="">Genel rezervasyon</option>
                    <?php foreach ($services as $service): ?>
                        <option value="<?= (int) $service['id'] ?>" <?= ($item['booking_service_id'] ?? 0) == $service['id'] ? 'selected' : '' ?>><?= e($service['name']) ?></option>
                    <?php endforeach; ?>
                </select>
                <label class="checkrow"><input type="checkbox" name="show_booking" value="1" <?= !$item || !empty($item['show_booking']) ? 'checked' : '' ?>> İçeriğin altında rezervasyon alanı göster</label>
            </div>
        </div>
    </div>
</form>

<?php admin_footer(); ?>
