<?php
require_once '../../config/config.php';
require_once '../../includes/auth.php';

requireAdminLogin();

$id = $_GET['id'] ?? 0;

$stmt = $pdo->prepare("SELECT * FROM blog_posts WHERE id = ?");
$stmt->execute([$id]);
$post = $stmt->fetch();

if (!$post) {
    setFlashMessage('error', 'Blog yazısı bulunamadı.');
    redirect('index.php');
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $excerpt = trim($_POST['excerpt'] ?? '');
    $meta_title = trim($_POST['meta_title'] ?? '');
    $meta_description = trim($_POST['meta_description'] ?? '');
    $meta_keywords = trim($_POST['meta_keywords'] ?? '');
    $status = $_POST['status'] ?? 'draft';
    
    // Slug oluştur
    $slug = createSlug($title);
    
    // Resim yükleme
    $image = $post['image'];
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload = uploadImage($_FILES['image'], 'blog');
        if ($upload['success']) {
            // Eski resmi sil
            if ($image) {
                $oldPath = str_replace(UPLOAD_URL, UPLOAD_PATH, $image);
                deleteImage($oldPath);
            }
            $image = $upload['url'];
        } else {
            $error = $upload['message'];
        }
    }
    
    // Excerpt oluştur
    if (empty($excerpt) && !empty($content)) {
        $excerpt = excerpt(strip_tags($content), 150);
    }
    
    if (empty($title)) {
        $error = 'Başlık gereklidir.';
    } elseif (empty($content)) {
        $error = 'İçerik gereklidir.';
    } else {
        // Slug'un benzersiz olup olmadığını kontrol et (kendi ID'si hariç)
        $stmt = $pdo->prepare("SELECT id FROM blog_posts WHERE slug = ? AND id != ?");
        $stmt->execute([$slug, $id]);
        if ($stmt->fetch()) {
            $slug = $slug . '-' . time();
        }
        
        try {
            $stmt = $pdo->prepare("
                UPDATE blog_posts 
                SET title = ?, slug = ?, content = ?, excerpt = ?, image = ?, meta_title = ?, meta_description = ?, meta_keywords = ?, status = ?
                WHERE id = ?
            ");
            $stmt->execute([$title, $slug, $content, $excerpt, $image, $meta_title, $meta_description, $meta_keywords, $status, $id]);
            
            setFlashMessage('success', 'Blog yazısı başarıyla güncellendi.');
            redirect('index.php');
        } catch (PDOException $e) {
            $error = 'Blog yazısı güncellenirken bir hata oluştu.';
        }
    }
}

$page_title = 'Blog Yazısı Düzenle';
include '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Blog Yazısı Düzenle</h1>
    <a href="index.php" class="btn btn-secondary">
        <i class="fas fa-arrow-left me-2"></i>Geri Dön
    </a>
</div>

<?php if ($error): ?>
    <div class="alert alert-danger"><?= e($error) ?></div>
<?php endif; ?>

<div class="card">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data" id="blogForm">
            <div class="row">
                <div class="col-md-8">
                    <div class="mb-3">
                        <label for="title" class="form-label">Başlık <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="title" name="title" value="<?= e($post['title']) ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label for="excerpt" class="form-label">Özet</label>
                        <textarea class="form-control" id="excerpt" name="excerpt" rows="3"><?= e($post['excerpt']) ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="content" class="form-label">İçerik <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="content" name="content" rows="15"><?= htmlspecialchars($post['content'], ENT_QUOTES, 'UTF-8') ?></textarea>
                        <div id="content-error" class="text-danger small mt-1" style="display: none;">İçerik gereklidir.</div>
                    </div>
                    
                    <h5 class="mt-4 mb-3">SEO Ayarları</h5>
                    
                    <div class="mb-3">
                        <label for="meta_title" class="form-label">Meta Başlık</label>
                        <input type="text" class="form-control" id="meta_title" name="meta_title" value="<?= e($post['meta_title']) ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label for="meta_description" class="form-label">Meta Açıklama</label>
                        <textarea class="form-control" id="meta_description" name="meta_description" rows="3"><?= e($post['meta_description']) ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label for="meta_keywords" class="form-label">Meta Anahtar Kelimeler</label>
                        <input type="text" class="form-control" id="meta_keywords" name="meta_keywords" value="<?= e($post['meta_keywords']) ?>">
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="image" class="form-label">Öne Çıkan Görsel</label>
                        <?php if ($post['image']): ?>
                            <div class="mb-2">
                                <img src="<?= e($post['image']) ?>" alt="" class="img-thumbnail w-100">
                            </div>
                        <?php endif; ?>
                        <input type="file" class="form-control" id="image" name="image" accept="image/*">
                    </div>
                    
                    <div class="mb-3">
                        <label for="status" class="form-label">Durum</label>
                        <select class="form-select" id="status" name="status">
                            <option value="draft" <?= $post['status'] === 'draft' ? 'selected' : '' ?>>Taslak</option>
                            <option value="published" <?= $post['status'] === 'published' ? 'selected' : '' ?>>Yayında</option>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Slug</label>
                        <input type="text" class="form-control" value="<?= e($post['slug']) ?>" disabled>
                        <small class="text-muted">URL: <?= SITE_URL ?>/blog/<?= e($post['slug']) ?></small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Görüntülenme</label>
                        <input type="text" class="form-control" value="<?= $post['views'] ?>" disabled>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-save me-2"></i>Güncelle
                </button>
                <a href="index.php" class="btn btn-secondary">İptal</a>
            </div>
        </form>
    </div>
</div>

<?php include '../includes/footer.php'; ?>

<!-- CKEditor (Ücretsiz) -->
<script src="https://cdn.ckeditor.com/ckeditor5/41.0.0/classic/ckeditor.js"></script>
<script>
let editorInstance;

ClassicEditor
    .create(document.querySelector('#content'), {
        language: 'tr',
        toolbar: {
            items: [
                'heading', '|',
                'bold', 'italic', 'link', '|',
                'bulletedList', 'numberedList', '|',
                'insertImage', 'insertTable', '|',
                'undo', 'redo', '|',
                'sourceEditing'
            ]
        },
        simpleUpload: {
            uploadUrl: '../upload-editor-image.php',
            withCredentials: false,
            headers: {
                'X-CSRF-TOKEN': 'CSRF-Token'
            }
        }
    })
    .then(editor => {
        editorInstance = editor;
    })
    .catch(error => {
        console.error(error);
    });

// Form gönderilmeden önce editor içeriğini textarea'ya yaz ve validasyon yap
document.getElementById('blogForm')?.addEventListener('submit', function(e) {
    if (editorInstance) {
        const content = editorInstance.getData();
        const textarea = document.getElementById('content');
        const errorDiv = document.getElementById('content-error');
        
        // İçeriği textarea'ya yaz
        textarea.value = content;
        
        // Boş içerik kontrolü (HTML tag'leri olmadan)
        const textContent = content.replace(/<[^>]*>/g, '').trim();
        
        if (!textContent) {
            e.preventDefault();
            if (errorDiv) {
                errorDiv.style.display = 'block';
            }
            editorInstance.editing.view.focus();
            return false;
        } else {
            if (errorDiv) {
                errorDiv.style.display = 'none';
            }
        }
    }
});
</script>
