<?php
session_start();
require_once 'system/db.php';

// Güvenlik
if (!isset($_SESSION['is_logged_in']) || $_SESSION['is_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

// 1. KATEGORİLERİ VERİTABANINDAN ÇEK
$kategoriler = $db->query("SELECT * FROM faq_categories ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);

// Aktif Kategori (URL'den al, yoksa ilk kategoriyi seç)
$first_cat_id = $kategoriler[0]['id'];
$aktif_kat_id = isset($_GET['cat']) ? intval($_GET['cat']) : $first_cat_id;

// Aktif kategorinin adını bul (Başlıkta yazmak için)
$aktif_kat_baslik = "Liste";
foreach($kategoriler as $k) { if($k['id'] == $aktif_kat_id) { $aktif_kat_baslik = $k['title']; break; } }

$mesaj = "";
$mesaj_tur = "";

// 2. SIRALAMA GÜNCELLEME
if (isset($_POST['update_order']) && isset($_POST['sira'])) {
    foreach ($_POST['sira'] as $id => $sira) {
        $db->query("UPDATE faqs SET sort_order = ".intval($sira)." WHERE id = ".intval($id));
    }
    $mesaj = "Sıralama güncellendi.";
    $mesaj_tur = "success";
}

// 3. YENİ SORU EKLEME
if (isset($_POST['add_new'])) {
    $cat = intval($_POST['category']);
    $question = trim($_POST['question']);
    $answer = trim($_POST['answer']);
    $sort_order = intval($_POST['sort_order']);

    if (!empty($question) && !empty($answer)) {
        $stmt = $db->prepare("INSERT INTO faqs (category, question, answer, sort_order) VALUES (?, ?, ?, ?)");
        if ($stmt->execute([$cat, $question, $answer, $sort_order])) {
            $mesaj = "Soru eklendi.";
            $mesaj_tur = "success";
            header("Location: faq.php?cat=$cat"); exit;
        }
    }
}

// 4. SİLME İŞLEMİ
if (isset($_GET['del'])) {
    $id = intval($_GET['del']);
    $db->query("DELETE FROM faqs WHERE id = $id");
    header("Location: faq.php?cat=$aktif_kat_id"); exit;
}

// LİSTEYİ ÇEK (Sadece Aktif Kategori)
$sorular = $db->query("SELECT * FROM faqs WHERE category = '$aktif_kat_id' ORDER BY sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="tr" data-theme="light">
<?php include 'inc/header.php'; ?>
<body>
    <?php include 'inc/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'inc/navbar.php'; ?>
        
        <div class="dashboard-main-body">
            
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Sıkça Sorulan Sorular</h6>
                <div class="d-flex gap-2">
                    <a href="faq-categories.php" class="btn btn-outline-primary py-2 px-3 radius-8 d-flex align-items-center gap-2">
                        <iconify-icon icon="solar:settings-outline"></iconify-icon> Kategorileri Düzenle
                    </a>
                </div>
            </div>

            <div class="card radius-12 border-0 mb-4 shadow-sm">
                <div class="card-body p-16">
                    <ul class="nav nav-pills d-flex gap-2 flex-wrap">
                        <?php foreach($kategoriler as $kat): ?>
                            <?php $isActive = ($kat['id'] == $aktif_kat_id) ? 'active bg-primary-600 text-white' : 'bg-base text-secondary-light border'; ?>
                            <li class="nav-item flex-grow-1 flex-md-grow-0">
                                <a href="?cat=<?php echo $kat['id']; ?>" class="nav-link w-100 d-flex align-items-center justify-content-center justify-content-md-start gap-2 px-16 py-10 radius-8 fw-medium <?php echo $isActive; ?>">
                                    <iconify-icon icon="<?php echo $kat['icon']; ?>" class="text-xl"></iconify-icon>
                                    <?php echo $kat['title']; ?>
                                </a>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>

            <?php if($mesaj != ""): ?>
                <div class="alert alert-<?php echo $mesaj_tur; ?> d-flex align-items-center gap-2 border-0 radius-8 px-16 py-12 mb-24 shadow-sm">
                    <iconify-icon icon="lucide:check-circle" class="text-xl"></iconify-icon>
                    <p class="mb-0 text-sm"><?php echo $mesaj; ?></p>
                </div>
            <?php endif; ?>

            <div class="row gy-4">
                
                <div class="col-lg-4">
                    <div class="card h-100 p-0 radius-12">
                        <div class="card-header border-bottom bg-base py-16 px-24">
                            <h6 class="text-lg fw-semibold mb-0">Soru Ekle</h6>
                        </div>
                        <div class="card-body p-24">
                            <form action="" method="POST">
                                <input type="hidden" name="add_new" value="1">
                                
                                <div class="mb-3">
                                    <label class="form-label text-sm fw-semibold">Kategori</label>
                                    <select name="category" class="form-control radius-8">
                                        <?php foreach($kategoriler as $kat): ?>
                                            <option value="<?php echo $kat['id']; ?>" <?php echo ($kat['id'] == $aktif_kat_id) ? 'selected' : ''; ?>>
                                                <?php echo $kat['title']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label text-sm fw-semibold">Sıra No</label>
                                    <input type="number" name="sort_order" class="form-control radius-8" value="0">
                                </div>
                                <div class="mb-3">
                                    <label class="form-label text-sm fw-semibold">Soru Başlığı</label>
                                    <input type="text" name="question" class="form-control radius-8" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label text-sm fw-semibold">Cevap</label>
                                    <textarea name="answer" class="form-control radius-8" rows="5" required></textarea>
                                </div>
                                <button type="submit" class="btn btn-primary w-100 radius-8">Kaydet</button>
                            </form>
                        </div>
                    </div>
                </div>

                <div class="col-lg-8">
                    <div class="card h-100 p-0 radius-12">
                        <div class="card-header border-bottom bg-base py-16 px-24">
                            <h6 class="text-lg fw-semibold mb-0"><?php echo htmlspecialchars($aktif_kat_baslik); ?> Listesi</h6>
                        </div>
                        <div class="card-body p-24">
                            
                            <form action="" method="POST">
                                <div class="accordion" id="faqList">
                                    <?php if(count($sorular) > 0): ?>
                                        <?php foreach($sorular as $s): ?>
                                        
                                        <div class="accordion-item radius-8 mb-16 border-0 overflow-hidden bg-base border">
                                            <h2 class="accordion-header" id="heading<?php echo $s['id']; ?>">
                                                <div class="accordion-button collapsed bg-transparent text-primary-light fw-medium d-flex align-items-center gap-3 shadow-none">
                                                    
                                                    <input type="number" name="sira[<?php echo $s['id']; ?>]" value="<?php echo $s['sort_order']; ?>" 
                                                           class="form-control text-center px-1" 
                                                           style="width: 60px; height: 35px; background: #fff;" 
                                                           onclick="event.stopPropagation();">
                                                    
                                                    <span class="flex-grow-1" data-bs-toggle="collapse" data-bs-target="#collapse<?php echo $s['id']; ?>" style="cursor: pointer;">
                                                        <?php echo htmlspecialchars($s['question']); ?>
                                                    </span>

                                                </div>
                                            </h2>
                                            <div id="collapse<?php echo $s['id']; ?>" class="accordion-collapse collapse" data-bs-parent="#faqList">
                                                <div class="accordion-body text-secondary-light text-sm pt-0">
                                                    <?php echo nl2br(htmlspecialchars($s['answer'])); ?>
                                                    <div class="mt-3 text-end border-top pt-2">
                                                        <a href="?del=<?php echo $s['id']; ?>&cat=<?php echo $aktif_kat_id; ?>" onclick="return confirm('Silmek istiyor musunuz?')" class="text-danger-main text-sm fw-medium">Sil</a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <?php endforeach; ?>

                                        <div class="d-flex justify-content-end mt-24">
                                            <button type="submit" name="update_order" class="btn btn-success px-24 py-12 radius-8 d-flex align-items-center gap-2">
                                                <iconify-icon icon="solar:refresh-circle-outline" class="text-xl"></iconify-icon>
                                                Sıralamayı Güncelle
                                            </button>
                                        </div>

                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <iconify-icon icon="solar:folder-with-files-outline" class="text-4xl text-secondary-light mb-2"></iconify-icon>
                                            <p class="text-secondary">Bu kategoride henüz soru yok.</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </form>

                        </div>
                    </div>
                </div>

            </div>
        </div>
        <?php include 'inc/copyright.php'; ?>
    </main>
    <?php include 'inc/footer.php'; ?>
</body>
</html>