<?php
/**
 * Admin Genel Site Ayarları
 * Konum: /magaza/admin/ayarlar/index.php
 */

require_once '../../includes/db.php';
require_once '../../includes/functions.php';

/**
 * GÜVENLİK KONTROLÜ
 */
adminCheck();

$mesaj = '';

// --- AYARLARI ÇEK ---
$stmt = $db->query("SELECT * FROM settings WHERE id = 1");
$ayar = $stmt->fetch();

// Eğer tabloda veri yoksa boş bir dizi oluştur (Hata almamak için)
if (!$ayar) {
    $db->query("INSERT INTO settings (id, title) VALUES (1, 'Sınav Koçu Mağaza')");
    $ayar = $db->query("SELECT * FROM settings WHERE id = 1")->fetch();
}

// --- GÜNCELLEME İŞLEMİ ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['ayarlar_guncelle'])) {
    $title = trim($_POST['title']);
    $description = trim($_POST['description']);
    $keywords = trim($_POST['keywords']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $address = trim($_POST['address']);
    $facebook = trim($_POST['facebook']);
    $instagram = trim($_POST['instagram']);
    
    // YENİ: STANDART ÜRÜN ŞABLONLARI
    $default_payment_text = trim($_POST['default_payment_text']);
    $default_delivery_text = trim($_POST['default_delivery_text']);
    
    $logo_path = $ayar['logo']; // Mevcut logo kalsın

    // Logo Yükleme İşlemi
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
        $izin_verilenler = ['jpg', 'jpeg', 'png', 'webp', 'svg'];
        
        if (in_array($ext, $izin_verilenler)) {
            $yeni_logo_adi = 'logo-' . time() . '.' . $ext;
            $hedef = '../../uploads/' . $yeni_logo_adi;
            
            if (move_uploaded_file($_FILES['logo']['tmp_name'], $hedef)) {
                // Eski logoyu sil (Eğer varsa ve varsayılan değilse)
                if ($ayar['logo'] && file_exists('../../' . $ayar['logo'])) {
                    unlink('../../' . $ayar['logo']);
                }
                $logo_path = 'uploads/' . $yeni_logo_adi;
            }
        }
    }

    try {
        // SQL Sorgusuna yeni eklenen sütunlar dahil edildi
        $sql = "UPDATE settings SET 
                title = ?, description = ?, keywords = ?, 
                email = ?, phone = ?, address = ?, 
                facebook = ?, instagram = ?, logo = ?,
                default_payment_text = ?, default_delivery_text = ?
                WHERE id = 1";
        $upd = $db->prepare($sql);
        $upd->execute([
            $title, $description, $keywords, 
            $email, $phone, $address, 
            $facebook, $instagram, $logo_path,
            $default_payment_text, $default_delivery_text
        ]);
        
        $mesaj = "<div class='alert alert-success shadow-sm'><i class='bi bi-check-circle-fill me-2'></i> Ayarlar başarıyla güncellendi!</div>";
        // Veriyi tazele
        $ayar = $db->query("SELECT * FROM settings WHERE id = 1")->fetch();
    } catch (Exception $e) {
        $mesaj = "<div class='alert alert-danger shadow-sm'>Hata: " . $e->getMessage() . "</div>";
    }
}

// YENİ YAPI: Header bir üst klasörde
require_once '../header.php';
?>

<div class="row mb-4 align-items-center">
    <div class="col-md-6">
        <h2 class="fw-bold mb-0 text-dark"><i class="bi bi-gear-wide-connected text-secondary me-2"></i>Genel Ayarlar</h2>
        <p class="text-muted small mb-0">Sitenizin başlık, logo, iletişim ve standart şablon bilgilerini buradan düzenleyin.</p>
    </div>
</div>

<?= $mesaj; ?>

<form action="index.php" method="POST" enctype="multipart/form-data">
    <div class="row">
        <div class="col-lg-8">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-dark text-white py-3">
                    <h5 class="card-title mb-0 fw-bold small text-uppercase"><i class="bi bi-info-circle me-2"></i>Site Kimliği (SEO)</h5>
                </div>
                <div class="card-body p-4">
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Site Başlığı (Title)</label>
                        <input type="text" name="title" class="form-control border-2" value="<?= htmlspecialchars($ayar['title'] ?? '') ?>" placeholder="Örn: Sınav Koçu - LGS ve YKS Hazırlık Mağazası">
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Site Açıklaması (Meta Description)</label>
                        <textarea name="description" class="form-control border-2" rows="3"><?= htmlspecialchars($ayar['description'] ?? '') ?></textarea>
                    </div>

                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Anahtar Kelimeler (Meta Keywords)</label>
                        <input type="text" name="keywords" class="form-control border-2" value="<?= htmlspecialchars($ayar['keywords'] ?? '') ?>" placeholder="kitap, lgs deneme, yks hazırlık">
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0 mb-4 border-start border-4 border-primary">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-secondary small text-uppercase"><i class="bi bi-card-text me-2 text-primary"></i>Standart Ürün Şablonları</h5>
                </div>
                <div class="card-body p-4">
                    <div class="alert alert-info py-2 mb-4" style="font-size: 0.85rem;">
                        <i class="bi bi-info-circle-fill me-1"></i> <b>Bilgi:</b> Ürün eklerken "Özel Sekme İçerikleri" boş bırakılırsa, ürün detay sayfalarındaki sekmelerde otomatik olarak buradaki standart şablonlar gösterilir.
                    </div>
                    
                    <div class="mb-4">
                        <label class="form-label fw-bold text-muted small text-uppercase">Genel Ödeme Seçenekleri Metni</label>
                        <textarea name="default_payment_text" class="form-control editor border-2" rows="4" placeholder="Sitenizin güvenli ödeme seçeneklerini detaylandırın..."><?= htmlspecialchars($ayar['default_payment_text'] ?? '') ?></textarea>
                    </div>
                    
                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Genel Teslimat & İade Şartları</label>
                        <textarea name="default_delivery_text" class="form-control editor border-2" rows="4" placeholder="Sitenizin standart kargo ve iade süreçlerini anlatın..."><?= htmlspecialchars($ayar['default_delivery_text'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-secondary small text-uppercase"><i class="bi bi-geo-alt me-2 text-danger"></i>İletişim Bilgileri</h5>
                </div>
                <div class="card-body p-4">
                    <div class="row mb-4">
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">E-Posta Adresi</label>
                            <input type="email" name="email" class="form-control border-2" value="<?= htmlspecialchars($ayar['email'] ?? '') ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold text-muted small text-uppercase">Telefon Numarası</label>
                            <input type="text" name="phone" class="form-control border-2" value="<?= htmlspecialchars($ayar['phone'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-bold text-muted small text-uppercase">Fiziksel Adres</label>
                        <textarea name="address" class="form-control border-2" rows="3"><?= htmlspecialchars($ayar['address'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-secondary small text-uppercase"><i class="bi bi-image me-2 text-primary"></i>Site Logosu</h5>
                </div>
                <div class="card-body p-4 text-center">
                    <div class="mb-3 p-3 border rounded bg-light">
                        <?php if($ayar['logo']): ?>
                            <img src="/magaza/<?= $ayar['logo'] ?>" class="img-fluid" style="max-height: 80px;" alt="Site Logosu">
                        <?php else: ?>
                            <span class="text-muted small">Henüz logo yüklenmedi.</span>
                        <?php endif; ?>
                    </div>
                    <input type="file" name="logo" class="form-control form-control-sm border-2" accept="image/*">
                    <div class="form-text small mt-2">Şeffaf PNG veya SVG tavsiye edilir.</div>
                </div>
            </div>

            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="card-title mb-0 fw-bold text-secondary small text-uppercase"><i class="bi bi-share me-2 text-info"></i>Sosyal Medya</h5>
                </div>
                <div class="card-body p-4">
                    <div class="mb-3">
                        <label class="form-label fw-bold small">Instagram URL</label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="bi bi-instagram text-danger"></i></span>
                            <input type="text" name="instagram" class="form-control" value="<?= htmlspecialchars($ayar['instagram'] ?? '') ?>">
                        </div>
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-bold small">Facebook URL</label>
                        <div class="input-group">
                            <span class="input-group-text bg-white"><i class="bi bi-facebook text-primary"></i></span>
                            <input type="text" name="facebook" class="form-control" value="<?= htmlspecialchars($ayar['facebook'] ?? '') ?>">
                        </div>
                    </div>
                </div>
            </div>

            <button type="submit" name="ayarlar_guncelle" class="btn btn-primary btn-lg w-100 fw-bold shadow">
                <i class="bi bi-save2 me-2"></i> TÜM AYARLARI KAYDET
            </button>
        </div>
    </div>
</form>

<script src="https://cdn.tiny.cloud/1/vrj5aef2zvyqm82vfs8ay0ltvq1l9v6bmkio7ovzkqj8trrq/tinymce/6/tinymce.min.js" referrerpolicy="origin"></script>
<script>
    tinymce.init({
        selector: '.editor',
        height: 250,
        menubar: false,
        plugins: 'lists link table code wordcount',
        toolbar: 'undo redo | formatselect | bold italic textcolor | alignleft aligncenter alignright alignjustify | bullist numlist | removeformat',
        language: 'tr' // Türkçe arayüz
    });
</script>

<?php require_once '../footer.php'; ?>