<?php
session_start();
// DİKKAT: Veritabanı bağlantı dosyanın yolu farklıysa burayı düzelt.
require_once 'system/db.php';

// Güvenlik: Login kontrolü (Kendi sistemine göre uyarla)
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) {
    // header("Location: login.php"); exit; 
    // Not: Asıl sitede login sistemin farklıysa burayı ona göre açmalısın.
}

$page = ['title'=>'', 'slug'=>'', 'status'=>'published', 'content_data'=>'[]'];
$id = 0;
$baslik = "Yeni Sayfa Oluştur";

if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $q = $db->query("SELECT * FROM pages WHERE id = $id")->fetch(PDO::FETCH_ASSOC);
    if ($q) {
        $page = $q;
        $baslik = "Sayfayı Düzenle: " . htmlspecialchars($page['title']);
        if(empty($page['content_data'])) $page['content_data'] = '[]';
    }
}

// Dosya Yükleme Fonksiyonu
function uploadFile($file, $prefix='img') {
    $target_dir = "assets/images/uploads/";
    // Klasör yoksa oluştur
    if (!file_exists($target_dir)) { mkdir($target_dir, 0777, true); }
    
    $ext = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
    $name = $prefix . "-" . uniqid() . "." . $ext;
    
    if(move_uploaded_file($file["tmp_name"], $target_dir . $name)) {
        return $name;
    }
    return "";
}

// KAYDETME İŞLEMİ
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $title = trim($_POST['title']);
    $slug = trim($_POST['slug']);
    if(empty($slug)) $slug = mb_strtolower(str_replace(' ', '-', $title));
    $status = $_POST['status'];
    
    $blocks = isset($_POST['blocks']) ? $_POST['blocks'] : [];
    $final_blocks = [];

    foreach ($blocks as $key => $block) {
        $clean_block = $block;
        // Slider Resimleri
        if(isset($_FILES['blocks']['name'][$key]['slides'])) {
            foreach($_FILES['blocks']['name'][$key]['slides'] as $slideKey => $val) {
                if($_FILES['blocks']['error'][$key]['slides'][$slideKey] == 0) {
                    $file_info = [
                        'name' => $_FILES['blocks']['name'][$key]['slides'][$slideKey],
                        'tmp_name' => $_FILES['blocks']['tmp_name'][$key]['slides'][$slideKey]
                    ];
                    $uploaded = uploadFile($file_info, 'slide');
                    $clean_block['slides'][$slideKey]['image'] = $uploaded ? $uploaded : ($block['slides'][$slideKey]['old_image'] ?? '');
                } else {
                    $clean_block['slides'][$slideKey]['image'] = $block['slides'][$slideKey]['old_image'] ?? '';
                }
            }
        }
        
        // Tekil Resimler
        if(isset($_FILES['blocks']['name'][$key]['image']) && $_FILES['blocks']['error'][$key]['image'] == 0) {
            $file_info = [
                'name' => $_FILES['blocks']['name'][$key]['image'],
                'tmp_name' => $_FILES['blocks']['tmp_name'][$key]['image']
            ];
            $uploaded = uploadFile($file_info, 'module');
            $clean_block['image'] = $uploaded ? $uploaded : ($block['old_image'] ?? '');
        } else {
            $clean_block['image'] = $block['old_image'] ?? '';
        }
        $final_blocks[] = $clean_block;
    }

    $json_data = json_encode(array_values($final_blocks), JSON_UNESCAPED_UNICODE);

    if ($id > 0) {
        $stmt = $db->prepare("UPDATE pages SET title=?, slug=?, content_data=?, status=? WHERE id=?");
        $stmt->execute([$title, $slug, $json_data, $status, $id]);
    } else {
        $stmt = $db->prepare("INSERT INTO pages (title, slug, content_data, status) VALUES (?, ?, ?, ?)");
        $stmt->execute([$title, $slug, $json_data, $status]);
        $id = $db->lastInsertId();
    }
    
    // Başarılı mesajı ile yönlendir
    header("Location: page-form.php?id=$id&success=1");
    exit;
}
?>

<!DOCTYPE html>
<html lang="tr" data-theme="light">
<?php include 'inc/header.php'; ?>

<link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.css" rel="stylesheet">

<style>
    /* --- 1. RENK VE STİL DÜZELTMELERİ (CSS RESET) --- */
    .note-editable { color: #333; }
    
    /* Inline stillerin (renk vb.) çalışması için inherit kuralı */
    .note-editable span[style], 
    .note-editable p[style], 
    .note-editable font[color] {
        color: inherit !important; 
    }
    .note-editable p { margin-bottom: 10px; color: inherit; }

    /* --- 2. KOD EKRANI (VS CODE / DARK THEME) --- */
    .note-editor.note-frame .note-editing-area .note-codable {
        background-color: #282c34 !important;
        color: #abb2bf !important;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace !important;
        font-size: 14px !important;
        line-height: 1.5 !important;
        padding: 15px !important;
    }

    /* --- 3. EDİTÖR İÇİ ELEMENTLER --- */
    .note-editable u { text-decoration: underline !important; }
    .note-editable i, .note-editable em { font-style: italic !important; }
    .note-editable ul { list-style: disc !important; padding-left: 30px !important; margin-bottom: 10px !important; }
    .note-editable ol { list-style: decimal !important; padding-left: 30px !important; margin-bottom: 10px !important; }
    .note-editable li { display: list-item !important; }

    /* Başlıklar */
    .note-editable h1 { font-size: 26px !important; margin: 10px 0; font-weight: bold; line-height: 1.2; color: inherit; }
    .note-editable h2 { font-size: 22px !important; margin: 10px 0; font-weight: bold; line-height: 1.2; color: inherit; }
    .note-editable h3 { font-size: 18px !important; margin: 8px 0; font-weight: bold; color: inherit; }
    
    /* Menüdeki Başlık Boyutları */
    .note-dropdown-menu h1 { font-size: 18px !important; margin: 0; }
    .note-dropdown-menu h2 { font-size: 16px !important; margin: 0; }
    .note-dropdown-menu h3 { font-size: 14px !important; margin: 0; }

    /* Renk Paleti Butonları */
    .note-color-palette .note-color-btn { width: 20px !important; height: 20px !important; border: 1px solid #e2e8f0; }
    .note-color-palette .note-color-btn:hover { border: 1px solid #000; transform: scale(1.2); }

    /* Tam Ekran */
    .note-fullscreen { position: fixed !important; top: 0; left: 0; width: 100% !important; height: 100% !important; z-index: 99999 !important; background: #fff; }

    /* --- 4. PANEL TASARIMI --- */
    .module-item { background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.03); overflow: visible; transition: all 0.3s ease; }
    .module-header { background: #f8fafc; padding: 12px 20px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; }
    .module-body { padding: 20px; }
    
    .ctrl-btn { width: 32px; height: 32px; display: inline-flex; align-items: center; justify-content: center; border-radius: 6px; border: 1px solid #d1d5db; background: white; color: #4b5563; cursor: pointer; transition: all 0.2s; }
    .ctrl-btn:hover { background: #f3f4f6; color: #111827; }
    .ctrl-btn.btn-del { border-color: #fee2e2; color: #ef4444; background: #fef2f2; }
    .ctrl-btn.btn-del:hover { background: #fee2e2; color: #dc2626; border-color: #fca5a5; }
    
    .btn-add-module { width: 100%; display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; background: white; border: 1px solid #e5e7eb; border-radius: 8px; color: #374151; font-weight: 500; transition: all 0.2s; text-align: left; }
    .btn-add-module:hover { background: #f9fafb; border-color: #d1d5db; transform: translateX(3px); }
    
    #builder-area { min-height: 400px; padding-bottom: 100px; }
    .preview-img { max-height: 80px; border-radius: 4px; border: 1px solid #e5e7eb; margin-top: 8px; display: block; }
    .inner-label { font-size: 0.75rem; text-transform: uppercase; font-weight: 700; color: #64748b; margin-bottom: 8px; display: flex; align-items: center; gap: 6px; }
</style>

<body>
    <?php include 'inc/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'inc/navbar.php'; ?>
        
        <div class="dashboard-main-body">
            
            <form action="" method="POST" enctype="multipart/form-data" id="pageForm">
                
                <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                    <h6 class="fw-semibold mb-0"><?php echo $baslik; ?></h6>
                    <div class="d-flex gap-2">
                        <a href="pages.php" class="btn btn-outline-secondary px-4 py-2 radius-8">İptal</a>
                        <button type="submit" class="btn btn-primary px-4 py-2 radius-8">Kaydet</button>
                    </div>
                </div>

                <?php if(isset($_GET['success'])): ?>
                    <div class="alert alert-success radius-8 mb-4">
                        <iconify-icon icon="solar:check-circle-bold" class="vertical-middle me-2"></iconify-icon>Sayfa başarıyla kaydedildi!
                    </div>
                <?php endif; ?>

                <div class="row gy-4">
                    
                    <div class="col-lg-3">
                        <div class="card p-3 radius-12 mb-4 border-0 shadow-sm">
                            <h6 class="fw-bold mb-3">Sayfa Ayarları</h6>
                            <div class="mb-3">
                                <label class="form-label text-sm">Başlık</label>
                                <input type="text" name="title" class="form-control" value="<?php echo htmlspecialchars($page['title']); ?>" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-sm">Slug</label>
                                <input type="text" name="slug" class="form-control" value="<?php echo htmlspecialchars($page['slug']); ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label text-sm">Durum</label>
                                <select name="status" class="form-control">
                                    <option value="published" <?php echo ($page['status']=='published')?'selected':''; ?>>Yayında</option>
                                    <option value="draft" <?php echo ($page['status']=='draft')?'selected':''; ?>>Taslak</option>
                                </select>
                            </div>
                        </div>

                        <div class="card p-3 radius-12 bg-white border-0 shadow-sm sticky-top" style="top: 100px; z-index: 10;">
                            <h6 class="fw-bold mb-3 text-primary">Modül Ekle</h6>
                            <div class="d-flex flex-column gap-2">
                                <button type="button" class="btn-add-module" data-type="slider">
                                    <span><iconify-icon icon="solar:gallery-wide-bold" class="text-primary vertical-middle me-2"></iconify-icon> Slider Banner</span>
                                    <iconify-icon icon="solar:add-circle-bold" class="text-success text-xl"></iconify-icon>
                                </button>
                                <button type="button" class="btn-add-module" data-type="text_full">
                                    <span><iconify-icon icon="solar:text-field-bold" class="text-secondary vertical-middle me-2"></iconify-icon> Tam Yazı</span>
                                    <iconify-icon icon="solar:add-circle-bold" class="text-success text-xl"></iconify-icon>
                                </button>
                                <button type="button" class="btn-add-module" data-type="text_2col">
                                    <span><iconify-icon icon="solar:columns-bold" class="text-info vertical-middle me-2"></iconify-icon> 2 Sütun Yazı</span>
                                    <iconify-icon icon="solar:add-circle-bold" class="text-success text-xl"></iconify-icon>
                                </button>
                                <button type="button" class="btn-add-module" data-type="img_text">
                                    <span><iconify-icon icon="solar:align-left-bold" class="text-warning vertical-middle me-2"></iconify-icon> Sol Resim / Sağ Yazı</span>
                                    <iconify-icon icon="solar:add-circle-bold" class="text-success text-xl"></iconify-icon>
                                </button>
                                <button type="button" class="btn-add-module" data-type="text_img">
                                    <span><iconify-icon icon="solar:align-right-bold" class="text-danger vertical-middle me-2"></iconify-icon> Sol Yazı / Sağ Resim</span>
                                    <iconify-icon icon="solar:add-circle-bold" class="text-success text-xl"></iconify-icon>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-9">
                        <div id="builder-area"></div>
                        <div id="empty-hint" class="text-center py-5 text-muted border-2 border-dashed radius-12 bg-light-50">
                            <iconify-icon icon="solar:inbox-line" class="text-4xl mb-2 text-secondary-light"></iconify-icon>
                            <div class="text-secondary">Soldaki butonlara tıklayarak modül ekleyin.</div>
                        </div>
                    </div>

                </div>
            </form>
        </div>
        <?php include 'inc/copyright.php'; ?>
    </main>
    <?php include 'inc/footer.php'; ?>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-lite.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/lang/summernote-tr-TR.min.js"></script>

    <script>
    function generateUUID() { 
        return 'mod_' + Math.random().toString(36).substr(2, 9); 
    }

    // HTML ŞABLONLARI
    function createModuleHTML(type, data = null) {
        var id = generateUUID();
        var html = '';
        var controls = `
            <div class="d-flex gap-2">
                <button type="button" class="ctrl-btn up-btn" title="Yukarı"><iconify-icon icon="solar:arrow-up-bold"></iconify-icon></button>
                <button type="button" class="ctrl-btn down-btn" title="Aşağı"><iconify-icon icon="solar:arrow-down-bold"></iconify-icon></button>
                <button type="button" class="ctrl-btn btn-del del-btn" title="Sil"><iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon></button>
            </div>`;

        if(type === 'slider') {
            html += `<div class="module-item" id="${id}"><input type="hidden" name="blocks[${id}][type]" value="slider"><div class="module-header"><span class="fw-bold text-primary d-flex align-items-center"><iconify-icon icon="solar:gallery-wide-bold" class="me-2"></iconify-icon> Slider Banner</span>${controls}</div><div class="module-body bg-light"><div class="row g-3">`;
            for(let i=0; i<3; i++) {
                let d = (data && data.slides && data.slides[i]) ? data.slides[i] : {};
                let img_preview = d.image ? `<img src="assets/images/uploads/${d.image}" class="preview-img">` : '';
                html += `<div class="col-md-4"><div class="card p-3 border h-100 shadow-sm"><div class="inner-label"><iconify-icon icon="solar:slider-minimalistic-horizontal-bold"></iconify-icon> Slayt ${i+1}</div><input type="text" name="blocks[${id}][slides][${i}][title]" class="form-control mb-2 form-control-sm" placeholder="Başlık" value="${d.title||''}"><input type="text" name="blocks[${id}][slides][${i}][link]" class="form-control mb-2 form-control-sm" placeholder="Link" value="${d.link||''}"><input type="file" name="blocks[${id}][slides][${i}]" class="form-control form-control-sm"><input type="hidden" name="blocks[${id}][slides][${i}][old_image]" value="${d.image||''}">${img_preview}</div></div>`;
            }
            html += `</div></div></div>`;
        }
        else if(type === 'text_full') {
            let val = data ? data.content : '';
            html = `<div class="module-item" id="${id}"><input type="hidden" name="blocks[${id}][type]" value="text_full"><div class="module-header"><span class="fw-bold text-secondary d-flex align-items-center"><iconify-icon icon="solar:text-field-bold" class="me-2"></iconify-icon> Tam Yazı</span>${controls}</div><div class="module-body"><div class="inner-label"><iconify-icon icon="solar:document-text-bold"></iconify-icon> İçerik</div><textarea name="blocks[${id}][content]" class="summernote">${val}</textarea></div></div>`;
        }
        else if(type === 'text_2col') {
            let c1 = data ? data.col1 : ''; let c2 = data ? data.col2 : '';
            html = `<div class="module-item" id="${id}"><input type="hidden" name="blocks[${id}][type]" value="text_2col"><div class="module-header"><span class="fw-bold text-info d-flex align-items-center"><iconify-icon icon="solar:columns-bold" class="me-2"></iconify-icon> 2 Sütun Yazı</span>${controls}</div><div class="module-body row"><div class="col-md-6"><div class="inner-label text-info"><iconify-icon icon="solar:align-left-bold"></iconify-icon> Sol Sütun</div><textarea name="blocks[${id}][col1]" class="summernote">${c1}</textarea></div><div class="col-md-6"><div class="inner-label text-info"><iconify-icon icon="solar:align-right-bold"></iconify-icon> Sağ Sütun</div><textarea name="blocks[${id}][col2]" class="summernote">${c2}</textarea></div></div></div>`;
        }
        else if(type === 'img_text' || type === 'text_img') {
            let img = data ? data.image : ''; let txt = data ? data.content : '';
            let isLeft = (type === 'img_text');
            let img_preview = img ? `<img src="assets/images/uploads/${img}" class="preview-img">` : '';
            let title = isLeft ? "Sol Resim - Sağ Yazı" : "Sol Yazı - Sağ Resim";
            let color = isLeft ? "text-warning" : "text-danger";
            let img_html = `<div class="col-md-4 text-center p-4 bg-light radius-8 border"><div class="inner-label justify-content-center"><iconify-icon icon="solar:image-bold"></iconify-icon> Görsel</div><input type="file" name="blocks[${id}][image]" class="form-control mb-2 form-control-sm"><input type="hidden" name="blocks[${id}][old_image]" value="${img}">${img_preview}</div>`;
            let txt_html = `<div class="col-md-8"><div class="inner-label"><iconify-icon icon="solar:text-bold"></iconify-icon> İçerik</div><textarea name="blocks[${id}][content]" class="summernote">${txt}</textarea></div>`;
            html = `<div class="module-item" id="${id}"><input type="hidden" name="blocks[${id}][type]" value="${type}"><div class="module-header"><span class="fw-bold ${color} d-flex align-items-center"><iconify-icon icon="solar:align-left-bold" class="me-2"></iconify-icon> ${title}</span>${controls}</div><div class="module-body row align-items-center">${isLeft ? img_html + txt_html : txt_html + img_html}</div></div>`;
        }
        return {html: html, id: id};
    }

    // SUMMERNOTE BAŞLATICI
    function initSummernote(selector) {
        $(selector).summernote({
            lang: 'tr-TR',
            height: 200,
            styleWithSpan: false, // RENK SORUNUNU ÇÖZEN AYAR BURASI (false olmalı)
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture']],
                ['view', ['fullscreen', 'codeview']]
            ],
            styleTags: [
                'p', 
                { title: 'Başlık 1', tag: 'h1', className: '', value: 'h1' },
                { title: 'Başlık 2', tag: 'h2', className: '', value: 'h2' },
                { title: 'Başlık 3', tag: 'h3', className: '', value: 'h3' },
            ],
            disableDragAndDrop: true
        });
    }

    $(document).ready(function() {
        
        $('.btn-add-module').on('click', function() {
            var type = $(this).data('type');
            $('#empty-hint').hide();
            
            var generated = createModuleHTML(type);
            $('#builder-area').append(generated.html);
            initSummernote('#'+generated.id+' .summernote');
            
            $('html, body').animate({ scrollTop: $('#'+generated.id).offset().top - 100 }, 500);
        });

        $(document).on('click', '.del-btn', function() {
            if(confirm('Silmek istediğinize emin misiniz?')) {
                $(this).closest('.module-item').remove();
                if($('#builder-area').children().length === 0) $('#empty-hint').show();
            }
        });

        $(document).on('click', '.up-btn', function() {
            var current = $(this).closest('.module-item');
            var prev = current.prev('.module-item');
            if (prev.length !== 0) {
                current.find('.summernote').summernote('destroy');
                current.insertBefore(prev);
                current.find('textarea.summernote').each(function() { initSummernote(this); });
            }
        });

        $(document).on('click', '.down-btn', function() {
            var current = $(this).closest('.module-item');
            var next = current.next('.module-item');
            if (next.length !== 0) {
                current.find('.summernote').summernote('destroy');
                current.insertAfter(next);
                current.find('textarea.summernote').each(function() { initSummernote(this); });
            }
        });

        var savedData = <?php echo !empty($page['content_data']) ? $page['content_data'] : '[]'; ?>;
        if(savedData && savedData.length > 0) {
            $('#empty-hint').hide();
            savedData.forEach(function(block) {
                var generated = createModuleHTML(block.type, block);
                $('#builder-area').append(generated.html);
                initSummernote('#'+generated.id+' .summernote');
            });
        }
    });
    </script>
</body>
</html>