<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/bootstrap.php';
require_once __DIR__ . '/../includes/admin_layout.php';

require_admin();

$fonts = theme_font_catalog();
$presets = theme_presets();
$tab = trim((string) ($_GET['tab'] ?? 'renkler'));
$allowedTabs = ['renkler', 'yazi', 'ust', 'footer', 'urun', 'guvenli', 'odeme', 'koruma'];
if (!in_array($tab, $allowedTabs, true)) {
    $tab = 'renkler';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['action'] ?? 'save');
    $returnTab = trim((string) ($_POST['tab'] ?? 'renkler'));
    if (!in_array($returnTab, $allowedTabs, true)) {
        $returnTab = 'renkler';
    }

    if ($action === 'reset_all') {
        $settings = settings_get();
        $settings['theme'] = theme_normalize(theme_defaults());
        $settings['theme_copy'] = theme_copy_normalize(theme_copy_defaults());
        settings_save($settings);
        flash('success', 'Tema ve tüm metinler varsayılana döndü.');
        redirect(url('admin/tema.php?tab=' . rawurlencode($returnTab)));
    }

    if ($action === 'reset_colors') {
        $cur = theme_get();
        $def = theme_defaults();
        foreach (['bg', 'bg_2', 'surface', 'ink', 'muted', 'line', 'brand', 'brand_dark', 'accent', 'btn', 'btn_text', 'footer_bg'] as $k) {
            $cur[$k] = $def[$k];
        }
        theme_save($cur);
        flash('success', 'Renkler varsayılana döndü.');
        redirect(url('admin/tema.php?tab=renkler'));
    }

    if ($action === 'reset_copy') {
        theme_copy_save(theme_copy_defaults());
        flash('success', 'Metinler varsayılana döndü.');
        redirect(url('admin/tema.php?tab=' . rawurlencode($returnTab)));
    }

    if ($action === 'apply_preset') {
        $pid = (string) ($_POST['preset_id'] ?? '');
        $found = null;
        foreach ($presets as $p) {
            if ($p['id'] === $pid) {
                $found = $p;
                break;
            }
        }
        if ($found) {
            $cur = theme_get();
            foreach ($found['colors'] as $k => $v) {
                $cur[$k] = $v;
            }
            theme_save($cur);
            flash('success', $found['label'] . ' paleti uygulandı.');
        }
        redirect(url('admin/tema.php?tab=renkler'));
    }

    // Kaydet — renk + font + metinler (tek yazma)
    $nextTheme = theme_normalize([
        'bg' => $_POST['bg'] ?? '',
        'bg_2' => $_POST['bg_2'] ?? '',
        'surface' => $_POST['surface'] ?? '',
        'ink' => $_POST['ink'] ?? '',
        'muted' => $_POST['muted'] ?? '',
        'line' => $_POST['line'] ?? '',
        'brand' => $_POST['brand'] ?? '',
        'brand_dark' => $_POST['brand_dark'] ?? '',
        'accent' => $_POST['accent'] ?? '',
        'btn' => $_POST['btn'] ?? '',
        'btn_text' => $_POST['btn_text'] ?? '',
        'footer_bg' => $_POST['footer_bg'] ?? '',
        'font' => $_POST['font'] ?? '',
        'display' => $_POST['display'] ?? '',
        'radius' => $_POST['radius'] ?? '18',
        'block_context_menu' => !empty($_POST['block_context_menu']) ? '1' : '0',
        'block_select' => !empty($_POST['block_select']) ? '1' : '0',
        'block_drag' => !empty($_POST['block_drag']) ? '1' : '0',
        'block_copy' => !empty($_POST['block_copy']) ? '1' : '0',
        'block_shortcuts' => !empty($_POST['block_shortcuts']) ? '1' : '0',
    ]);

    // Sadece bu sekmede gelen metinleri güncelle; diğerleri settings’ten korunur.
    $postedCopy = $_POST['copy'] ?? [];
    if (!is_array($postedCopy)) {
        $postedCopy = [];
    }
    $copyIn = [];
    foreach (array_keys(theme_copy_defaults()) as $key) {
        if (array_key_exists($key, $postedCopy)) {
            $copyIn[$key] = (string) $postedCopy[$key];
        }
    }
    $mergedCopy = array_merge(theme_copy_get(), $copyIn);

    $settings = settings_get();
    $settings['theme'] = $nextTheme;
    $settings['theme_copy'] = theme_copy_normalize($mergedCopy);
    if (!settings_save($settings)) {
        flash('error', 'Tema kaydedilemedi. data/settings.json yazılabilir mi kontrol et.');
        redirect(url('admin/tema.php?tab=' . rawurlencode($returnTab)));
    }

    flash('success', 'Tema kaydedildi. Vitrini yenile.');
    redirect(url('admin/tema.php?tab=' . rawurlencode($returnTab)));
}

$theme = theme_get();
$copy = theme_copy_get();

admin_layout_start('Tema', 'theme');

$colorFields = [
    'bg' => ['Site arka planı', 'Sayfa genel zemini'],
    'bg_2' => ['Arka plan 2', 'Gradient / ikinci ton'],
    'surface' => ['Kart rengi', 'Ürün kartı / paneller'],
    'ink' => ['Ana yazı rengi', 'Başlık ve gövde metni'],
    'muted' => ['İkincil yazı', 'Açıklama / soluk metin'],
    'line' => ['Çizgi / kenarlık', 'İnce ayırıcılar'],
    'brand' => ['Marka rengi', 'Linkler ve vurgu'],
    'brand_dark' => ['Marka koyu', 'Hover tonu'],
    'accent' => ['Aksan rengi', 'Dekoratif vurgu'],
    'btn' => ['Buton rengi', 'SATIN AL vb.'],
    'btn_text' => ['Buton yazı rengi', 'Buton içi metin'],
    'footer_bg' => ['Footer rengi', 'Alt kısım zemini'],
];

$tabs = [
    'renkler' => 'Renkler',
    'yazi' => 'Yazı tipleri',
    'ust' => 'Üst menü',
    'footer' => 'Footer',
    'urun' => 'Ürün avantajları',
    'guvenli' => 'Güvenli ödeme',
    'odeme' => 'Sipariş / Ödeme',
    'koruma' => 'Koruma',
];
$protectFlags = [
    'block_context_menu' => ($theme['block_context_menu'] ?? '0') === '1',
    'block_select' => ($theme['block_select'] ?? '0') === '1',
    'block_drag' => ($theme['block_drag'] ?? '0') === '1',
    'block_copy' => ($theme['block_copy'] ?? '0') === '1',
    'block_shortcuts' => ($theme['block_shortcuts'] ?? '0') === '1',
];
$blockContext = $protectFlags['block_context_menu'];

function theme_field(string $key, string $label, array $copy, string $hint = '', int $rows = 1): void
{
    $val = $copy[$key] ?? '';
    echo '<label class="theme-text-field">';
    echo '<span class="theme-text-label">' . e($label) . '</span>';
    if ($hint !== '') {
        echo '<span class="hint" style="margin:0">' . e($hint) . '</span>';
    }
    if ($rows > 1) {
        echo '<textarea name="copy[' . e($key) . ']" rows="' . (int) $rows . '">' . e($val) . '</textarea>';
    } else {
        echo '<input type="text" name="copy[' . e($key) . ']" value="' . e($val) . '">';
    }
    echo '</label>';
}
?>

<section class="admin-panel theme-studio">
    <div class="theme-studio-head">
        <div>
            <h2>Vitrin teması</h2>
            <p class="hint">Renk, yazı tipi, footer sol/sağ başlıklar, ürün avantajları ve güvenli ödeme sayfası metinlerini buradan yönet.</p>
        </div>
        <div class="theme-studio-links">
            <a class="admin-btn ghost" href="<?= e(url('index.php')) ?>" target="_blank" rel="noopener">Vitrin</a>
            <a class="admin-btn ghost" href="<?= e(url('guvenli-odeme.php')) ?>" target="_blank" rel="noopener">Güvenli ödeme</a>
        </div>
    </div>

    <nav class="theme-tabs" aria-label="Tema bölümleri">
        <?php foreach ($tabs as $id => $label): ?>
            <a class="theme-tab<?= $tab === $id ? ' is-active' : '' ?>" href="<?= e(url('admin/tema.php?tab=' . rawurlencode($id))) ?>"><?= e($label) ?></a>
        <?php endforeach; ?>
    </nav>

    <form method="post" class="admin-form theme-form" id="theme-form">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="tab" value="<?= e($tab) ?>">

        <?php if ($tab === 'renkler'): ?>
            <div class="theme-preset-row">
                <span class="theme-section-label">Hazır paletler</span>
                <div class="theme-presets">
                    <?php foreach ($presets as $p): ?>
                        <button type="submit" class="theme-preset-btn" name="action" value="apply_preset"
                                formaction="<?= e(url('admin/tema.php?tab=renkler')) ?>"
                                onclick="var f=this.form; var el=f.querySelector('input[name=preset_id]'); if(!el){el=document.createElement('input'); el.type='hidden'; el.name='preset_id'; f.appendChild(el);} el.value='<?= e($p['id']) ?>';">
                            <span class="theme-preset-swatches" aria-hidden="true">
                                <i style="background:<?= e($p['colors']['brand']) ?>"></i>
                                <i style="background:<?= e($p['colors']['btn']) ?>"></i>
                                <i style="background:<?= e($p['colors']['accent']) ?>"></i>
                                <i style="background:<?= e($p['colors']['footer_bg']) ?>"></i>
                            </span>
                            <?= e($p['label']) ?>
                        </button>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="theme-layout-2">
                <div>
                    <div class="theme-grid">
                        <?php foreach ($colorFields as $key => [$label, $hint]): ?>
                            <label class="theme-color-field">
                                <span class="theme-color-label"><?= e($label) ?></span>
                                <span class="hint" style="margin:0"><?= e($hint) ?></span>
                                <span class="theme-color-row">
                                    <input type="color" name="<?= e($key) ?>_picker" value="<?= e($theme[$key]) ?>" data-color-sync="<?= e($key) ?>">
                                    <input type="text" name="<?= e($key) ?>" id="theme-<?= e($key) ?>" value="<?= e($theme[$key]) ?>" pattern="^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$" maxlength="7" required>
                                </span>
                            </label>
                        <?php endforeach; ?>
                    </div>
                    <label class="theme-text-field" style="margin-top:0.85rem">
                        <span class="theme-text-label">Köşe yuvarlaklığı (px)</span>
                        <span class="hint" style="margin:0">0 = keskin. 18 = varsayılan. 8–24 arası dene.</span>
                        <input type="number" name="radius" min="0" max="24" value="<?= e((string) ($theme['radius'] ?? '18')) ?>">
                    </label>
                </div>

                <aside class="theme-live-preview" data-theme-preview>
                    <p class="theme-preview-label">Canlı önizleme</p>
                    <div class="theme-preview-card" style="background:<?= e($theme['bg']) ?>;color:<?= e($theme['ink']) ?>;border-color:<?= e($theme['line']) ?>;border-radius:<?= (int) ($theme['radius'] ?? 0) ?>px">
                        <small style="color:<?= e($theme['muted']) ?>">Vitrin kartı</small>
                        <strong style="color:<?= e($theme['brand']) ?>">Organik Bal</strong>
                        <p style="color:<?= e($theme['muted']) ?>;margin:0.35rem 0 0.75rem">İkincil açıklama metni</p>
                        <div class="theme-preview-actions">
                            <span class="theme-preview-btn" style="background:<?= e($theme['btn']) ?>;color:<?= e($theme['btn_text']) ?>;border-radius:<?= (int) ($theme['radius'] ?? 0) ?>px">SATIN AL</span>
                            <span class="theme-preview-chip" style="background:<?= e($theme['surface']) ?>;border-color:<?= e($theme['line']) ?>;color:<?= e($theme['ink']) ?>;border-radius:<?= (int) ($theme['radius'] ?? 0) ?>px">Kart</span>
                        </div>
                        <div class="theme-preview-footer" style="background:<?= e($theme['footer_bg']) ?>;border-radius:<?= (int) ($theme['radius'] ?? 0) ?>px">Footer</div>
                    </div>
                </aside>
            </div>

        <?php elseif ($tab === 'yazi'): ?>
            <p class="hint">Gövde ve başlık fontlarını ayrı seçebilirsin. Kaydettikten sonra vitrinde Google Fonts yüklenir.</p>
            <div class="theme-fonts">
                <label>Gövde yazı tipi
                    <select name="font" data-font-preview="body">
                        <?php foreach ($fonts as $f): ?>
                            <option value="<?= e($f['id']) ?>" <?= ($theme['font'] ?? '') === $f['id'] ? 'selected' : '' ?>><?= e($f['label']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
                <label>Başlık / display yazı tipi
                    <select name="display" data-font-preview="display">
                        <?php foreach ($fonts as $f): ?>
                            <option value="<?= e($f['id']) ?>" <?= ($theme['display'] ?? '') === $f['id'] ? 'selected' : '' ?>><?= e($f['label']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </label>
            </div>
            <div class="theme-font-sample">
                <p class="theme-preview-label">Örnek</p>
                <h3 data-font-sample-display style="font-family:<?= e($theme['display']) ?>, Georgia, serif">Doğadan Sofranıza</h3>
                <p data-font-sample-body style="font-family:<?= e($theme['font']) ?>, system-ui, sans-serif">Bölgesel üreticilerden seçilmiş doğal ürünler — vitrin gövde yazısı örneği.</p>
            </div>
            <?php
            // Font sekmesinde renkleri korumak için hidden gönder
            foreach (array_keys($colorFields) as $key): ?>
                <input type="hidden" name="<?= e($key) ?>" value="<?= e($theme[$key]) ?>">
            <?php endforeach; ?>
            <input type="hidden" name="radius" value="<?= e((string) ($theme['radius'] ?? '0')) ?>">

        <?php elseif ($tab === 'ust'): ?>
            <p class="hint">Masaüstü üst bardaki menü etiketleri. Mobil menü linkleri için <a href="<?= e(url('admin/menu.php')) ?>">Menü</a> sayfasını kullan.</p>
            <div class="theme-text-grid">
                <?php
                theme_field('nav_home', 'Vitrin linki', $copy);
                theme_field('nav_shop', 'Mağaza linki', $copy);
                theme_field('home_empty', 'Vitrin boş durum mesajı', $copy, '', 2);
                ?>
            </div>
            <?php theme_hidden_style_fields($theme, $colorFields); ?>

        <?php elseif ($tab === 'footer'): ?>
            <p class="hint">Alt kısımdaki sol (kategoriler), orta (popüler) ve sağ (hakkında) sütun başlıkları ile link yazıları. Sosyal URL boşsa buton # kalır.</p>
            <h3 class="theme-subhead">Sütun başlıkları (sol · orta · sağ)</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('footer_cats_title', 'Sol — Kategoriler', $copy);
                theme_field('footer_popular_title', 'Orta — Popüler aramalar', $copy);
                theme_field('footer_about_title', 'Sağ — Hakkında', $copy);
                ?>
            </div>
            <h3 class="theme-subhead">Sağ sütun link yazıları</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('footer_link_vitrin', 'Vitrin linki', $copy);
                theme_field('footer_link_contact', 'İletişim yazısı', $copy);
                theme_field('footer_link_support', 'Destek yazısı', $copy);
                theme_field('footer_link_shop', 'Satıcı mağazası', $copy);
                theme_field('footer_link_secure', 'Güvenli ödeme', $copy);
                ?>
            </div>
            <h3 class="theme-subhead">İletişim & Destek yönlendirme</h3>
            <p class="hint">Tıklanınca gidilecek adres. Boş bırakırsan WhatsApp (Site Ayarları telefonu) açılır. Tam URL veya site içi yol yazabilirsin (<code>https://...</code> / <code>iletisim.php</code>).</p>
            <div class="theme-text-grid">
                <?php
                theme_field('footer_url_contact', 'İletişim linki', $copy, 'Boş = WhatsApp');
                theme_field('footer_url_support', 'Destek linki', $copy, 'Boş = WhatsApp');
                ?>
            </div>
            <h3 class="theme-subhead">Sosyal medya URL</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('social_twitter', 'Twitter / X URL', $copy, 'Boş bırakılabilir');
                theme_field('social_facebook', 'Facebook URL', $copy, 'Boş bırakılabilir');
                theme_field('social_instagram', 'Instagram URL', $copy, 'Boş bırakılabilir');
                ?>
            </div>
            <?php theme_hidden_style_fields($theme, $colorFields); ?>

        <?php elseif ($tab === 'urun'): ?>
            <p class="hint">Ürün detayındaki “Doğal Avantajları” + alttaki iki büyük satır (kamyon / kart). Satır kırmak için Enter. <code>{site}</code> → <strong><?= e(site_name()) ?></strong></p>
            <h3 class="theme-subhead">Bölüm + 3 ikon kutusu</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('adv_section_title', 'Bölüm başlığı', $copy);
                theme_field('adv_item_1', 'Avantaj 1 (ikon yazısı)', $copy, 'İki satır önerilir', 2);
                theme_field('adv_item_2', 'Avantaj 2', $copy, '', 2);
                theme_field('adv_item_3', 'Avantaj 3', $copy, '', 2);
                ?>
            </div>
            <h3 class="theme-subhead">Kamyon satırı (güvenli ödeme kutusu)</h3>
            <p class="hint">Ürün sayfasında kamyon ikonlu büyük satır — tıkladığında güvenli ödeme sayfasına gider.</p>
            <div class="theme-text-grid">
                <?php
                theme_field('adv_secure_title', 'Başlık', $copy, '{site} yazarsan site adı gelir', 2);
                theme_field('adv_secure_body', 'Açıklama', $copy, '', 4);
                ?>
            </div>
            <h3 class="theme-subhead">Kart satırı (ödeme seçenekleri)</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('adv_pay_title', 'Başlık', $copy);
                theme_field('adv_pay_body', 'Açıklama', $copy, '', 3);
                ?>
            </div>
            <?php theme_hidden_style_fields($theme, $colorFields); ?>

        <?php elseif ($tab === 'guvenli'): ?>
            <p class="hint"><a href="<?= e(url('guvenli-odeme.php')) ?>" target="_blank" rel="noopener">Güvenli Ödeme</a> kurumsal sayfası + ürün detayındaki kamyon/kart kutuları. <code>{site}</code> → <strong><?= e(site_name()) ?></strong></p>

            <h3 class="theme-subhead">Ürün sayfası — kamyon / kart kutuları</h3>
            <p class="hint">Ekrandaki kamyon ikonlu satır buradan düzenlenir. Aynı alanlar <a href="<?= e(url('admin/tema.php?tab=urun')) ?>">Ürün avantajları</a> sekmesinde de var.</p>
            <div class="theme-text-grid">
                <?php
                theme_field('adv_secure_title', 'Kamyon satırı — başlık', $copy, '{site} kullanabilirsin', 2);
                theme_field('adv_secure_body', 'Kamyon satırı — açıklama', $copy, '', 4);
                theme_field('adv_pay_title', 'Kart satırı — başlık', $copy);
                theme_field('adv_pay_body', 'Kart satırı — açıklama', $copy, '', 3);
                ?>
            </div>

            <h3 class="theme-subhead">Üst / paylaşım</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('secure_page_title', 'Sayfa başlığı (sekme)', $copy);
                theme_field('secure_og_title', 'Paylaşım başlığı', $copy);
                theme_field('secure_og_desc', 'Paylaşım açıklaması', $copy, '', 2);
                theme_field('secure_eyebrow', 'Üst etiket', $copy);
                theme_field('secure_h1', 'Ana başlık', $copy);
                theme_field('secure_lead', 'Giriş paragrafı', $copy, '', 3);
                ?>
            </div>
            <h3 class="theme-subhead">Nasıl çalışır? (4 adım)</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('secure_how_title', 'Bölüm başlığı', $copy);
                theme_field('secure_step1_title', 'Adım 1 başlık', $copy);
                theme_field('secure_step1_body', 'Adım 1 metin', $copy, '', 2);
                theme_field('secure_step2_title', 'Adım 2 başlık', $copy);
                theme_field('secure_step2_body', 'Adım 2 metin', $copy, '', 2);
                theme_field('secure_step3_title', 'Adım 3 başlık', $copy);
                theme_field('secure_step3_body', 'Adım 3 metin', $copy, '', 2);
                theme_field('secure_step4_title', 'Adım 4 başlık', $copy);
                theme_field('secure_step4_body', 'Adım 4 metin', $copy, '', 2);
                ?>
            </div>
            <h3 class="theme-subhead">Ödeme seçenekleri</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('secure_pay_title', 'Başlık', $copy);
                theme_field('secure_pay_body', 'Açıklama', $copy, '', 3);
                theme_field('secure_pay_li1', 'Madde 1', $copy);
                theme_field('secure_pay_li2', 'Madde 2', $copy);
                theme_field('secure_pay_li3', 'Madde 3', $copy);
                ?>
            </div>
            <h3 class="theme-subhead">Neden güvenli havuz? (3 kutu)</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('secure_why_title', 'Bölüm başlığı', $copy);
                theme_field('secure_why1_title', 'Kutu 1 başlık', $copy);
                theme_field('secure_why1_body', 'Kutu 1 metin', $copy, '', 2);
                theme_field('secure_why2_title', 'Kutu 2 başlık', $copy);
                theme_field('secure_why2_body', 'Kutu 2 metin', $copy, '', 2);
                theme_field('secure_why3_title', 'Kutu 3 başlık', $copy);
                theme_field('secure_why3_body', 'Kutu 3 metin', $copy, '', 2);
                theme_field('secure_foot', 'Alt not', $copy, '', 2);
                ?>
            </div>
            <?php theme_hidden_style_fields($theme, $colorFields); ?>

        <?php elseif ($tab === 'odeme'): ?>
            <p class="hint">Teslimat formu, onay özeti, ödeme ve tamamlandı ekranı metinleri. <code>{minutes}</code> = ödeme süresi (dakika).</p>

            <h3 class="theme-subhead">Ana ilerleme (Teslimat → Ödeme → Tamam)</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('chk_step_form', '1. adım adı', $copy);
                theme_field('chk_step_pay', '2. adım adı', $copy);
                theme_field('chk_step_done', '3. adım adı', $copy);
                ?>
            </div>

            <h3 class="theme-subhead">Teslimat — alt adımlar & başlık</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('chk_form_title', 'Sayfa başlığı', $copy);
                theme_field('chk_sub_contact', 'Alt adım: İletişim', $copy);
                theme_field('chk_sub_address', 'Alt adım: Adres', $copy);
                theme_field('chk_sub_summary', 'Alt adım: Özet', $copy);
                ?>
            </div>

            <h3 class="theme-subhead">İletişim adımı</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('chk_contact_title', 'Bölüm başlığı', $copy);
                theme_field('chk_contact_hint', 'Açıklama', $copy, '', 2);
                theme_field('chk_label_first_name', 'Ad etiketi', $copy);
                theme_field('chk_label_last_name', 'Soyad etiketi', $copy);
                theme_field('chk_label_phone', 'Telefon etiketi', $copy);
                theme_field('chk_label_tc', 'TC etiketi', $copy);
                theme_field('chk_ph_phone', 'Telefon placeholder', $copy);
                theme_field('chk_ph_tc', 'TC placeholder', $copy);
                theme_field('chk_btn_to_address', 'Devam butonu', $copy);
                theme_field('chk_hint_after_contact', 'Alt ipucu', $copy, '', 2);
                ?>
            </div>

            <h3 class="theme-subhead">Adres adımı</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('chk_address_title', 'Bölüm başlığı', $copy);
                theme_field('chk_address_hint', 'Açıklama', $copy, '', 2);
                theme_field('chk_label_city', 'Şehir', $copy);
                theme_field('chk_label_district', 'İlçe', $copy);
                theme_field('chk_label_neighborhood', 'Mahalle', $copy);
                theme_field('chk_label_street', 'Sokak', $copy);
                theme_field('chk_label_apartment', 'Apartman', $copy);
                theme_field('chk_label_door', 'Kapı No', $copy);
                theme_field('chk_label_note', 'Not', $copy);
                theme_field('chk_ph_city', 'Şehir placeholder', $copy);
                theme_field('chk_ph_district', 'İlçe placeholder', $copy);
                theme_field('chk_ph_neighborhood', 'Mahalle placeholder', $copy);
                theme_field('chk_ph_street', 'Sokak placeholder', $copy);
                theme_field('chk_ph_door', 'Kapı placeholder', $copy);
                theme_field('chk_ph_optional', 'Opsiyonel placeholder', $copy);
                theme_field('chk_btn_back', 'Geri butonu', $copy);
                theme_field('chk_btn_to_summary', 'Devam — Özet butonu', $copy);
                theme_field('chk_hint_after_address', 'Alt ipucu', $copy, '', 2);
                ?>
            </div>

            <h3 class="theme-subhead">Onay özeti</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('chk_summary_title', 'Başlık', $copy);
                theme_field('chk_summary_hint', 'Açıklama', $copy, '', 2);
                theme_field('chk_sum_buyer', 'Alıcı etiketi', $copy);
                theme_field('chk_sum_phone', 'Telefon etiketi', $copy);
                theme_field('chk_sum_tc', 'TC etiketi', $copy);
                theme_field('chk_sum_address', 'Adres etiketi', $copy);
                theme_field('chk_sum_note', 'Not etiketi', $copy);
                theme_field('chk_sum_total', 'Tutar etiketi', $copy);
                theme_field('chk_btn_edit', 'Düzenle butonu', $copy);
                theme_field('chk_btn_confirm', 'Onayla butonu', $copy);
                theme_field('chk_hint_after_summary', 'Alt ipucu ({minutes})', $copy, '', 2);
                ?>
            </div>

            <h3 class="theme-subhead">Ödeme ekranı</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('pay_title', 'Sayfa başlığı', $copy);
                theme_field('pay_sub_transfer', 'Alt adım: Havale', $copy);
                theme_field('pay_sub_receipt', 'Alt adım: Dekont', $copy);
                theme_field('pay_method_kicker', 'Ödeme yöntemi etiketi', $copy);
                theme_field('pay_method_title', 'Ödeme yöntemi başlığı', $copy);
                theme_field('pay_timer_active', 'Süre aktif metni', $copy);
                theme_field('pay_timer_expired', 'Süre doldu metni', $copy);
                theme_field('pay_timer_hint', 'Süre altı ipucu', $copy, '', 2);
                theme_field('pay_order_no_label', 'Sipariş no etiketi', $copy);
                theme_field('pay_label_bank', 'Banka', $copy);
                theme_field('pay_label_account', 'Hesap adı', $copy);
                theme_field('pay_label_iban', 'IBAN', $copy);
                theme_field('pay_label_amount', 'Tutar', $copy);
                theme_field('pay_label_delivery', 'Teslimat', $copy);
                theme_field('pay_order_no_note', 'Açıklamaya sipariş no', $copy);
                theme_field('pay_btn_copy_iban', 'IBAN kopyala', $copy);
                theme_field('pay_btn_copy_order', 'Sipariş no kopyala', $copy);
                theme_field('pay_copied', 'Kopyalandı bildirimi', $copy);
                theme_field('pay_receipt_title', 'Dekont başlığı', $copy);
                theme_field('pay_receipt_hint', 'Dekont ipucu', $copy, '', 2);
                theme_field('pay_receipt_btn', 'Dekont butonu', $copy);
                theme_field('pay_file_pick', 'Dosya seç yazısı', $copy);
                theme_field('pay_file_types', 'Dosya türleri satırı', $copy);
                theme_field('pay_expired_hint', 'Süre doldu (dekont kutusu)', $copy, '', 2);
                ?>
            </div>

            <h3 class="theme-subhead">Tamamlandı ekranı</h3>
            <div class="theme-text-grid">
                <?php
                theme_field('pay_done_title', 'Başlık', $copy);
                theme_field('pay_done_ok', 'Başarı satırı', $copy);
                theme_field('pay_done_pending', 'Bekleyen kontrol satırı', $copy, '', 2);
                theme_field('pay_done_note', 'SMS / not', $copy, '', 2);
                theme_field('pay_done_order_no', 'Sipariş no etiketi', $copy);
                theme_field('pay_done_hint', 'Alt ipucu', $copy, '', 2);
                theme_field('pay_done_shop', 'Mağazaya dön butonu', $copy);
                ?>
            </div>
            <?php theme_hidden_style_fields($theme, $colorFields); ?>

        <?php elseif ($tab === 'koruma'): ?>
            <p class="hint">
                Sadece <strong>vitrinde</strong> çalışır — bu admin sayfasında koruma yoktur (yönetim bozulmasın diye).
                Kaydettikten sonra <a href="<?= e(url('index.php')) ?>" target="_blank" rel="noopener">vitrini</a> açıp dene.
                WhatsApp / OG bozulmaz.
            </p>
            <p class="hint" style="margin:0.35rem 0 0.75rem;color:#9b2c2c;font-weight:600">
                F12 ve tarayıcı menüsü çoğu Chrome/Edge’de engellenemez. Asıl etkisi: sağ tık, metin seçimi, Ctrl+U / Ctrl+S / Ctrl+C.
            </p>
            <p style="margin:0 0 0.65rem">
                <button type="button" class="admin-btn ghost" id="theme-protect-all">Hepsini işaretle</button>
            </p>
            <div class="theme-protect-list">
                <label class="theme-toggle-field">
                    <input type="checkbox" name="block_context_menu" value="1" <?= $protectFlags['block_context_menu'] ? 'checked' : '' ?>>
                    <span>
                        <strong>Sağ tık menüsünü kapat</strong>
                        <span class="hint" style="margin:0;display:block">Görsel kaydet / incele menüsünü engeller. (En çok fark edilen)</span>
                    </span>
                </label>
                <label class="theme-toggle-field">
                    <input type="checkbox" name="block_select" value="1" <?= $protectFlags['block_select'] ? 'checked' : '' ?>>
                    <span>
                        <strong>Metin seçimini kapat</strong>
                        <span class="hint" style="margin:0;display:block">Sürükleyerek kopyalamayı zorlaştırır. Form alanları ve ödeme kutusu hariç.</span>
                    </span>
                </label>
                <label class="theme-toggle-field">
                    <input type="checkbox" name="block_drag" value="1" <?= $protectFlags['block_drag'] ? 'checked' : '' ?>>
                    <span>
                        <strong>Görsel sürüklemeyi kapat</strong>
                        <span class="hint" style="margin:0;display:block">Ürün fotoğraflarını masaüstüne sürükleyip bırakmayı engeller.</span>
                    </span>
                </label>
                <label class="theme-toggle-field">
                    <input type="checkbox" name="block_copy" value="1" <?= $protectFlags['block_copy'] ? 'checked' : '' ?>>
                    <span>
                        <strong>Kopyala / kes kısayolunu kapat</strong>
                        <span class="hint" style="margin:0;display:block">Ctrl+C / Ctrl+X ve kopyala olayını engeller (ödeme alanı hariç).</span>
                    </span>
                </label>
                <label class="theme-toggle-field">
                    <input type="checkbox" name="block_shortcuts" value="1" <?= $protectFlags['block_shortcuts'] ? 'checked' : '' ?>>
                    <span>
                        <strong>Geliştirici / kaydet kısayollarını kapat</strong>
                        <span class="hint" style="margin:0;display:block">Ctrl+U, Ctrl+S, Ctrl+P denemelerini engeller. F12 tarayıcıya bağlıdır, garanti değil.</span>
                    </span>
                </label>
            </div>
            <p class="hint" style="margin-top:0.75rem">Not: Bunlar sıradan kullanıcıyı yavaşlatır; teknik olarak bilen biri kaynağı yine görebilir.</p>
            <?php theme_hidden_style_fields($theme, $colorFields); ?>
            <script>
            document.getElementById('theme-protect-all')?.addEventListener('click', function () {
              document.querySelectorAll('.theme-protect-list input[type="checkbox"]').forEach(function (c) { c.checked = true; });
            });
            </script>
        <?php endif; ?>

        <?php
        // Metin sekmelerinde font/display korunsun
        if ($tab !== 'yazi' && $tab !== 'renkler'): ?>
            <input type="hidden" name="font" value="<?= e($theme['font']) ?>">
            <input type="hidden" name="display" value="<?= e($theme['display']) ?>">
        <?php elseif ($tab === 'renkler'): ?>
            <input type="hidden" name="font" value="<?= e($theme['font']) ?>">
            <input type="hidden" name="display" value="<?= e($theme['display']) ?>">
        <?php endif; ?>

        <?php if ($tab !== 'koruma'): ?>
            <?php foreach ($protectFlags as $pfKey => $pfOn): ?>
                <input type="hidden" name="<?= e($pfKey) ?>" value="<?= $pfOn ? '1' : '0' ?>">
            <?php endforeach; ?>
        <?php endif; ?>

        <div class="theme-sticky-bar">
            <button class="admin-btn" type="submit" name="action" value="save">Kaydet</button>
            <?php if ($tab === 'renkler'): ?>
                <button class="admin-btn ghost" type="submit" name="action" value="reset_colors" onclick="return confirm('Sadece renkler varsayılana dönsün mü?')">Renkleri sıfırla</button>
            <?php elseif (in_array($tab, ['ust', 'footer', 'urun', 'guvenli', 'odeme'], true)): ?>
                <button class="admin-btn ghost" type="submit" name="action" value="reset_copy" onclick="return confirm('Tüm metinler varsayılana dönsün mü?')">Metinleri sıfırla</button>
            <?php endif; ?>
            <button class="admin-btn ghost" type="submit" name="action" value="reset_all" onclick="return confirm('Tema + tüm metinler varsayılana dönsün mü?')">Hepsini sıfırla</button>
        </div>
    </form>
</section>

<style>
.theme-studio-head{display:flex;flex-wrap:wrap;justify-content:space-between;gap:.75rem;align-items:flex-start;margin-bottom:.75rem}
.theme-studio-head h2{margin:0 0 .25rem}
.theme-studio-links{display:flex;flex-wrap:wrap;gap:.45rem}
.theme-tabs{display:flex;flex-wrap:wrap;gap:.35rem;margin:0 0 1rem;padding-bottom:.75rem;border-bottom:1px solid #d5e0cc}
.theme-tab{display:inline-flex;align-items:center;padding:.45rem .75rem;font-size:.82rem;font-weight:700;color:#3d4f3a;background:#f3f7f1;border:1px solid #d5e0cc;text-decoration:none}
.theme-tab:hover{background:#e8f0e4}
.theme-tab.is-active{background:#2f6b3a;border-color:#2f6b3a;color:#fff}
.theme-section-label{display:block;font-size:.72rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase;color:#6a7a64;margin-bottom:.4rem}
.theme-subhead{margin:1.1rem 0 .55rem;font-size:.95rem;color:#2f3d2f}
.theme-preset-row{margin-bottom:1rem}
.theme-presets{display:flex;flex-wrap:wrap;gap:.5rem}
.theme-preset-btn{display:inline-flex;align-items:center;gap:.45rem;padding:.45rem .7rem;border:1px solid #c5d4be;background:#fff;font:inherit;font-size:.8rem;font-weight:700;color:#2f3d2f;cursor:pointer}
.theme-preset-btn:hover{border-color:#2f6b3a}
.theme-preset-swatches{display:inline-flex;gap:3px}
.theme-preset-swatches i{width:12px;height:12px;display:block;border-radius:2px}
.theme-layout-2{display:grid;grid-template-columns:1fr minmax(220px,280px);gap:1rem;align-items:start}
.theme-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:.75rem}
.theme-color-field{display:grid;gap:.25rem;padding:.65rem .75rem;border:1px dashed #b7c9b0;background:#f8fbf6}
.theme-color-label{font-weight:800;color:#2f3d2f;font-size:.88rem}
.theme-color-row{display:flex;align-items:center;gap:.45rem}
.theme-color-row input[type="color"]{width:42px;height:36px;padding:0;border:1px solid #c5d4be;background:#fff;cursor:pointer}
.theme-color-row input[type="text"]{flex:1;min-width:0;font-family:ui-monospace,Consolas,monospace;font-size:.88rem}
.theme-live-preview{position:sticky;top:.75rem;padding:.85rem;border:1px solid #d5e0cc;background:#f8fbf6}
.theme-preview-label{margin:0 0 .5rem;font-size:.72rem;font-weight:800;letter-spacing:.06em;text-transform:uppercase;color:#6a7a64}
.theme-preview-card{padding:.9rem;border:1px solid}
.theme-preview-card strong{display:block;font-size:1.1rem;margin-top:.2rem}
.theme-preview-actions{display:flex;flex-wrap:wrap;gap:.4rem}
.theme-preview-btn,.theme-preview-chip{display:inline-flex;align-items:center;justify-content:center;min-width:72px;height:36px;padding:0 10px;font-weight:800;font-size:.72rem}
.theme-preview-chip{border:1px solid}
.theme-preview-footer{margin-top:.65rem;padding:.55rem;color:#fff;font-weight:700;font-size:.75rem;text-align:center}
.theme-fonts{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:.85rem}
.theme-font-sample{margin-top:1rem;padding:1rem;border:1px solid #d5e0cc;background:#f8fbf6}
.theme-font-sample h3{margin:0 0 .35rem;font-size:1.35rem}
.theme-font-sample p{margin:0;color:#5f6d57}
.theme-text-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:.75rem}
.theme-text-field{display:grid;gap:.25rem;padding:.65rem .75rem;border:1px dashed #b7c9b0;background:#f8fbf6}
.theme-text-label{font-weight:800;color:#2f3d2f;font-size:.88rem}
.theme-text-field textarea{resize:vertical;min-height:2.5rem}
.theme-sticky-bar{display:flex;flex-wrap:wrap;gap:.55rem;margin-top:1.1rem;padding-top:.85rem;border-top:1px solid #d5e0cc;position:sticky;bottom:0;background:linear-gradient(to top,#fff 70%,rgba(255,255,255,0));padding-bottom:.35rem}
.theme-protect-list{display:grid;gap:.55rem}
.theme-toggle-field{display:flex;gap:.75rem;align-items:flex-start;padding:.9rem 1rem;border:1px dashed #b7c9b0;background:#f8fbf6;cursor:pointer}
.theme-toggle-field input{width:auto;margin-top:.2rem;accent-color:#2f6b3a}
.theme-toggle-field strong{display:block;color:#2f3d2f;margin-bottom:.2rem}
.admin-btn.ghost{background:transparent;color:#2f6b3a;box-shadow:inset 0 0 0 1.5px #2f6b3a}
@media (max-width:900px){.theme-layout-2{grid-template-columns:1fr}.theme-live-preview{position:static}}
</style>

<script>
(function () {
  document.querySelectorAll('[data-color-sync]').forEach((picker) => {
    const text = document.getElementById('theme-' + picker.getAttribute('data-color-sync'));
    if (!text) return;
    const syncPreview = () => {
      const card = document.querySelector('[data-theme-preview] .theme-preview-card');
      if (!card) return;
      const get = (k) => { const el = document.getElementById('theme-' + k); return el ? el.value : ''; };
      card.style.background = get('bg');
      card.style.color = get('ink');
      card.style.borderColor = get('line');
      const brand = card.querySelector('strong');
      if (brand) brand.style.color = get('brand');
      card.querySelectorAll('small, p').forEach((el) => { el.style.color = get('muted'); });
      const btn = card.querySelector('.theme-preview-btn');
      if (btn) { btn.style.background = get('btn'); btn.style.color = get('btn_text'); }
      const chip = card.querySelector('.theme-preview-chip');
      if (chip) { chip.style.background = get('surface'); chip.style.borderColor = get('line'); chip.style.color = get('ink'); }
      const foot = card.querySelector('.theme-preview-footer');
      if (foot) foot.style.background = get('footer_bg');
      const rad = document.querySelector('input[name="radius"]');
      if (rad) {
        const r = (parseInt(rad.value, 10) || 0) + 'px';
        card.style.borderRadius = r;
        if (btn) btn.style.borderRadius = r;
        if (chip) chip.style.borderRadius = r;
        if (foot) foot.style.borderRadius = r;
      }
    };
    picker.addEventListener('input', () => { text.value = picker.value; syncPreview(); });
    text.addEventListener('input', () => {
      if (/^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(text.value)) {
        picker.value = text.value.length === 4
          ? '#' + text.value[1]+text.value[1]+text.value[2]+text.value[2]+text.value[3]+text.value[3]
          : text.value;
      }
      syncPreview();
    });
    const rad = document.querySelector('input[name="radius"]');
    if (rad) rad.addEventListener('input', syncPreview);
  });
})();
</script>

<?php
admin_layout_end();

/** @param array<string,string> $theme */
function theme_hidden_style_fields(array $theme, array $colorFields): void
{
    foreach (array_keys($colorFields) as $key) {
        echo '<input type="hidden" name="' . e($key) . '" value="' . e($theme[$key]) . '">';
    }
    echo '<input type="hidden" name="radius" value="' . e((string) ($theme['radius'] ?? '18')) . '">';
}
