<?php
declare(strict_types=1);

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

require_admin();

$settings = settings_get();
$tab = trim((string) ($_GET['tab'] ?? 'genel'));
$allowedTabs = ['genel', 'gorunum', 'erisim', 'teknik'];
if (!in_array($tab, $allowedTabs, true)) {
    $tab = 'genel';
}

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

    $status = (($_POST['site_status'] ?? $prev['site_status'] ?? '') === 'off') ? 'off' : 'on';
    $device = (string) ($_POST['site_device_mode'] ?? $prev['site_device_mode'] ?? 'all');
    if (!in_array($device, ['all', 'mobile_only', 'desktop_only'], true)) {
        $device = 'all';
    }
    $redirect = array_key_exists('site_redirect_url', $_POST)
        ? trim((string) $_POST['site_redirect_url'])
        : (string) ($prev['site_redirect_url'] ?? '');
    if ($redirect !== '' && !preg_match('#^https?://#i', $redirect)) {
        flash('error', 'Yönlendirme linki http:// veya https:// ile başlamalı.');
        redirect(url('admin/ayarlar.php?tab=erisim'));
    }

    // Erişim sekmesinden gelirse checkbox; diğer sekmelerde önceki değer korunur
    if ($returnTab === 'erisim') {
        $hideSearch = !empty($_POST['hide_from_search']) ? '1' : '0';
    } else {
        $hideSearch = (string) ($prev['hide_from_search'] ?? '1');
    }

    $next = [
        'site_name' => trim((string) ($_POST['site_name'] ?? ($prev['site_name'] ?? ''))),
        'tagline' => trim((string) ($_POST['tagline'] ?? ($prev['tagline'] ?? ''))),
        'whatsapp' => preg_replace('/\D+/', '', (string) ($_POST['whatsapp'] ?? ($prev['whatsapp'] ?? ''))) ?? '',
        'support_note' => trim((string) ($_POST['support_note'] ?? ($prev['support_note'] ?? ''))),
        'iban' => $prev['iban'] ?? '',
        'bank' => $prev['bank'] ?? '',
        'account_name' => $prev['account_name'] ?? '',
        'site_logo' => (string) ($prev['site_logo'] ?? ''),
        'favicon' => (string) ($prev['favicon'] ?? ''),
        'footer_image' => (string) ($prev['footer_image'] ?? ''),
        'appstore_badge' => (string) ($prev['appstore_badge'] ?? ''),
        'playstore_badge' => (string) ($prev['playstore_badge'] ?? ''),
        'appstore_url' => trim((string) ($_POST['appstore_url'] ?? ($prev['appstore_url'] ?? ''))),
        'playstore_url' => trim((string) ($_POST['playstore_url'] ?? ($prev['playstore_url'] ?? ''))),
        'theme' => is_array($prev['theme'] ?? null) ? $prev['theme'] : [],
        'theme_copy' => is_array($prev['theme_copy'] ?? null) ? $prev['theme_copy'] : [],
        'site_status' => $status,
        'site_redirect_url' => $redirect,
        'site_device_mode' => $device,
        'hide_from_search' => $hideSearch,
        'og_share' => is_array($prev['og_share'] ?? null) ? $prev['og_share'] : og_share_defaults(),
        'tesseract_path' => trim((string) ($_POST['tesseract_path'] ?? ($prev['tesseract_path'] ?? ''))),
        'gemini_api_keys' => is_array($prev['gemini_api_keys'] ?? null) ? $prev['gemini_api_keys'] : [],
        'gemini_api_key' => (string) ($prev['gemini_api_key'] ?? ''),
    ];

    if (isset($_POST['gemini_api_keys'])) {
        $keys = gemini_api_keys_normalize($_POST['gemini_api_keys'] ?? '');
        $next['gemini_api_keys'] = $keys;
        $next['gemini_api_key'] = $keys[0] ?? '';
    } else {
        $keys = gemini_api_keys_normalize($prev['gemini_api_keys'] ?? ($prev['gemini_api_key'] ?? ''));
        $next['gemini_api_keys'] = $keys;
        $next['gemini_api_key'] = $keys[0] ?? '';
    }

    if (!empty($_POST['remove_logo'])) {
        $next['site_logo'] = '';
    }
    if (!empty($_FILES['site_logo']['name'])) {
        $saved = save_site_logo_upload($_FILES['site_logo']);
        if ($saved === false) {
            flash('error', 'Logo yüklenemedi. PNG/JPG dene.');
            redirect(url('admin/ayarlar.php?tab=gorunum'));
        }
        $next['site_logo'] = $saved;
    }

    if (!empty($_POST['remove_favicon'])) {
        $next['favicon'] = '';
    }
    if (!empty($_FILES['favicon']['name'])) {
        $saved = save_favicon_upload($_FILES['favicon']);
        if ($saved === false) {
            flash('error', 'Favicon yüklenemedi. ICO/PNG dene.');
            redirect(url('admin/ayarlar.php?tab=gorunum'));
        }
        $next['favicon'] = $saved;
    }

    if (!empty($_POST['remove_footer_image'])) {
        $next['footer_image'] = '';
    }
    if (!empty($_FILES['footer_image']['name'])) {
        $saved = save_footer_image_upload($_FILES['footer_image']);
        if ($saved === false) {
            flash('error', 'Footer resmi yüklenemedi. PNG/JPG dene.');
            redirect(url('admin/ayarlar.php?tab=gorunum'));
        }
        $next['footer_image'] = $saved;
    }

    if (!empty($_POST['remove_appstore_badge'])) {
        $next['appstore_badge'] = '';
    }
    if (!empty($_FILES['appstore_badge']['name'])) {
        $saved = save_app_badge_upload($_FILES['appstore_badge'], 'ios_');
        if ($saved === false) {
            flash('error', 'App Store rozeti yüklenemedi. PNG/JPG/SVG dene.');
            redirect(url('admin/ayarlar.php?tab=gorunum'));
        }
        $next['appstore_badge'] = $saved;
    }

    if (!empty($_POST['remove_playstore_badge'])) {
        $next['playstore_badge'] = '';
    }
    if (!empty($_FILES['playstore_badge']['name'])) {
        $saved = save_app_badge_upload($_FILES['playstore_badge'], 'android_');
        if ($saved === false) {
            flash('error', 'Google Play rozeti yüklenemedi. PNG/JPG/SVG dene.');
            redirect(url('admin/ayarlar.php?tab=gorunum'));
        }
        $next['playstore_badge'] = $saved;
    }

    if ($next['site_name'] === '') {
        flash('error', 'Site adı zorunlu.');
        redirect(url('admin/ayarlar.php?tab=genel'));
    }

    settings_save($next);
    flash('success', 'Site ayarları kaydedildi.');
    redirect(url('admin/ayarlar.php?tab=' . rawurlencode($returnTab)));
}

$logoUrl = site_logo_url();
$hasCustomLogo = trim((string) ($settings['site_logo'] ?? '')) !== '';
$faviconUrl = site_favicon_url();
$hasCustomFavicon = trim((string) ($settings['favicon'] ?? '')) !== '';
$footerImageUrl = site_footer_image_url();
$hasFooterImage = $footerImageUrl !== '';
$appstoreBadgeUrl = site_app_badge_url('ios');
$playstoreBadgeUrl = site_app_badge_url('play');
$hasAppstoreBadge = trim((string) ($settings['appstore_badge'] ?? '')) !== '';
$hasPlaystoreBadge = trim((string) ($settings['playstore_badge'] ?? '')) !== '';

$status = (($settings['site_status'] ?? 'on') === 'off') ? 'off' : 'on';
$device = (string) ($settings['site_device_mode'] ?? 'all');
$redirectUrl = (string) ($settings['site_redirect_url'] ?? '');
$hideFromSearch = (($settings['hide_from_search'] ?? '1') !== '0');

$keyList = gemini_api_keys();
$keysText = implode("\n", $keyList);

$tabs = [
    'genel' => 'Genel',
    'gorunum' => 'Görünüm',
    'erisim' => 'Erişim',
    'teknik' => 'Teknik',
];

admin_layout_start('Site Ayarları', 'settings');
?>

<section class="admin-panel settings-studio">
    <div class="settings-head">
        <div>
            <h2>Site ayarları</h2>
            <p class="hint">Kimlik, görünüm, erişim ve teknik ayarlar tek yerde. Tema / menü / paylaşım ayrı sayfalarda.</p>
        </div>
        <div class="settings-links">
            <a class="admin-btn ghost" href="<?= e(url('admin/tema.php')) ?>">Tema</a>
            <a class="admin-btn ghost" href="<?= e(url('admin/paylasim.php')) ?>">Paylaşım</a>
            <a class="admin-btn ghost" href="<?= e(url('admin/kontrol.php')) ?>">Sıfırlama</a>
        </div>
    </div>

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

    <form method="post" enctype="multipart/form-data" class="admin-form">
        <input type="hidden" name="tab" value="<?= e($tab) ?>">

        <?php if ($tab === 'genel'): ?>
            <h3 class="settings-subhead">Kimlik & iletişim</h3>
            <label>Site adı
                <input type="text" name="site_name" required value="<?= e($settings['site_name'] ?? '') ?>">
            </label>
            <label>Kısa açıklama
                <input type="text" name="tagline" value="<?= e($settings['tagline'] ?? '') ?>">
            </label>
            <label>Destek notu
                <textarea name="support_note" rows="2"><?= e($settings['support_note'] ?? '') ?></textarea>
            </label>
            <label>WhatsApp / satıcı telefonu (90…)
                <input type="text" name="whatsapp" value="<?= e($settings['whatsapp'] ?? '') ?>" placeholder="905xxxxxxxxx">
                <p class="hint">Tüm satıcılarda bu numara kullanılır. Sadece rakam (örn. 905xxxxxxxxx).</p>
            </label>
            <p class="hint">Ödeme IBAN’ı <a href="<?= e(url('admin/ibanlar.php')) ?>">IBAN</a> sayfasından yönetilir.</p>

        <?php elseif ($tab === 'gorunum'): ?>
            <input type="hidden" name="site_name" value="<?= e($settings['site_name'] ?? '') ?>">
            <h3 class="settings-subhead">Logo & ikonlar</h3>

            <div class="bank-logo-box">
                <p class="bank-logo-box-title">Site logosu (mobil üst bar)</p>
                <div class="bank-logo-preview">
                    <img src="<?= e($logoUrl) ?>" alt="Logo" style="max-height:40px;width:auto;background:#fff;padding:6px 10px;border-radius:8px;border:1px solid #d5e0cc">
                    <div>
                        <strong><?= $hasCustomLogo ? 'Yüklediğin logo' : 'Varsayılan logo' ?></strong>
                        <p class="hint" style="margin:0.2rem 0 0">PNG/JPG — mobilde menü ile arama arasında görünür.</p>
                    </div>
                </div>
                <label class="bank-logo-file">
                    <span>Logo seç / değiştir</span>
                    <input type="file" name="site_logo" accept="image/png,image/jpeg,image/webp,image/gif,image/svg+xml">
                </label>
                <?php if ($hasCustomLogo): ?>
                    <label style="display:flex;align-items:center;gap:0.45rem;font-weight:600;margin:0">
                        <input type="checkbox" name="remove_logo" value="1" style="width:auto">
                        Yüklenen logoyu kaldır
                    </label>
                <?php endif; ?>
            </div>

            <div class="bank-logo-box">
                <p class="bank-logo-box-title">Favicon (sekme ikonu)</p>
                <div class="bank-logo-preview">
                    <img src="<?= e($faviconUrl) ?>" alt="Favicon" style="width:32px;height:32px;object-fit:contain;background:#fff;padding:4px;border:1px solid #d5e0cc">
                    <div>
                        <strong><?= $hasCustomFavicon ? 'Yüklediğin favicon' : 'Varsayılan (logo)' ?></strong>
                        <p class="hint" style="margin:0.2rem 0 0">ICO veya PNG (32×32 / 64×64 önerilir).</p>
                    </div>
                </div>
                <label class="bank-logo-file">
                    <span>Favicon seç / değiştir (.ico / .png)</span>
                    <input type="file" name="favicon" accept=".ico,image/x-icon,image/vnd.microsoft.icon,image/png,image/jpeg,image/webp,image/gif,image/svg+xml">
                </label>
                <?php if ($hasCustomFavicon): ?>
                    <label style="display:flex;align-items:center;gap:0.45rem;font-weight:600;margin:0">
                        <input type="checkbox" name="remove_favicon" value="1" style="width:auto">
                        Yüklenen favicon’u kaldır
                    </label>
                <?php endif; ?>
            </div>

            <div class="bank-logo-box">
                <p class="bank-logo-box-title">Alt kısım doğa resmi (footer)</p>
                <div class="bank-logo-preview">
                    <?php if ($hasFooterImage): ?>
                        <img src="<?= e($footerImageUrl) ?>" alt="Footer" style="max-height:72px;width:auto;max-width:140px;object-fit:cover;background:#fff;padding:4px;border:1px solid #d5e0cc">
                    <?php else: ?>
                        <span style="display:inline-grid;place-items:center;width:72px;height:72px;background:#e8f0e4;border:1px dashed #b7c9b0;color:#7a8a72;font-size:0.7rem;text-align:center;padding:0.35rem">Resim yok</span>
                    <?php endif; ?>
                    <div>
                        <strong><?= $hasFooterImage ? 'Yüklediğin doğa resmi' : 'Henüz resim yok' ?></strong>
                        <p class="hint" style="margin:0.2rem 0 0">PNG/JPG — footer arka planı.</p>
                    </div>
                </div>
                <label class="bank-logo-file">
                    <span>Doğa resmi seç / değiştir</span>
                    <input type="file" name="footer_image" accept="image/png,image/jpeg,image/webp,image/gif">
                </label>
                <?php if ($hasFooterImage): ?>
                    <label style="display:flex;align-items:center;gap:0.45rem;font-weight:600;margin:0">
                        <input type="checkbox" name="remove_footer_image" value="1" style="width:auto">
                        Yüklenen footer resmini kaldır
                    </label>
                <?php endif; ?>
            </div>

            <h3 class="settings-subhead">Uygulama mağaza rozetleri</h3>
            <p class="hint">Yarın uygulama çıkınca rozet ve linki buradan güncelle.</p>

            <div class="bank-logo-box">
                <div class="bank-logo-preview">
                    <img src="<?= e($appstoreBadgeUrl) ?>" alt="App Store" style="height:40px;width:auto;background:#111;border:1px solid #d5e0cc">
                    <div><strong>App Store rozeti<?= $hasAppstoreBadge ? '' : ' (varsayılan)' ?></strong></div>
                </div>
                <label>App Store linki
                    <input type="url" name="appstore_url" value="<?= e($settings['appstore_url'] ?? '') ?>" placeholder="https://apps.apple.com/...">
                </label>
                <label class="bank-logo-file">
                    <span>App Store rozet resmi seç</span>
                    <input type="file" name="appstore_badge" accept="image/png,image/jpeg,image/webp,image/gif,image/svg+xml">
                </label>
                <?php if ($hasAppstoreBadge): ?>
                    <label style="display:flex;align-items:center;gap:0.45rem;font-weight:600;margin:0">
                        <input type="checkbox" name="remove_appstore_badge" value="1" style="width:auto">
                        Yüklenen App Store rozetini kaldır
                    </label>
                <?php endif; ?>

                <div class="bank-logo-preview" style="margin-top:0.75rem">
                    <img src="<?= e($playstoreBadgeUrl) ?>" alt="Google Play" style="height:40px;width:auto;background:#111;border:1px solid #d5e0cc">
                    <div><strong>Google Play rozeti<?= $hasPlaystoreBadge ? '' : ' (varsayılan)' ?></strong></div>
                </div>
                <label>Google Play linki
                    <input type="url" name="playstore_url" value="<?= e($settings['playstore_url'] ?? '') ?>" placeholder="https://play.google.com/store/apps/...">
                </label>
                <label class="bank-logo-file">
                    <span>Google Play rozet resmi seç</span>
                    <input type="file" name="playstore_badge" accept="image/png,image/jpeg,image/webp,image/gif,image/svg+xml">
                </label>
                <?php if ($hasPlaystoreBadge): ?>
                    <label style="display:flex;align-items:center;gap:0.45rem;font-weight:600;margin:0">
                        <input type="checkbox" name="remove_playstore_badge" value="1" style="width:auto">
                        Yüklenen Google Play rozetini kaldır
                    </label>
                <?php endif; ?>
            </div>

        <?php elseif ($tab === 'erisim'): ?>
            <input type="hidden" name="site_name" value="<?= e($settings['site_name'] ?? '') ?>">
            <h3 class="settings-subhead">Siteyi aç / kapat & cihaz</h3>
            <p class="hint">Kapalıyken veya yanlış cihazda ziyaretçi yönlendirme linkine gider. Panele giriş: <code>/temo</code></p>

            <label>Site durumu
                <select name="site_status">
                    <option value="on" <?= $status === 'on' ? 'selected' : '' ?>>Açık (aktif)</option>
                    <option value="off" <?= $status === 'off' ? 'selected' : '' ?>>Kapalı (sistem durduruldu)</option>
                </select>
            </label>

            <label>Cihaz görünürlüğü
                <select name="site_device_mode">
                    <option value="all" <?= $device === 'all' ? 'selected' : '' ?>>Herkes (mobil + PC)</option>
                    <option value="mobile_only" <?= $device === 'mobile_only' ? 'selected' : '' ?>>Sadece telefon (mobil)</option>
                    <option value="desktop_only" <?= $device === 'desktop_only' ? 'selected' : '' ?>>Sadece bilgisayar (PC)</option>
                </select>
                <p class="hint">Sadece mobil = gerçek telefon. Bilgisayar / emülatör kapalı kalır.</p>
            </label>

            <label>Yönlendirme linki
                <input type="url" name="site_redirect_url" value="<?= e($redirectUrl) ?>"
                       placeholder="https://ornek.com veya Instagram / WhatsApp linki">
                <p class="hint">Boş bırakılırsa ziyaretçi genel 404 görür.</p>
            </label>

            <label class="admin-reset-opt" style="margin:0.5rem 0 0">
                <input type="checkbox" name="hide_from_search" value="1" <?= $hideFromSearch ? 'checked' : '' ?>>
                <span>
                    <strong>Google'da görünmesin</strong>
                    <small>Sadece Google/Bing’e noindex. WhatsApp kartına engel olmaz.</small>
                </span>
            </label>

        <?php elseif ($tab === 'teknik'): ?>
            <input type="hidden" name="site_name" value="<?= e($settings['site_name'] ?? '') ?>">
            <h3 class="settings-subhead">Dekont kontrolü (OCR)</h3>
            <p class="hint">
                Dekontlar <strong>müşterinin tarayıcısında</strong> okunur (Tesseract.js) — sunucuya program kurmana gerek yok, Gemini kullanılmaz.
                <?php if (function_exists('tesseract_available') && tesseract_available()): ?>
                    <br><strong style="color:#2f6b3a">Sunucu Tesseract da bulundu (yedek okuma).</strong>
                <?php endif; ?>
            </p>
            <label>Sunucu Tesseract yolu (opsiyonel yedek)
                <input type="text" name="tesseract_path" value="<?= e((string) ($settings['tesseract_path'] ?? '')) ?>"
                       placeholder="Boş bırakabilirsiniz — tarayıcı OCR yeterli">
                <p class="hint">Sadece yedek içindir. Normal kullanımda kurulum gerekmez.</p>
            </label>

            <h3 class="settings-subhead">Yapay zeka (yorum)</h3>
            <p class="hint">
                Sadece ürün yorumları için. Dekont kontrolünde kullanılmaz.
                <a href="https://aistudio.google.com/apikey" target="_blank" rel="noopener">Gemini API key al</a>
                — her satıra bir anahtar.
            </p>
            <label>Gemini API Key’leri
                <textarea name="gemini_api_keys" rows="<?= max(3, min(8, count($keyList) + 1)) ?>"
                          placeholder="AIza...birinci&#10;AIza...ikinci"
                          autocomplete="off" spellcheck="false"
                          style="font-family:ui-monospace,Consolas,monospace;font-size:0.85rem"><?= e($keysText) ?></textarea>
                <p class="hint"><?= count($keyList) ?> anahtar kayıtlı. Üstteki önce denenir.</p>
            </label>
        <?php endif; ?>

        <div class="settings-actions">
            <button class="admin-btn" type="submit">Kaydet</button>
        </div>
    </form>
</section>

<style>
.settings-head {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  gap: 0.75rem;
  align-items: flex-start;
  margin-bottom: 0.75rem;
}
.settings-head h2 { margin: 0 0 0.25rem; }
.settings-links { display: flex; flex-wrap: wrap; gap: 0.45rem; }
.settings-tabs {
  display: flex;
  flex-wrap: wrap;
  gap: 0.35rem;
  margin: 0 0 1rem;
  padding-bottom: 0.75rem;
  border-bottom: 1px solid #d5e0cc;
}
.settings-tab {
  display: inline-flex;
  align-items: center;
  padding: 0.45rem 0.75rem;
  font-size: 0.82rem;
  font-weight: 700;
  color: #3d4f3a;
  background: #f3f7f1;
  border: 1px solid #d5e0cc;
  text-decoration: none;
}
.settings-tab:hover { background: #e8f0e4; }
.settings-tab.is-active {
  background: #2f6b3a;
  border-color: #2f6b3a;
  color: #fff;
}
.settings-subhead {
  margin: 0.35rem 0 0.65rem;
  font-size: 0.95rem;
  color: #2f3d2f;
}
.settings-actions {
  display: flex;
  gap: 0.55rem;
  margin-top: 1rem;
  padding-top: 0.85rem;
  border-top: 1px solid #d5e0cc;
}
.admin-btn.ghost {
  background: transparent;
  color: #2f6b3a;
  box-shadow: inset 0 0 0 1.5px #2f6b3a;
}
.admin-reset-opt {
  display: flex !important;
  align-items: flex-start;
  gap: 0.65rem;
  padding: 0.75rem 0.85rem;
  border: 1px solid #d5e0cc;
  background: #fbfdf9;
  font-weight: 600 !important;
  cursor: pointer;
}
.admin-reset-opt input { width: auto !important; margin-top: 0.15rem; }
.admin-reset-opt span { display: grid; gap: 0.15rem; }
.admin-reset-opt small { color: #6b7864; font-weight: 500; }
.admin-reset-opt:has(input:checked) {
  border-color: #2f6b3a;
  background: #f3f8f2;
}
</style>

<?php admin_layout_end(); ?>
