<?php
$pages = section_pages() + ['contact' => 'İletişim sayfası (formun altı)'];
$page = array_key_exists(get('sayfa', 'home'), $pages) ? get('sayfa', 'home') : 'home';

if (is_post()) {
    csrf_check();
    $action = post('action');
    $section = db_find('sections', post_int('id'));

    if ($action === 'sort') {
        foreach (array_values((array) post('ids', [])) as $sort => $id) {
            db_query('UPDATE sections SET sort = ? WHERE id = ?', [$sort, (int) $id]);
        }
        log_action('Bölüm sırasını değiştirdi', $pages[$page] ?? $page);
        reply(true, 'Sıralama kaydedildi.');
    }
    if ($action === 'status' && $section) {
        db_update('sections', ['status' => post_int('value') ? 1 : 0], $section['id']);
        reply(true, post_int('value') ? 'Bölüm yayında.' : 'Bölüm gizlendi.');
    }
    if ($action === 'add' && section_type(post('type', ''))) {
        $id = section_add(post('page', $page), post('type'));
        log_action('Bölüm ekledi', section_type(post('type'))['label']);
        finish('Bölüm eklendi, ayarlarını düzenleyebilirsiniz.', admin_url('bolum?id=' . $id));
    }
    if ($action === 'duplicate' && $section) {
        $copy = $section;
        unset($copy['id']);
        $copy['sort'] = $section['sort'] + 1;
        db_query('UPDATE sections SET sort = sort + 1 WHERE page = ? AND sort > ?', [$section['page'], $section['sort']]);
        db_insert('sections', $copy);
        finish('Bölüm kopyalandı.', admin_url('duzen?sayfa=' . $section['page']));
    }
    if ($action === 'delete' && $section) {
        db_delete('sections', $section['id']);
        log_action('Bölüm sildi', section_label($section)[0]);
        finish('Bölüm silindi.', admin_url('duzen?sayfa=' . $section['page']));
    }
    reply(false, 'İşlem yapılamadı.');
}

// Bölümler özelleştiricinin içinde yönetilir; bu dosya sadece işlemleri (sıralama, ekleme, silme...) yapar.
go(admin_url('tema?panel=bolumler&sayfa=' . urlencode($page)));
