<?php
/**
 * SMM Paket Satış Scripti - Sayfa Yönetimi
 * @version 1.0.0
 */

require_once __DIR__ . '/../config.php';

if (!isLoggedIn() || !isAdmin()) {
    redirect(SITE_URL . '/admin/');
    exit;
}

// CSRF Token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrfToken = $_SESSION['csrf_token'];

// POST İşlemleri
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if (!hash_equals($csrfToken, $_POST['csrf_token'] ?? '')) {
        setFlash('error', 'Güvenlik hatası.');
        redirect(SITE_URL . '/admin/sayfalar.php');
        exit;
    }
    
    $action = $_POST['action'];
    
    try {
        switch ($action) {
            case 'add_page':
                $title = trim($_POST['title'] ?? '');
                $slug = trim($_POST['slug'] ?? '');
                $content = $_POST['content'] ?? '';
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                $showInMenu = isset($_POST['show_in_menu']) ? 1 : 0;
                $showInFooter = isset($_POST['show_in_footer']) ? 1 : 0;
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                
                if (empty($title)) {
                    throw new Exception('Sayfa başlığı zorunludur.');
                }
                
                // Slug oluştur
                if (empty($slug)) {
                    $slug = createSlug($title);
                } else {
                    $slug = createSlug($slug);
                }
                
                // Slug benzersizlik kontrolü
                $checkStmt = $db->prepare("SELECT id FROM pages WHERE slug = ?");
                $checkStmt->execute([$slug]);
                if ($checkStmt->fetch()) {
                    $slug = $slug . '-' . time();
                }
                
                $stmt = $db->prepare("
                    INSERT INTO pages (title, slug, content, is_active, show_in_menu, show_in_footer, sort_order, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, NOW())
                ");
                $stmt->execute([$title, $slug, $content, $isActive, $showInMenu, $showInFooter, $sortOrder]);
                
                setFlash('success', 'Sayfa başarıyla eklendi.');
                break;
                
            case 'update_page':
                $pageId = (int)($_POST['page_id'] ?? 0);
                $title = trim($_POST['title'] ?? '');
                $slug = trim($_POST['slug'] ?? '');
                $content = $_POST['content'] ?? '';
                $isActive = isset($_POST['is_active']) ? 1 : 0;
                $showInMenu = isset($_POST['show_in_menu']) ? 1 : 0;
                $showInFooter = isset($_POST['show_in_footer']) ? 1 : 0;
                $sortOrder = (int)($_POST['sort_order'] ?? 0);
                
                if ($pageId <= 0) {
                    throw new Exception('Geçersiz sayfa.');
                }
                
                if (empty($title)) {
                    throw new Exception('Sayfa başlığı zorunludur.');
                }
                
                // Slug oluştur
                if (empty($slug)) {
                    $slug = createSlug($title);
                } else {
                    $slug = createSlug($slug);
                }
                
                // Slug benzersizlik kontrolü (kendi hariç)
                $checkStmt = $db->prepare("SELECT id FROM pages WHERE slug = ? AND id != ?");
                $checkStmt->execute([$slug, $pageId]);
                if ($checkStmt->fetch()) {
                    $slug = $slug . '-' . time();
                }
                
                $stmt = $db->prepare("
                    UPDATE pages 
                    SET title = ?, slug = ?, content = ?, is_active = ?, show_in_menu = ?, show_in_footer = ?, sort_order = ?
                    WHERE id = ?
                ");
                $stmt->execute([$title, $slug, $content, $isActive, $showInMenu, $showInFooter, $sortOrder, $pageId]);
                
                setFlash('success', 'Sayfa güncellendi.');
                break;
                
            case 'delete_page':
                $pageId = (int)($_POST['page_id'] ?? 0);
                
                if ($pageId <= 0) {
                    throw new Exception('Geçersiz sayfa.');
                }
                
                $db->prepare("DELETE FROM pages WHERE id = ?")->execute([$pageId]);
                
                setFlash('success', 'Sayfa silindi.');
                break;
                
            case 'toggle_status':
                $pageId = (int)($_POST['page_id'] ?? 0);
                $field = $_POST['field'] ?? 'is_active';
                $value = (int)($_POST['value'] ?? 0);
                
                if ($pageId <= 0) {
                    throw new Exception('Geçersiz sayfa.');
                }
                
                if (!in_array($field, ['is_active', 'show_in_menu', 'show_in_footer'])) {
                    throw new Exception('Geçersiz alan.');
                }
                
                $db->prepare("UPDATE pages SET $field = ? WHERE id = ?")->execute([$value, $pageId]);
                
                $labels = [
                    'is_active' => $value ? 'aktif' : 'pasif',
                    'show_in_menu' => $value ? 'menüde gösterilecek' : 'menüden kaldırıldı',
                    'show_in_footer' => $value ? 'footerda gösterilecek' : 'footerdan kaldırıldı'
                ];
                
                setFlash('success', 'Sayfa ' . $labels[$field] . '.');
                break;
                
            case 'duplicate_page':
                $pageId = (int)($_POST['page_id'] ?? 0);
                
                if ($pageId <= 0) {
                    throw new Exception('Geçersiz sayfa.');
                }
                
                $stmt = $db->prepare("SELECT * FROM pages WHERE id = ?");
                $stmt->execute([$pageId]);
                $page = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if (!$page) {
                    throw new Exception('Sayfa bulunamadı.');
                }
                
                $newSlug = $page['slug'] . '-kopya-' . time();
                $newTitle = $page['title'] . ' (Kopya)';
                
                $stmt = $db->prepare("
                    INSERT INTO pages (title, slug, content, is_active, show_in_menu, show_in_footer, sort_order, created_at)
                    VALUES (?, ?, ?, 0, 0, 0, ?, NOW())
                ");
                $stmt->execute([$newTitle, $newSlug, $page['content'], $page['sort_order']]);
                
                setFlash('success', 'Sayfa kopyalandı. Düzenleyebilirsiniz.');
                break;
        }
    } catch (Exception $e) {
        setFlash('error', $e->getMessage());
    }
    
    redirect(SITE_URL . '/admin/sayfalar.php');
    exit;
}

// Slug oluşturma fonksiyonu
function createSlug($text) {
    $text = mb_strtolower($text, 'UTF-8');
    $text = str_replace(['ı', 'ğ', 'ü', 'ş', 'ö', 'ç'], ['i', 'g', 'u', 's', 'o', 'c'], $text);
    $text = preg_replace('/[^a-z0-9\-]/', '-', $text);
    $text = preg_replace('/-+/', '-', $text);
    $text = trim($text, '-');
    return $text;
}

// Sayfaları çek
try {
    $pages = $db->query("SELECT * FROM pages ORDER BY sort_order ASC, id ASC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $pages = [];
}

// İstatistikler
$stats = [
    'total' => count($pages),
    'active' => count(array_filter($pages, fn($p) => $p['is_active'] == 1)),
    'in_menu' => count(array_filter($pages, fn($p) => $p['show_in_menu'] == 1)),
    'in_footer' => count(array_filter($pages, fn($p) => $p['show_in_footer'] == 1))
];

// Düzenleme modu
$editPage = null;
if (isset($_GET['edit']) && (int)$_GET['edit'] > 0) {
    $editId = (int)$_GET['edit'];
    foreach ($pages as $p) {
        if ($p['id'] == $editId) {
            $editPage = $p;
            break;
        }
    }
}

$adminPageTitle = 'Sayfalar';
require_once __DIR__ . '/header.php';
?>

<style>
/* Header */
.page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 25px;
    flex-wrap: wrap;
    gap: 15px;
}

.page-header h2 {
    font-size: 18px;
    font-weight: 700;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.page-header h2 i {
    color: var(--primary);
}

/* Stats */
.stats-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
    gap: 15px;
    margin-bottom: 25px;
}

.stat-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 20px;
    text-align: center;
}

.stat-card .value {
    font-size: 32px;
    font-weight: 800;
    margin-bottom: 5px;
}

.stat-card .label {
    font-size: 13px;
    color: var(--text-secondary);
}

/* Layout */
.pages-layout {
    display: grid;
    grid-template-columns: 350px 1fr;
    gap: 20px;
}

/* Pages List */
.pages-list-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
    height: fit-content;
}

.pages-list-header {
    padding: 20px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.pages-list-header h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.pages-list-header h3 i {
    color: var(--primary);
}

.pages-list {
    max-height: 600px;
    overflow-y: auto;
}

.page-item {
    padding: 15px 20px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    gap: 15px;
    cursor: pointer;
    transition: all 0.2s;
}

.page-item:last-child {
    border-bottom: none;
}

.page-item:hover {
    background: var(--bg-hover);
}

.page-item.active {
    background: rgba(var(--primary-rgb), 0.1);
    border-left: 3px solid var(--primary);
}

.page-icon {
    width: 42px;
    height: 42px;
    background: var(--gradient);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #fff;
    flex-shrink: 0;
}

.page-icon.inactive {
    background: var(--bg-hover);
    color: var(--text-secondary);
}

.page-info {
    flex: 1;
    min-width: 0;
}

.page-title {
    font-size: 14px;
    font-weight: 600;
    margin: 0 0 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.page-meta {
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 11px;
    color: var(--text-secondary);
}

.page-meta span {
    display: flex;
    align-items: center;
    gap: 4px;
}

.page-badges {
    display: flex;
    gap: 5px;
    flex-shrink: 0;
}

.page-badge {
    width: 24px;
    height: 24px;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
}

.page-badge.active {
    background: rgba(16, 185, 129, 0.15);
    color: #10b981;
}

.page-badge.inactive {
    background: rgba(107, 114, 128, 0.15);
    color: #6b7280;
}

.page-badge.menu {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

.page-badge.footer {
    background: rgba(139, 92, 246, 0.15);
    color: #8b5cf6;
}

/* Editor Card */
.editor-card {
    background: var(--bg-card);
    border: 1px solid var(--border-color);
    border-radius: 16px;
    overflow: hidden;
}

.editor-header {
    padding: 20px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.editor-header h3 {
    font-size: 16px;
    font-weight: 600;
    margin: 0;
    display: flex;
    align-items: center;
    gap: 8px;
}

.editor-header h3 i {
    color: var(--primary);
}

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

.editor-body {
    padding: 20px;
}

.form-group {
    margin-bottom: 20px;
}

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

.form-row-3 {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
}

.form-label {
    display: block;
    font-weight: 500;
    margin-bottom: 8px;
    font-size: 14px;
}

.form-label .required {
    color: #ef4444;
}

.form-control {
    width: 100%;
    padding: 12px 15px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    color: var(--text-primary);
    font-size: 14px;
    transition: all 0.2s;
}

.form-control:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
    outline: none;
}

.form-control::placeholder {
    color: var(--text-secondary);
}

.form-hint {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 6px;
}

/* Content Editor */
.content-editor {
    min-height: 400px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    overflow: hidden;
}

.editor-toolbar {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
    padding: 10px;
    background: var(--bg-hover);
    border-bottom: 1px solid var(--border-color);
}

.editor-btn {
    width: 36px;
    height: 36px;
    background: var(--bg-dark);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    color: var(--text-secondary);
    font-size: 14px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.editor-btn:hover {
    background: var(--primary);
    border-color: var(--primary);
    color: #fff;
}

.editor-btn.active {
    background: var(--primary);
    border-color: var(--primary);
    color: #fff;
}

.editor-divider {
    width: 1px;
    height: 36px;
    background: var(--border-color);
    margin: 0 5px;
}

.editor-textarea {
    width: 100%;
    min-height: 350px;
    padding: 15px;
    background: transparent;
    border: none;
    color: var(--text-primary);
    font-size: 14px;
    font-family: inherit;
    line-height: 1.6;
    resize: vertical;
}

.editor-textarea:focus {
    outline: none;
}

/* Checkboxes */
.checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.form-check {
    display: flex;
    align-items: center;
    gap: 10px;
}

.form-check input[type="checkbox"] {
    width: 20px;
    height: 20px;
    accent-color: var(--primary);
    cursor: pointer;
}

.form-check label {
    font-size: 14px;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 6px;
}

/* Preview */
.preview-box {
    background: var(--bg-hover);
    border: 1px solid var(--border-color);
    border-radius: 10px;
    padding: 20px;
    margin-top: 20px;
}

.preview-box h4 {
    font-size: 14px;
    font-weight: 600;
    margin: 0 0 15px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: var(--text-secondary);
}

.preview-link {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px 15px;
    background: var(--bg-dark);
    border-radius: 8px;
    font-size: 13px;
    color: var(--primary);
    word-break: break-all;
}

.preview-link i {
    flex-shrink: 0;
}

/* Empty State */
.empty-editor {
    text-align: center;
    padding: 80px 30px;
}

.empty-editor i {
    font-size: 60px;
    color: var(--primary);
    opacity: 0.3;
    margin-bottom: 20px;
}

.empty-editor h3 {
    font-size: 18px;
    margin-bottom: 10px;
}

.empty-editor p {
    color: var(--text-secondary);
    font-size: 14px;
}

/* Page Actions */
.page-actions-dropdown {
    position: relative;
}

.page-actions-btn {
    width: 32px;
    height: 32px;
    background: var(--bg-hover);
    border: none;
    border-radius: 8px;
    color: var(--text-secondary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.page-actions-btn:hover {
    background: var(--primary);
    color: #fff;
}

/* Quick Edit Buttons */
.quick-actions {
    display: flex;
    gap: 8px;
    margin-top: 15px;
    padding-top: 15px;
    border-top: 1px solid var(--border-color);
}

.quick-btn {
    flex: 1;
    padding: 10px;
    border: none;
    border-radius: 8px;
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    transition: all 0.2s;
}

.quick-btn.view {
    background: rgba(59, 130, 246, 0.15);
    color: #3b82f6;
}

.quick-btn.duplicate {
    background: rgba(139, 92, 246, 0.15);
    color: #8b5cf6;
}

.quick-btn.delete {
    background: rgba(239, 68, 68, 0.15);
    color: #ef4444;
}

.quick-btn:hover {
    transform: translateY(-2px);
}

/* Responsive */
@media (max-width: 1200px) {
    .pages-layout {
        grid-template-columns: 300px 1fr;
    }
}

@media (max-width: 992px) {
    .pages-layout {
        grid-template-columns: 1fr;
    }
    
    .pages-list {
        max-height: 300px;
    }
}

@media (max-width: 768px) {
    .form-row, .form-row-3 {
        grid-template-columns: 1fr;
    }
    
    .checkbox-group {
        flex-direction: column;
        gap: 12px;
    }
    
    .editor-toolbar {
        overflow-x: auto;
        flex-wrap: nowrap;
    }
}
</style>

<div class="page-header">
    <h2><i class="fas fa-file-alt"></i> Sayfalar</h2>
    <a href="?new=1" class="btn-primary-custom">
        <i class="fas fa-plus"></i> Yeni Sayfa
    </a>
</div>

<!-- Stats -->
<div class="stats-row">
    <div class="stat-card">
        <div class="value" style="color: var(--primary)"><?php echo $stats['total']; ?></div>
        <div class="label">Toplam Sayfa</div>
    </div>
    <div class="stat-card">
        <div class="value" style="color: #10b981"><?php echo $stats['active']; ?></div>
        <div class="label">Aktif Sayfa</div>
    </div>
    <div class="stat-card">
        <div class="value" style="color: #3b82f6"><?php echo $stats['in_menu']; ?></div>
        <div class="label">Menüde</div>
    </div>
    <div class="stat-card">
        <div class="value" style="color: #8b5cf6"><?php echo $stats['in_footer']; ?></div>
        <div class="label">Footer'da</div>
    </div>
</div>

<div class="pages-layout">
    <!-- Pages List -->
    <div class="pages-list-card">
        <div class="pages-list-header">
            <h3><i class="fas fa-list"></i> Sayfa Listesi</h3>
            <span style="font-size: 12px; color: var(--text-secondary)"><?php echo count($pages); ?> sayfa</span>
        </div>
        
        <div class="pages-list">
            <?php if (empty($pages)): ?>
            <div style="padding: 40px 20px; text-align: center; color: var(--text-secondary);">
                <i class="fas fa-file-alt" style="font-size: 32px; opacity: 0.3; margin-bottom: 10px; display: block;"></i>
                <p>Henüz sayfa yok</p>
            </div>
            <?php else: ?>
            <?php foreach ($pages as $page): ?>
            <div class="page-item <?php echo ($editPage && $editPage['id'] == $page['id']) ? 'active' : ''; ?>" 
                 onclick="window.location='?edit=<?php echo $page['id']; ?>'">
                <div class="page-icon <?php echo !$page['is_active'] ? 'inactive' : ''; ?>">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="page-info">
                    <h4 class="page-title"><?php echo clean($page['title']); ?></h4>
                    <div class="page-meta">
                        <span><i class="fas fa-link"></i> /<?php echo clean($page['slug']); ?></span>
                    </div>
                </div>
                <div class="page-badges">
                    <span class="page-badge <?php echo $page['is_active'] ? 'active' : 'inactive'; ?>" title="<?php echo $page['is_active'] ? 'Aktif' : 'Pasif'; ?>">
                        <i class="fas fa-<?php echo $page['is_active'] ? 'check' : 'times'; ?>"></i>
                    </span>
                    <?php if ($page['show_in_menu']): ?>
                    <span class="page-badge menu" title="Menüde gösteriliyor">
                        <i class="fas fa-bars"></i>
                    </span>
                    <?php endif; ?>
                    <?php if ($page['show_in_footer']): ?>
                    <span class="page-badge footer" title="Footer'da gösteriliyor">
                        <i class="fas fa-shoe-prints"></i>
                    </span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
    
    <!-- Editor -->
    <div class="editor-card">
        <?php if ($editPage || isset($_GET['new'])): ?>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
            <input type="hidden" name="action" value="<?php echo $editPage ? 'update_page' : 'add_page'; ?>">
            <?php if ($editPage): ?>
            <input type="hidden" name="page_id" value="<?php echo $editPage['id']; ?>">
            <?php endif; ?>
            
            <div class="editor-header">
                <h3>
                    <i class="fas fa-<?php echo $editPage ? 'edit' : 'plus'; ?>"></i>
                    <?php echo $editPage ? 'Sayfa Düzenle' : 'Yeni Sayfa'; ?>
                </h3>
                <div class="editor-actions">
                    <a href="<?php echo SITE_URL; ?>/admin/sayfalar.php" class="btn-secondary-custom">
                        <i class="fas fa-times"></i> İptal
                    </a>
                    <button type="submit" class="btn-primary-custom">
                        <i class="fas fa-save"></i> <?php echo $editPage ? 'Güncelle' : 'Kaydet'; ?>
                    </button>
                </div>
            </div>
            
            <div class="editor-body">
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Sayfa Başlığı <span class="required">*</span></label>
                        <input type="text" name="title" id="pageTitle" class="form-control" 
                               value="<?php echo $editPage ? clean($editPage['title']) : ''; ?>" 
                               placeholder="Örn: Hakkımızda" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">URL (Slug)</label>
                        <input type="text" name="slug" id="pageSlug" class="form-control" 
                               value="<?php echo $editPage ? clean($editPage['slug']) : ''; ?>" 
                               placeholder="hakkimizda">
                        <div class="form-hint">Boş bırakırsanız otomatik oluşturulur</div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Sayfa İçeriği</label>
                    <div class="content-editor">
                        <div class="editor-toolbar">
                            <button type="button" class="editor-btn" onclick="insertTag('h2')" title="Başlık 2">
                                <i class="fas fa-heading"></i>
                            </button>
                            <button type="button" class="editor-btn" onclick="insertTag('h3')" title="Başlık 3">
                                <b>H3</b>
                            </button>
                            <button type="button" class="editor-btn" onclick="insertTag('p')" title="Paragraf">
                                <i class="fas fa-paragraph"></i>
                            </button>
                            <div class="editor-divider"></div>
                            <button type="button" class="editor-btn" onclick="insertTag('strong')" title="Kalın">
                                <i class="fas fa-bold"></i>
                            </button>
                            <button type="button" class="editor-btn" onclick="insertTag('em')" title="İtalik">
                                <i class="fas fa-italic"></i>
                            </button>
                            <button type="button" class="editor-btn" onclick="insertTag('u')" title="Altı Çizili">
                                <i class="fas fa-underline"></i>
                            </button>
                            <div class="editor-divider"></div>
                            <button type="button" class="editor-btn" onclick="insertTag('ul')" title="Liste">
                                <i class="fas fa-list-ul"></i>
                            </button>
                            <button type="button" class="editor-btn" onclick="insertTag('ol')" title="Numaralı Liste">
                                <i class="fas fa-list-ol"></i>
                            </button>
                            <div class="editor-divider"></div>
                            <button type="button" class="editor-btn" onclick="insertLink()" title="Link">
                                <i class="fas fa-link"></i>
                            </button>
                            <button type="button" class="editor-btn" onclick="insertImage()" title="Resim">
                                <i class="fas fa-image"></i>
                            </button>
                            <div class="editor-divider"></div>
                            <button type="button" class="editor-btn" onclick="insertTag('blockquote')" title="Alıntı">
                                <i class="fas fa-quote-right"></i>
                            </button>
                            <button type="button" class="editor-btn" onclick="insertHr()" title="Yatay Çizgi">
                                <i class="fas fa-minus"></i>
                            </button>
                        </div>
                        <textarea name="content" id="pageContent" class="editor-textarea" 
                                  placeholder="Sayfa içeriğini buraya yazın... HTML kullanabilirsiniz."><?php echo $editPage ? $editPage['content'] : ''; ?></textarea>
                    </div>
                </div>
                
                <div class="form-row-3">
                    <div class="form-group">
                        <label class="form-label">Sıralama</label>
                        <input type="number" name="sort_order" class="form-control" 
                               value="<?php echo $editPage ? $editPage['sort_order'] : 0; ?>" min="0">
                        <div class="form-hint">Küçük değerler önce</div>
                    </div>
                    <div class="form-group" style="grid-column: span 2;">
                        <label class="form-label">Görünürlük Ayarları</label>
                        <div class="checkbox-group" style="margin-top: 8px;">
                            <div class="form-check">
                                <input type="checkbox" name="is_active" id="isActive" 
                                       <?php echo (!$editPage || $editPage['is_active']) ? 'checked' : ''; ?>>
                                <label for="isActive"><i class="fas fa-eye"></i> Aktif</label>
                            </div>
                            <div class="form-check">
                                <input type="checkbox" name="show_in_menu" id="showInMenu"
                                       <?php echo ($editPage && $editPage['show_in_menu']) ? 'checked' : ''; ?>>
                                <label for="showInMenu"><i class="fas fa-bars"></i> Menüde Göster</label>
                            </div>
                            <div class="form-check">
                                <input type="checkbox" name="show_in_footer" id="showInFooter"
                                       <?php echo ($editPage && $editPage['show_in_footer']) ? 'checked' : ''; ?>>
                                <label for="showInFooter"><i class="fas fa-shoe-prints"></i> Footer'da Göster</label>
                            </div>
                        </div>
                    </div>
                </div>
                
                <?php if ($editPage): ?>
                <div class="preview-box">
                    <h4><i class="fas fa-external-link-alt"></i> Sayfa Önizleme</h4>
                    <a href="<?php echo SITE_URL; ?>/sayfa/<?php echo clean($editPage['slug']); ?>" 
                       class="preview-link" target="_blank">
                        <i class="fas fa-link"></i>
                        <?php echo SITE_URL; ?>/sayfa/<?php echo clean($editPage['slug']); ?>
                    </a>
                    
                    <div class="quick-actions">
                        <a href="<?php echo SITE_URL; ?>/sayfa/<?php echo clean($editPage['slug']); ?>" 
                           class="quick-btn view" target="_blank">
                            <i class="fas fa-eye"></i> Görüntüle
                        </a>
                        <button type="button" class="quick-btn duplicate" onclick="duplicatePage(<?php echo $editPage['id']; ?>)">
                            <i class="fas fa-copy"></i> Kopyala
                        </button>
                        <button type="button" class="quick-btn delete" onclick="deletePage(<?php echo $editPage['id']; ?>, '<?php echo clean($editPage['title']); ?>')">
                            <i class="fas fa-trash"></i> Sil
                        </button>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </form>
        <?php else: ?>
        <div class="empty-editor">
            <i class="fas fa-mouse-pointer"></i>
            <h3>Bir sayfa seçin</h3>
            <p>Düzenlemek için soldaki listeden bir sayfa seçin veya yeni sayfa oluşturun.</p>
            <a href="?new=1" class="btn-primary-custom" style="margin-top: 20px;">
                <i class="fas fa-plus"></i> Yeni Sayfa Oluştur
            </a>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
var csrfToken = '<?php echo $csrfToken; ?>';

// Başlıktan otomatik slug oluştur
document.getElementById('pageTitle')?.addEventListener('input', function() {
    var slugInput = document.getElementById('pageSlug');
    if (slugInput && !slugInput.dataset.manual) {
        var slug = this.value
            .toLowerCase()
            .replace(/ı/g, 'i')
            .replace(/ğ/g, 'g')
            .replace(/ü/g, 'u')
            .replace(/ş/g, 's')
            .replace(/ö/g, 'o')
            .replace(/ç/g, 'c')
            .replace(/[^a-z0-9\-]/g, '-')
            .replace(/-+/g, '-')
            .replace(/^-|-$/g, '');
        slugInput.value = slug;
    }
});

// Manuel slug değişikliği işaretle
document.getElementById('pageSlug')?.addEventListener('input', function() {
    this.dataset.manual = 'true';
});

// HTML Tag ekle
function insertTag(tag) {
    var textarea = document.getElementById('pageContent');
    var start = textarea.selectionStart;
    var end = textarea.selectionEnd;
    var selectedText = textarea.value.substring(start, end);
    var before = textarea.value.substring(0, start);
    var after = textarea.value.substring(end);
    
    var newText = '';
    
    if (tag === 'ul' || tag === 'ol') {
        if (selectedText) {
            var lines = selectedText.split('\n');
            var items = lines.map(function(line) { return '  <li>' + line + '</li>'; }).join('\n');
            newText = '<' + tag + '>\n' + items + '\n</' + tag + '>';
        } else {
            newText = '<' + tag + '>\n  <li></li>\n</' + tag + '>';
        }
    } else {
        newText = '<' + tag + '>' + selectedText + '</' + tag + '>';
    }
    
    textarea.value = before + newText + after;
    textarea.focus();
    textarea.selectionStart = textarea.selectionEnd = start + newText.length;
}

// Link ekle
function insertLink() {
    var url = prompt('Link URL:', 'https://');
    if (url) {
        var textarea = document.getElementById('pageContent');
        var start = textarea.selectionStart;
        var end = textarea.selectionEnd;
        var selectedText = textarea.value.substring(start, end) || 'Link metni';
        var before = textarea.value.substring(0, start);
        var after = textarea.value.substring(end);
        
        var newText = '<a href="' + url + '">' + selectedText + '</a>';
        textarea.value = before + newText + after;
        textarea.focus();
    }
}

// Resim ekle
function insertImage() {
    var url = prompt('Resim URL:', 'https://');
    if (url) {
        var alt = prompt('Alternatif metin:', '');
        var textarea = document.getElementById('pageContent');
        var start = textarea.selectionStart;
        var before = textarea.value.substring(0, start);
        var after = textarea.value.substring(start);
        
        var newText = '<img src="' + url + '" alt="' + (alt || '') + '">';
        textarea.value = before + newText + after;
        textarea.focus();
    }
}

// Yatay çizgi ekle
function insertHr() {
    var textarea = document.getElementById('pageContent');
    var start = textarea.selectionStart;
    var before = textarea.value.substring(0, start);
    var after = textarea.value.substring(start);
    
    var newText = '\n<hr>\n';
    textarea.value = before + newText + after;
    textarea.focus();
}

// Sayfa kopyala
function duplicatePage(pageId) {
    Swal.fire({
        title: 'Sayfayı Kopyala',
        text: 'Bu sayfanın bir kopyası oluşturulacak.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#8b5cf6',
        cancelButtonColor: '#64748b',
        confirmButtonText: '<i class="fas fa-copy me-1"></i> Kopyala',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="duplicate_page">' +
                '<input type="hidden" name="page_id" value="' + pageId + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}

// Sayfa sil
function deletePage(pageId, pageTitle) {
    Swal.fire({
        title: 'Sayfayı Sil',
        html: '<strong>' + pageTitle + '</strong> silinecek.<br><small class="text-muted">Bu işlem geri alınamaz!</small>',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#ef4444',
        cancelButtonColor: '#64748b',
        confirmButtonText: '<i class="fas fa-trash me-1"></i> Evet, Sil',
        cancelButtonText: 'İptal',
        background: '#1e293b',
        color: '#f8fafc'
    }).then(function(result) {
        if (result.isConfirmed) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = '<input type="hidden" name="csrf_token" value="' + csrfToken + '">' +
                '<input type="hidden" name="action" value="delete_page">' +
                '<input type="hidden" name="page_id" value="' + pageId + '">';
            document.body.appendChild(form);
            form.submit();
        }
    });
}
</script>

<?php require_once __DIR__ . '/footer.php'; ?>