<?php

function view_header($title = '', $meta = [])
{
    include PARTS . '/header.php';
}

function view_footer()
{
    include PARTS . '/footer.php';
}

function admin_header($title = '', $actions = '')
{
    include PARTS . '/admin-header.php';
}

function admin_footer()
{
    include PARTS . '/admin-footer.php';
}

function account_header($title)
{
    view_header($title, ['noindex' => true]);
    include PARTS . '/account-header.php';
}

function account_footer()
{
    include PARTS . '/account-footer.php';
    view_footer();
}

function auth_header($title)
{
    view_header($title, ['noindex' => true]);
    include PARTS . '/auth-layout.php';
}

function auth_footer()
{
    include PARTS . '/auth-layout-end.php';
    view_footer();
}

function page_title($title)
{
    if (!$title) {
        return setting('seo_home_title') ?: store_name() . ' — ' . site_setting('store_tagline', '');
    }
    return $title . setting('seo_separator', ' — ') . store_name();
}

function tailwind_head()
{
    include PARTS . '/head.php';
}

function flash_messages()
{
    include PARTS . '/flash.php';
}

function product_card($product)
{
    include PARTS . '/product-card.php';
}

function product_grid($products, $empty = 'Henüz ürün yok.', $cols = null)
{
    include PARTS . '/product-grid.php';
}

function pagination($pager)
{
    include PARTS . '/pagination.php';
}

function breadcrumb($items)
{
    include PARTS . '/breadcrumb.php';
}

function admin_field($field, $value, $name, $path)
{
    include PARTS . '/admin-field.php';
}

function admin_repeater_row($fields, $row, $name, $path, $index)
{
    include PARTS . '/admin-repeater-row.php';
}

// Alan listesini iki sütunlu bir ızgarada çizer.
function admin_fields($fields, $values, $prefix)
{
    echo '<div class="grid gap-5 sm:grid-cols-2">';
    foreach ($fields as $field) {
        admin_field($field, $values[$field[0]] ?? '', $prefix . '[' . $field[0] . ']', $field[0]);
    }
    echo '</div>';
}

function filter_open($key, $label, $selected = 0)
{
    include PARTS . '/filter-section.php';
}

function filter_close()
{
    echo '</div></section>';
}

function section_title($title, $link = null, $link_text = 'Tümünü gör')
{
    include PARTS . '/section-title.php';
}

function placeholder($name, $size = 'text-6xl')
{
    $tones = ['bg-stone-100 text-stone-300', 'bg-rose-50 text-rose-200', 'bg-sky-50 text-sky-200', 'bg-amber-50 text-amber-200', 'bg-emerald-50 text-emerald-200', 'bg-violet-50 text-violet-200', 'bg-zinc-100 text-zinc-300'];
    $tone = $tones[crc32((string) $name) % count($tones)];
    return '<div class="flex h-full w-full items-center justify-center ' . $tone . '"><span class="font-display ' . $size . ' font-semibold tracking-tighter">'
        . e(mb_strtoupper(mb_substr((string) $name, 0, 1))) . '</span></div>';
}

function image_tag($file, $alt, $class = '', $size = 'text-6xl')
{
    if (!$file) {
        return placeholder($alt, $size);
    }
    return '<img src="' . e(upload_url($file)) . '" alt="' . e($alt) . '" class="' . $class . '" loading="lazy">';
}

function product_image($product, $class = 'h-full w-full object-cover', $size = 'text-6xl')
{
    return image_tag($product['image'] ?? null, $product['name'] ?? '', $class, $size);
}

function product_url($product)
{
    return url('urun/' . $product['slug']);
}

function category_url($category)
{
    return url('kategori/' . $category['slug']);
}

function page_url($page)
{
    return url('sayfa/' . $page['slug']);
}

function menu_categories()
{
    static $categories = null;
    if ($categories === null) {
        $categories = db_all('SELECT * FROM categories WHERE status = 1 AND parent_id IS NULL ORDER BY sort, name');
    }
    return $categories;
}

function menu_children($parent_id)
{
    static $all = null;
    if ($all === null) {
        $all = db_all('SELECT * FROM categories WHERE status = 1 AND parent_id IS NOT NULL ORDER BY sort, name');
    }
    return array_values(array_filter($all, fn($row) => $row['parent_id'] == $parent_id));
}

function footer_pages()
{
    static $pages = null;
    if ($pages === null) {
        $pages = db_all('SELECT id, title, slug FROM pages WHERE status = 1 ORDER BY sort, title');
    }
    return $pages;
}

function social_links()
{
    $links = [];
    foreach (['instagram' => 'Instagram', 'facebook' => 'Facebook', 'x' => 'X'] as $key => $label) {
        if (setting($key)) {
            $links[$label] = setting($key);
        }
    }
    return $links;
}

function admin_menu()
{
    return [
        'Mağaza' => [
            ['index',       'Panel',         ['index'],                     'home'],
            ['siparisler',  'Siparişler',    ['siparisler', 'siparis'],     'cart'],
            ['musteriler',  'Müşteriler',    ['musteriler', 'musteri'],     'users'],
            ['mesajlar',    'Mesajlar',      ['mesajlar'],                  'mail'],
        ],
        'Katalog' => [
            ['urunler',     'Ürünler',       ['urunler', 'urun'],           'cube'],
            ['kategoriler', 'Kategoriler',   ['kategoriler', 'kategori'],   'grid'],
            ['yorumlar',    'Yorumlar',      ['yorumlar'],                  'chat'],
        ],
        'Görünüm' => [
            ['tema',        'Tema',          ['tema'],                      'photo'],
            ['duzen',       'Sayfa düzeni',  ['duzen', 'bolum'],            'slides'],
            ['menuler',     'Menüler',       ['menuler'],                   'menu'],
            ['sayfalar',    'Sayfalar',      ['sayfalar', 'sayfa'],         'document'],
        ],
        'Pazarlama' => [
            ['kuponlar',    'Kuponlar',      ['kuponlar', 'kupon'],         'tag'],
            ['aboneler',    'Bülten aboneleri', ['aboneler'],               'users'],
        ],
        'Sistem' => [
            ['ayarlar',     'Ayarlar',       ['ayarlar'],                   'cog'],
            ['kargo',       'Kargo kuralları', ['kargo'],                   'truck'],
            ['araclar',     'Araçlar',       ['araclar'],                   'filter'],
            ['yoneticiler', 'Yöneticiler',   ['yoneticiler', 'yonetici'],   'lock'],
            ['gunluk',      'İşlem günlüğü', ['gunluk'],                    'clock'],
        ],
    ];
}

function admin_badge($file)
{
    if ($file === 'siparisler') {
        return (int) db_value("SELECT COUNT(*) FROM orders WHERE status = 'beklemede'");
    }
    if ($file === 'yorumlar') {
        return pending_review_count();
    }
    if ($file === 'mesajlar') {
        return (int) db_value('SELECT COUNT(*) FROM messages WHERE is_read = 0');
    }
    return 0;
}

function is_menu_active($files)
{
    return in_array(current_file(), $files, true);
}

function status_badge($active, $on = 'Aktif', $off = 'Pasif')
{
    return $active
        ? '<span class="inline-flex items-center gap-1.5 rounded-full bg-emerald-50 px-2.5 py-1 text-xs font-semibold text-emerald-700 ring-1 ring-emerald-600/20 ring-inset"><span class="size-1.5 rounded-full bg-emerald-500"></span>' . $on . '</span>'
        : '<span class="inline-flex items-center gap-1.5 rounded-full bg-zinc-100 px-2.5 py-1 text-xs font-semibold text-zinc-600 ring-1 ring-zinc-500/20 ring-inset"><span class="size-1.5 rounded-full bg-zinc-400"></span>' . $off . '</span>';
}

function form_error($error)
{
    if ($error) {
        return '<div class="mb-6 flex items-start gap-3 rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-800">' . icon('alert', 'mt-0.5 size-4 shrink-0', '2') . '<span>' . e($error) . '</span></div>';
    }
    return '';
}

function empty_state($icon, $title, $text = '', $button = null)
{
    include PARTS . '/empty-state.php';
}
