<?php

// Sayfa oluşturucudaki bölüm tipleri. Her tipin görünümü inc/sections/{tip}.php dosyasındadır.
function section_types()
{
    $button = [
        ['button_text', 'Buton yazısı', 'text'],
        ['link', 'Buton bağlantısı', 'url'],
    ];

    return [
        'slider' => [
            'label' => 'Slider', 'icon' => 'slides', 'text' => 'Büyük, dönen kapak görselleri.',
            'fields' => [
                ['height', 'Yükseklik', 'select', ['md' => 'Orta', 'lg' => 'Büyük', 'xl' => 'Ekran boyu']],
                ['boxed', 'Kutulu görünüm (kenarlardan boşluklu)', 'toggle'],
                ['align', 'Metin hizası', 'select', ['left' => 'Sol', 'center' => 'Orta']],
                ['interval', 'Geçiş süresi (saniye)', 'number'],
                ['items', 'Slaytlar', 'items', [
                    ['image', 'Görsel', 'image'],
                    ['eyebrow', 'Üst yazı', 'text'],
                    ['title', 'Başlık', 'text'],
                    ['subtitle', 'Alt metin', 'textarea'],
                    ...$button,
                ]],
            ],
            'defaults' => ['height' => 'lg', 'boxed' => '1', 'align' => 'left', 'interval' => '6', 'padding' => 'sm', 'items' => [
                ['image' => '', 'eyebrow' => 'Yeni sezon', 'title' => 'Tarzını yansıtan ürünler', 'subtitle' => 'Özenle seçilmiş koleksiyonları keşfet.', 'button_text' => 'Alışverişe başla', 'link' => '/urunler'],
            ]],
        ],
        'categories' => [
            'label' => 'Kategori kartları', 'icon' => 'grid', 'text' => 'Görselli kategori kartları ya da kategori hapları.',
            'fields' => [
                ['title', 'Başlık', 'text'],
                ['source', 'Kategoriler', 'select', ['top' => 'Ana kategoriler', 'selected' => 'Seçtiklerim']],
                ['category_ids', 'Seçili kategoriler', 'categories'],
                ['style', 'Görünüm', 'select', ['cards' => 'Görselli kartlar', 'tiles' => 'Yatay kutular', 'pills' => 'Haplar']],
                ['columns', 'Sütun', 'select', ['3' => '3', '4' => '4', '6' => '6']],
                ['limit', 'En fazla', 'number'],
            ],
            'defaults' => ['title' => 'Kategoriler', 'source' => 'top', 'category_ids' => [], 'style' => 'cards', 'columns' => '4', 'limit' => '4'],
        ],
        'products' => [
            'label' => 'Ürün vitrini', 'icon' => 'cube', 'text' => 'Öne çıkan, yeni, indirimli ya da seçtiğin ürünler.',
            'fields' => [
                ['title', 'Başlık', 'text'],
                ['subtitle', 'Alt başlık', 'text'],
                ['source', 'Ürünler', 'select', ['featured' => 'Öne çıkanlar', 'latest' => 'Yeni gelenler', 'sale' => 'İndirimdekiler', 'bestsellers' => 'Çok satanlar', 'rating' => 'En yüksek puanlılar', 'category' => 'Bir kategoriden', 'manual' => 'Seçtiklerim']],
                ['category_id', 'Kategori', 'category'],
                ['product_ids', 'Seçili ürünler', 'products'],
                ['limit', 'Ürün sayısı', 'number'],
                ['layout', 'Düzen', 'select', ['grid' => 'Izgara', 'carousel' => 'Kaydırmalı', 'promo' => 'Kampanya kutusu']],
                ['promo_text', 'Kampanya kutusu metni', 'textarea'],
                ['show_link', '"Tümünü gör" bağlantısı', 'toggle'],
            ],
            'defaults' => ['title' => 'Öne çıkanlar', 'subtitle' => '', 'source' => 'featured', 'category_id' => '', 'product_ids' => [], 'limit' => '8', 'layout' => 'grid', 'promo_text' => '', 'show_link' => '1'],
        ],
        'banner' => [
            'label' => 'Banner', 'icon' => 'photo', 'text' => 'Tek, ikili ya da üçlü görselli tanıtım alanı.',
            'fields' => [
                ['columns', 'Yan yana', 'select', ['1' => '1', '2' => '2', '3' => '3']],
                ['height', 'Yükseklik', 'select', ['sm' => 'Kısa', 'md' => 'Orta', 'lg' => 'Uzun']],
                ['items', 'Bannerlar', 'items', [
                    ['image', 'Görsel', 'image'],
                    ['color', 'Görsel yoksa zemin rengi', 'color'],
                    ['dark_text', 'Koyu yazı (açık zeminler için)', 'toggle'],
                    ['eyebrow', 'Üst yazı', 'text'],
                    ['title', 'Başlık', 'text'],
                    ['text', 'Metin', 'textarea'],
                    ...$button,
                ]],
            ],
            'defaults' => ['columns' => '2', 'height' => 'md', 'items' => [
                ['image' => '', 'color' => '#18181b', 'dark_text' => '0', 'eyebrow' => 'Koleksiyon', 'title' => 'Yeni gelenler', 'text' => '', 'button_text' => 'İncele', 'link' => '/urunler'],
                ['image' => '', 'color' => '#e03d0b', 'dark_text' => '0', 'eyebrow' => 'Fırsat', 'title' => 'İndirimler', 'text' => '', 'button_text' => 'Keşfet', 'link' => '/urunler?indirim=1'],
            ]],
        ],
        'countdown' => [
            'label' => 'Kampanya sayacı', 'icon' => 'clock', 'text' => 'Bitiş tarihine geri sayan kampanya alanı.',
            'fields' => [
                ['eyebrow', 'Üst yazı', 'text'],
                ['title', 'Başlık', 'text'],
                ['text', 'Metin', 'textarea'],
                ['ends_at', 'Bitiş tarihi', 'datetime'],
                ['image', 'Arka plan görseli', 'image'],
                ['color', 'Zemin rengi', 'color'],
                ...$button,
            ],
            'defaults' => ['eyebrow' => 'Sınırlı süre', 'title' => 'Hafta sonu indirimi', 'text' => 'Seçili ürünlerde %30\'a varan indirim.', 'ends_at' => date('Y-m-d\TH:i', strtotime('+3 days')), 'image' => '', 'color' => '#0a0a0a', 'button_text' => 'Fırsatları gör', 'link' => '/urunler?indirim=1'],
        ],
        'features' => [
            'label' => 'Avantajlar şeridi', 'icon' => 'shield', 'text' => 'Kargo, iade, güvenli ödeme gibi avantajlar.',
            'fields' => [
                ['style', 'Görünüm', 'select', ['plain' => 'Sade', 'cards' => 'Kartlar']],
                ['items', 'Avantajlar', 'items', [
                    ['icon', 'İkon', 'icon'],
                    ['title', 'Başlık', 'text'],
                    ['text', 'Metin', 'text'],
                ]],
            ],
            'defaults' => ['style' => 'plain', 'bg' => '#fafafa', 'items' => [
                ['icon' => 'truck', 'title' => 'Hızlı teslimat', 'text' => '1-3 iş gününde kargoda'],
                ['icon' => 'shield', 'title' => 'Güvenli alışveriş', 'text' => 'Bilgileriniz her zaman güvende'],
                ['icon' => 'refresh', 'title' => 'Kolay iade', 'text' => '14 gün içinde ücretsiz iade'],
                ['icon' => 'chat', 'title' => 'Müşteri desteği', 'text' => 'Her zaman yanınızdayız'],
            ]],
        ],
        'reviews' => [
            'label' => 'Müşteri yorumları', 'icon' => 'chat', 'text' => 'Onaylı ve yüksek puanlı yorumlar.',
            'fields' => [
                ['eyebrow', 'Üst yazı', 'text'],
                ['title', 'Başlık', 'text'],
                ['limit', 'Yorum sayısı', 'number'],
            ],
            'defaults' => ['eyebrow' => 'Müşteri yorumları', 'title' => 'Onlar ne diyor?', 'limit' => '3'],
        ],
        'logos' => [
            'label' => 'Marka logoları', 'icon' => 'tag', 'text' => 'Çalıştığın markalar ya da basında biz.',
            'fields' => [
                ['title', 'Başlık', 'text'],
                ['grayscale', 'Gri tonlu göster', 'toggle'],
                ['items', 'Logolar', 'items', [
                    ['image', 'Logo', 'image'],
                    ['title', 'Marka adı', 'text'],
                    ['link', 'Bağlantı', 'url'],
                ]],
            ],
            'defaults' => ['title' => 'Markalarımız', 'grayscale' => '1', 'items' => []],
        ],
        'text' => [
            'label' => 'Metin bloğu', 'icon' => 'document', 'text' => 'Başlık, paragraf ve buton.',
            'fields' => [
                ['eyebrow', 'Üst yazı', 'text'],
                ['title', 'Başlık', 'text'],
                ['content', 'Metin', 'textarea'],
                ['align', 'Hiza', 'select', ['left' => 'Sol', 'center' => 'Orta']],
                ['size', 'Başlık boyutu', 'select', ['md' => 'Orta', 'lg' => 'Büyük', 'xl' => 'Çok büyük']],
                ...$button,
            ],
            'defaults' => ['eyebrow' => '', 'title' => 'Hikayemiz', 'content' => 'Kaliteli ürünleri sade bir alışveriş deneyimiyle buluşturuyoruz.', 'align' => 'center', 'size' => 'lg', 'button_text' => '', 'link' => ''],
        ],
        'image_text' => [
            'label' => 'Görsel + metin', 'icon' => 'photo', 'text' => 'Yan yana büyük görsel ve açıklama.',
            'fields' => [
                ['image', 'Görsel', 'image'],
                ['reverse', 'Görsel sağda', 'toggle'],
                ['eyebrow', 'Üst yazı', 'text'],
                ['title', 'Başlık', 'text'],
                ['content', 'Metin', 'textarea'],
                ...$button,
            ],
            'defaults' => ['image' => '', 'reverse' => '0', 'eyebrow' => 'Hakkımızda', 'title' => 'Özenle tasarlandı', 'content' => 'Her ürünü kalite, dayanıklılık ve sade tasarım ilkeleriyle seçiyoruz.', 'button_text' => 'Daha fazla', 'link' => '/sayfa/hakkimizda'],
        ],
        'newsletter' => [
            'label' => 'Bülten aboneliği', 'icon' => 'mail', 'text' => 'E-posta toplama formu.',
            'fields' => [
                ['title', 'Başlık', 'text'],
                ['text', 'Metin', 'textarea'],
                ['button_text', 'Buton yazısı', 'text'],
                ['dark', 'Koyu zemin', 'toggle'],
            ],
            'defaults' => ['title' => 'Kampanyalardan ilk sen haberdar ol', 'text' => 'Yeni ürünler ve size özel indirimler e-postanıza gelsin.', 'button_text' => 'Abone ol', 'dark' => '1'],
        ],
        'gallery' => [
            'label' => 'Görsel galeri', 'icon' => 'photo', 'text' => 'Instagram tarzı görsel ızgarası.',
            'fields' => [
                ['title', 'Başlık', 'text'],
                ['subtitle', 'Alt başlık', 'text'],
                ['columns', 'Sütun', 'select', ['3' => '3', '4' => '4', '6' => '6']],
                ['items', 'Görseller', 'items', [
                    ['image', 'Görsel', 'image'],
                    ['link', 'Bağlantı', 'url'],
                ]],
            ],
            'defaults' => ['title' => '@magazamiz', 'subtitle' => 'Bizi Instagram\'da takip edin', 'columns' => '6', 'items' => []],
        ],
        'faq' => [
            'label' => 'Sık sorulan sorular', 'icon' => 'chat', 'text' => 'Açılır kapanır soru-cevap listesi.',
            'fields' => [
                ['title', 'Başlık', 'text'],
                ['items', 'Sorular', 'items', [
                    ['question', 'Soru', 'text'],
                    ['answer', 'Cevap', 'textarea'],
                ]],
            ],
            'defaults' => ['title' => 'Sık sorulan sorular', 'items' => [
                ['question' => 'Kargom ne zaman gelir?', 'answer' => 'Siparişleriniz 1-3 iş günü içinde kargoya verilir.'],
                ['question' => 'İade nasıl yapılır?', 'answer' => 'Ürünü teslim aldıktan sonra 14 gün içinde iade edebilirsiniz.'],
            ]],
        ],
        'spacer' => [
            'label' => 'Boşluk / çizgi', 'icon' => 'minus', 'text' => 'Bölümler arasına boşluk ya da ayırıcı çizgi.',
            'fields' => [
                ['size', 'Yükseklik', 'select', ['sm' => 'Küçük', 'md' => 'Orta', 'lg' => 'Büyük']],
                ['line', 'Ayırıcı çizgi', 'toggle'],
            ],
            'defaults' => ['size' => 'md', 'line' => '0', 'padding' => 'none'],
        ],
        'html' => [
            'label' => 'Özel HTML', 'icon' => 'document', 'text' => 'Kendi HTML kodun (video, harita, form...).',
            'fields' => [
                ['code', 'HTML kodu', 'code'],
            ],
            'defaults' => ['code' => ''],
        ],
    ];
}

// Tüm bölümlerde ortak görünüm ayarları.
function section_common_fields()
{
    return [
        ['bg', 'Arka plan rengi', 'color'],
        ['padding', 'Dikey boşluk', 'select', ['none' => 'Yok', 'sm' => 'Az', 'md' => 'Normal', 'lg' => 'Çok']],
        ['width', 'Genişlik', 'select', ['container' => 'Sayfa genişliği', 'full' => 'Tam ekran']],
        ['hide_mobile', 'Mobilde gizle', 'toggle'],
    ];
}

function section_common_defaults()
{
    return ['bg' => '', 'padding' => 'md', 'width' => 'container', 'hide_mobile' => '0'];
}

// Yöneticinin kaydetmeden önizlediği bölüm ayarları (sadece kendi oturumunda görünür).
function section_draft($id)
{
    return is_admin() ? (sess('section_drafts')[$id] ?? null) : null;
}

function section_draft_set($id, $settings)
{
    $drafts = sess('section_drafts', []);
    if ($settings === null) {
        unset($drafts[$id]);
    } else {
        $drafts[$id] = $settings;
    }
    sess_set('section_drafts', $drafts);
}

// Tek bir bölümün HTML çıktısı (önizlemede yerinde değiştirmek için).
function section_html($section)
{
    ob_start();
    render_section($section);
    return ob_get_clean();
}

function section_type($type)
{
    return section_types()[$type] ?? null;
}

function section_settings($section)
{
    $type = section_type($section['type']);
    $saved = section_draft($section['id']) ?? (json_decode((string) $section['settings'], true) ?: []);
    $settings = array_merge(section_common_defaults(), $type['defaults'] ?? [], $saved);

    // Tekrarlı alanlarda (slayt, banner...) her satırın tüm anahtarları olsun.
    foreach ($type['fields'] ?? [] as $field) {
        if ($field[2] === 'items') {
            $blank = array_fill_keys(array_column($field[3], 0), '');
            $settings[$field[0]] = array_map(fn($row) => array_merge($blank, (array) $row), (array) ($settings[$field[0]] ?? []));
        } elseif (!array_key_exists($field[0], $settings)) {
            $settings[$field[0]] = in_array($field[2], ['categories', 'products'], true) ? [] : '';
        }
    }
    return $settings;
}

function sections_of($page, $only_active = true)
{
    return db_all('SELECT * FROM sections WHERE page = ?' . ($only_active ? ' AND status = 1' : '') . ' ORDER BY sort, id', [$page]);
}

function render_sections($page)
{
    foreach (sections_of($page) as $section) {
        render_section($section);
    }
}

function render_section($section)
{
    $type = section_type($section['type']);
    $file = INC . '/sections/' . $section['type'] . '.php';
    if (!$type || !is_file($file)) {
        return;
    }
    $s = section_settings($section);
    $padding = ['none' => '', 'sm' => 'py-6 sm:py-8', 'md' => 'py-12 sm:py-16', 'lg' => 'py-20 sm:py-28'][$s['padding']] ?? 'py-12 sm:py-16';
    $style = $s['bg'] ? 'background-color: ' . e(hex_color($s['bg'], '#ffffff')) . ';' : '';
    $full = $s['width'] === 'full';

    echo '<section id="bolum-' . (int) $section['id'] . '" data-section="' . e($section['type']) . '" data-customize-section="' . (int) $section['id'] . '" data-customize-label="' . e($type['label']) . '" class="' . $padding . ($s['hide_mobile'] === '1' ? ' max-sm:hidden' : '') . '" style="' . $style . '">';
    echo '<div class="' . ($full ? 'w-full' : 'container-x') . '">';
    include $file;
    echo '</div></section>';
}

function section_title_html($title, $subtitle = '', $link = null, $center = false)
{
    if (!$title && !$subtitle) {
        return '';
    }
    $html = '<div class="mb-8 flex flex-wrap items-end justify-between gap-4 ' . ($center ? 'justify-center text-center' : '') . '"><div>';
    if ($title) {
        $html .= '<h2 class="heading text-2xl ' . heading_weight_class() . ' sm:text-3xl">' . e($title) . '</h2>';
    }
    if ($subtitle) {
        $html .= '<p class="mt-2 text-zinc-500">' . e($subtitle) . '</p>';
    }
    $html .= '</div>';
    if ($link) {
        $html .= '<a href="' . e($link) . '" class="group inline-flex shrink-0 items-center gap-1.5 text-sm font-medium text-zinc-600 transition hover:text-ink">Tümünü gör' . icon('arrow', 'size-4 transition group-hover:translate-x-0.5', '2') . '</a>';
    }
    return $html . '</div>';
}

function section_link($link)
{
    $link = trim((string) $link);
    if ($link === '' || str_starts_with($link, 'http') || str_starts_with($link, '#') || str_starts_with($link, 'mailto:') || str_starts_with($link, 'tel:')) {
        return $link;
    }
    return url($link);
}

// Ürün vitrini bölümünün ürünlerini kaynağa göre getirir.
function section_products($s)
{
    $limit = max(1, min(24, (int) $s['limit']));
    $where = 'status = 1';
    $params = [];
    $order = 'id DESC';

    switch ($s['source']) {
        case 'featured':
            $where .= ' AND featured = 1';
            break;
        case 'sale':
            $where .= ' AND old_price > price';
            $order = '(old_price - price) / old_price DESC';
            break;
        case 'bestsellers':
            $order = 'sold DESC, id DESC';
            break;
        case 'rating':
            $where .= ' AND review_count > 0';
            $order = 'rating DESC, review_count DESC';
            break;
        case 'category':
            $ids = $s['category_id'] ? category_children_ids($s['category_id']) : [0];
            $where .= ' AND category_id IN (' . db_in($ids) . ')';
            $params = $ids;
            break;
        case 'manual':
            $ids = array_map('intval', (array) $s['product_ids']) ?: [0];
            $products = db_all("SELECT * FROM products WHERE $where AND id IN (" . db_in($ids) . ')', $ids);
            usort($products, fn($a, $b) => array_search((int) $a['id'], $ids, true) <=> array_search((int) $b['id'], $ids, true));
            return array_slice($products, 0, $limit);
    }

    return db_all("SELECT * FROM products WHERE $where ORDER BY $order LIMIT $limit", $params);
}

function section_products_link($s)
{
    return match ($s['source']) {
        'sale'        => url('urunler?indirim=1'),
        'bestsellers' => url('urunler?sirala=cok-satan'),
        'rating'      => url('urunler?sirala=puan'),
        'category'    => ($category = db_find('categories', (int) $s['category_id'])) ? category_url($category) : url('urunler'),
        default       => url('urunler'),
    };
}

function section_categories($s)
{
    if ($s['source'] === 'selected' && $s['category_ids']) {
        $ids = array_map('intval', (array) $s['category_ids']);
        $rows = db_all('SELECT * FROM categories WHERE status = 1 AND id IN (' . db_in($ids) . ')', $ids);
        usort($rows, fn($a, $b) => array_search((int) $a['id'], $ids, true) <=> array_search((int) $b['id'], $ids, true));
        return $rows;
    }
    return array_slice(menu_categories(), 0, max(1, (int) $s['limit'] ?: 4));
}

// Formdan gelen bölüm ayarlarını alan tiplerine göre temizler, görselleri yükler.
function section_clean($type, $input)
{
    $fields = array_merge(section_type($type)['fields'], section_common_fields());
    return section_clean_fields($fields, $input);
}

function section_clean_fields($fields, $input)
{
    $clean = [];
    foreach ($fields as $field) {
        [$key, , $kind] = $field;
        $value = $input[$key] ?? null;
        $clean[$key] = match ($kind) {
            'toggle'     => $value ? '1' : '0',
            'number'     => (string) max(0, (int) $value),
            'color'      => $value ? hex_color($value, '') : '',
            'select'     => array_key_exists((string) $value, $field[3]) ? (string) $value : (string) array_key_first($field[3]),
            'categories', 'products' => array_values(array_map('intval', array_filter((array) $value))),
            'category'   => (string) (int) $value,
            'items'      => array_values(array_map(fn($row) => section_clean_fields($field[3], (array) $row), array_filter((array) $value, 'is_array'))),
            'code'       => (string) $value,
            default      => trim((string) $value),
        };
    }
    return $clean;
}

// "file__items__2__image" gibi adlandırılmış dosya alanlarını ayarlara yerleştirir.
// Temizlemeden (section_clean) önce ham form verisine uygulanmalı. Yüklenenleri yol => dosya olarak döner.
function section_apply_uploads(&$settings, &$error = null)
{
    $uploaded = [];
    foreach (array_keys($_FILES) as $name) {
        if (!str_starts_with($name, 'file__')) {
            continue;
        }
        $file = upload_image($name, $error);
        if (!$file) {
            continue;
        }
        $path = explode('__', substr($name, 6));
        $target = &$settings;
        foreach ($path as $segment) {
            if (!is_array($target)) {
                continue 2;
            }
            $target = &$target[$segment];
        }
        $target = $file;
        unset($target);
        $uploaded[substr($name, 6)] = ['value' => $file, 'src' => upload_url($file)];
    }
    return $uploaded;
}

function section_label($section)
{
    $s = section_settings($section);
    $type = section_type($section['type']);
    $detail = $s['title'] ?? ($s['items'][0]['title'] ?? '');
    return [$type['label'] ?? $section['type'], $detail];
}

function section_pages()
{
    $pages = ['home' => 'Anasayfa'];
    foreach (db_all('SELECT id, title FROM pages ORDER BY sort, title') as $page) {
        $pages['page-' . $page['id']] = 'Sayfa: ' . $page['title'];
    }
    return $pages;
}

function section_page_url($page)
{
    if ($page === 'home') {
        return url();
    }
    $row = db_find('pages', (int) substr($page, 5));
    return $row ? page_url($row) : url();
}

function section_add($page, $type)
{
    $sort = (int) db_value('SELECT COALESCE(MAX(sort), 0) + 1 FROM sections WHERE page = ?', [$page]);
    return db_insert('sections', ['page' => $page, 'type' => $type, 'settings' => json_encode(section_type($type)['defaults'], JSON_UNESCAPED_UNICODE), 'sort' => $sort]);
}

// Anasayfayı mevcut içerikten bölümlerle kurar (ilk geçişte bir kez çalışır).
function sections_seed()
{
    if (db_value("SELECT COUNT(*) FROM sections WHERE page = 'home'")) {
        return;
    }

    $slides = db_all('SELECT * FROM slides WHERE status = 1 ORDER BY sort, id');
    $items = array_map(fn($slide) => [
        'image' => $slide['image'] ?? '', 'eyebrow' => '', 'title' => $slide['title'], 'subtitle' => $slide['subtitle'] ?? '',
        'button_text' => $slide['button_text'] ?? '', 'link' => $slide['link'] ?? '',
    ], $slides);

    $plan = [
        ['slider', $items ? ['items' => $items] : []],
        ['categories', []],
        ['products', ['title' => 'Öne çıkanlar', 'source' => 'featured']],
        ['products', ['title' => 'İndirimli seçkiler', 'source' => 'sale', 'limit' => '4', 'layout' => 'promo', 'bg' => '', 'promo_text' => 'Sevilen ürünlerde kaçırılmayacak fiyatlar. Stoklarla sınırlı.']],
        ['products', ['title' => 'Yeni gelenler', 'source' => 'latest']],
        ['banner', []],
        ['products', ['title' => 'Çok satanlar', 'source' => 'bestsellers', 'limit' => '4']],
        ['reviews', []],
        ['newsletter', []],
    ];

    $sort = 0;
    foreach ($plan as [$type, $settings]) {
        $settings = array_merge(section_type($type)['defaults'], $settings);
        db_insert('sections', ['page' => 'home', 'type' => $type, 'settings' => json_encode($settings, JSON_UNESCAPED_UNICODE), 'sort' => $sort++]);
    }
}
