<?php
$section = db_find('sections', get_int('id'));
if (!$section || !section_type($section['type'])) {
    flash('Bölüm bulunamadı.', 'error');
    go(admin_url('tema?panel=bolumler'));
}

$type = section_type($section['type']);
$settings = section_settings($section);

if (is_post()) {
    csrf_check();

    // Canlı önizleme: kaydetmeden taslağa yazar, bölümün yeni HTML'ini döner.
    if (post('action') === 'preview') {
        section_draft_set($section['id'], section_clean($section['type'], (array) post('s', [])));
        reply(true, '', ['html' => section_html(db_find('sections', $section['id']))]);
    }
    if (post('action') === 'discard') {
        section_draft_set($section['id'], null);
        reply(true, 'Değişiklikler geri alındı.', ['redirect' => admin_url('bolum?id=' . $section['id'] . '&embed=1&geri=1')]);
    }

    $input = (array) post('s', []);
    $error = null;
    $images = section_apply_uploads($input, $error);
    $clean = section_clean($section['type'], $input);
    section_draft_set($section['id'], null);
    db_update('sections', ['settings' => json_encode($clean, JSON_UNESCAPED_UNICODE), 'status' => checked('status')], $section['id']);
    log_action('Bölümü düzenledi', $type['label']);
    if ($error) {
        reply(false, 'Kaydedildi, ancak bir görsel yüklenemedi: ' . $error, ['images' => $images]);
    }
    reply(true, 'Bölüm kaydedildi.', ['images' => $images]);
}

// Bölümler özelleştiricinin içinde düzenlenir; bu sayfa orada gömülü form olarak açılır.
if (!get('embed')) {
    go(admin_url('tema?bolum=' . $section['id']));
}
?>
<!doctype html>
<html lang="tr">
<head>
    <?php tailwind_head() ?>
    <title><?= e($type['label']) ?></title>
</head>
<body class="bg-white font-sans text-zinc-900 antialiased">

<form method="post" action="<?= admin_url('bolum?id=' . $section['id'] . '&embed=1') ?>" enctype="multipart/form-data" data-section="<?= $section['id'] ?>" class="pb-24">
    <?= csrf_field() ?>

    <div class="space-y-5 p-5">
        <p class="flex items-start gap-3 rounded-xl bg-zinc-50 p-3 text-xs leading-5 text-zinc-500">
            <span class="flex size-8 shrink-0 items-center justify-center rounded-lg bg-white text-zinc-600 ring-1 ring-zinc-200"><?= icon($type['icon'], 'size-4') ?></span>
            <?= e($type['text']) ?>
        </p>
        <?php foreach ($type['fields'] as $field): ?>
            <?php admin_field($field, $settings[$field[0]] ?? '', 's[' . $field[0] . ']', $field[0]) ?>
        <?php endforeach ?>

        <details class="group/box rounded-xl border border-zinc-200">
            <summary class="flex cursor-pointer list-none items-center justify-between px-4 py-3 text-sm font-semibold">
                Görünüm ayarları
                <?= icon('down', 'size-4 text-zinc-400 transition group-open/box:rotate-180', '2') ?>
            </summary>
            <div class="space-y-5 border-t border-zinc-100 p-4">
                <?php foreach (section_common_fields() as $field): ?>
                    <?php admin_field($field, $settings[$field[0]] ?? '', 's[' . $field[0] . ']', $field[0]) ?>
                <?php endforeach ?>
            </div>
        </details>
    </div>

    <div class="fixed inset-x-0 bottom-0 z-10 border-t border-zinc-200 bg-white/95 px-4 py-3 backdrop-blur">
        <p data-draft-state class="mb-2 flex items-center justify-between gap-2 text-[11px] <?= section_draft($section['id']) !== null ? '' : 'hidden' ?>">
            <span class="flex items-center gap-1.5 font-medium text-amber-700"><span class="size-1.5 rounded-full bg-amber-500"></span>Önizlemede, henüz kaydedilmedi</span>
            <button name="action" value="discard" class="font-semibold text-zinc-500 underline hover:text-ink" formnovalidate>Vazgeç</button>
        </p>
        <div class="flex items-center gap-3">
            <label class="flex items-center gap-2 text-sm font-medium">
                <input type="checkbox" name="status" value="1" class="size-4 rounded accent-ink" <?= $section['status'] ? 'checked' : '' ?>> Yayında
            </label>
            <button class="btn-primary flex-1">Kaydet ve yayınla</button>
        </div>
    </div>
</form>

<div id="toasts" class="pointer-events-none fixed inset-x-0 bottom-20 z-[60] flex flex-col items-center gap-2 px-4"></div>
<?php include PARTS . '/admin-script.php' ?>
<script>
(() => {
    const { post } = window.admin;
    const form = document.querySelector('form[data-section]');
    const id = form.dataset.section;
    const state = document.querySelector('[data-draft-state]');
    let timer;

    // Yazdıkça taslak gönderilir, özelleştirici önizlemedeki bölümü yerinde değiştirir.
    const preview = () => {
        clearTimeout(timer);
        timer = setTimeout(async () => {
            const data = new FormData(form);
            data.set('action', 'preview');
            [...form.querySelectorAll('input[type=file]')].forEach(input => data.delete(input.name));
            const json = await post(form.action, data);
            if (!json.ok) return;
            state.classList.remove('hidden');
            window.parent.postMessage({ type: 'section-preview', id, html: json.html }, location.origin);
        }, 300);
    };

    form.addEventListener('input', event => { if (event.target.type !== 'file') preview(); });
    form.addEventListener('change', event => { if (event.target.type !== 'file') preview(); });
    // Satır ekleme, silme ve sıralama da önizlemeye yansır
    form.addEventListener('click', event => {
        if (event.target.closest('[data-repeater-add], [data-row-remove], [data-row-up], [data-row-down], [data-image-clear]')) setTimeout(preview, 50);
    });

    // Kaydedince taslak uyarısı kalkar
    form.addEventListener('submit', event => {
        if (!event.submitter || event.submitter.value !== 'discard') setTimeout(() => state.classList.add('hidden'), 400);
    });

    // Vazgeçildiyse önizleme kayıtlı hâle döner
    if (new URLSearchParams(location.search).has('geri')) {
        window.parent.postMessage({ type: 'customize-saved', section: id }, location.origin);
    }

    // Ctrl+S ile kaydet
    document.addEventListener('keydown', event => {
        if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
            event.preventDefault();
            form.requestSubmit();
        }
    });
})();
</script>
</body>
</html>
