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

requireAdminLogin();

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

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

if (!$page) {
    setFlashMessage('error', 'Sayfa bulunamadı.');
    redirect('index.php');
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $content = trim($_POST['content'] ?? '');
    $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);
    
    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 pages WHERE slug = ? AND id != ?");
        $stmt->execute([$slug, $id]);
        if ($stmt->fetch()) {
            $slug = $slug . '-' . time();
        }
        
        try {
            $stmt = $pdo->prepare("
                UPDATE pages 
                SET title = ?, slug = ?, content = ?, meta_title = ?, meta_description = ?, meta_keywords = ?, status = ?
                WHERE id = ?
            ");
            $stmt->execute([$title, $slug, $content, $meta_title, $meta_description, $meta_keywords, $status, $id]);
            
            setFlashMessage('success', 'Sayfa başarıyla güncellendi.');
            redirect('index.php');
        } catch (PDOException $e) {
            $error = 'Sayfa güncellenirken bir hata oluştu.';
        }
    }
}

$page_title = 'Sayfa Düzenle';
include '../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3">Sayfa 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" id="pageForm">
            <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($page['title']) ?>" required>
                    </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="20"><?= htmlspecialchars($page['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($page['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($page['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($page['meta_keywords']) ?>">
                    </div>
                </div>
                
                <div class="col-md-4">
                    <div class="mb-3">
                        <label for="status" class="form-label">Durum</label>
                        <select class="form-select" id="status" name="status">
                            <option value="draft" <?= $page['status'] === 'draft' ? 'selected' : '' ?>>Taslak</option>
                            <option value="published" <?= $page['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($page['slug']) ?>" disabled>
                        <small class="text-muted">URL: <?= SITE_URL ?>/page/<?= e($page['slug']) ?></small>
                    </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('pageForm')?.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();
            errorDiv.style.display = 'block';
            editorInstance.editing.view.focus();
            return false;
        } else {
            errorDiv.style.display = 'none';
        }
    }
});
</script>


