<?php
// admin/denemesonuc/konular.php
require_once '../../includes/db.php';
require_once '../header.php';

$mesaj = "";
$mesaj_turu = "";

// --- 1. SİLME İŞLEMİ ---
if (isset($_GET['sil'])) {
    $id = intval($_GET['sil']);
    $stmt = $db->prepare("DELETE FROM konular WHERE id = ?");
    if ($stmt->execute([$id])) {
        $mesaj = "Konu başarıyla silindi.";
        $mesaj_turu = "success";
    }
}

// --- 2. EKLEME VE GÜNCELLEME İŞLEMİ ---
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $brans = trim($_POST['brans']);
    $ders  = trim($_POST['ders']);
    $konu  = trim($_POST['konu']);
    
    // Eğer Branş veya Ders için "YENİ" seçilip input doldurulmuşsa onu al
    if($brans == "YENI_BRANS" && !empty($_POST['yeni_brans'])) $brans = trim($_POST['yeni_brans']);
    if($ders == "YENI_DERS" && !empty($_POST['yeni_ders'])) $ders = trim($_POST['yeni_ders']);

    if (isset($_POST['konu_id']) && !empty($_POST['konu_id'])) {
        $id = intval($_POST['konu_id']);
        $stmt = $db->prepare("UPDATE konular SET brans = ?, ders = ?, konu = ? WHERE id = ?");
        $stmt->execute([$brans, $ders, $konu, $id]);
        $mesaj = "Konu başarıyla güncellendi.";
    } else {
        $stmt = $db->prepare("INSERT INTO konular (brans, ders, konu) VALUES (?, ?, ?)");
        $stmt->execute([$brans, $ders, $konu]);
        $mesaj = "Yeni konu başarıyla eklendi.";
    }
    $mesaj_turu = "success";
}

// --- 3. VERİLERİ ÇEK VE GRUPLA ---
$tum_konular = $db->query("SELECT * FROM konular ORDER BY brans ASC, ders ASC, konu ASC")->fetchAll(PDO::FETCH_ASSOC);

$duzenli_liste = [];
$brans_ders_mapping = []; 

foreach ($tum_konular as $k) {
    $br = $k['brans'] ?: 'Genel';
    $duzenli_liste[$br][$k['ders']][] = $k;
    
    if (!isset($brans_ders_mapping[$br])) {
        $brans_ders_mapping[$br] = [];
    }
    if (!in_array($k['ders'], $brans_ders_mapping[$br])) {
        $brans_ders_mapping[$br][] = $k['ders'];
    }
}
$branslar = array_keys($duzenli_liste);
?>

<style>
    /* Üst Sekme (Tab) Görünürlük Ayarları - Beyazlık Sorunu Çözümü */
    #bransTab .nav-link {
        color: #3e5569 !important;
        background-color: #f1f3f5 !important;
        border: 1px solid #d1d9e6;
        margin-right: 5px;
        font-weight: 700;
        border-radius: 5px 5px 0 0;
        padding: 10px 20px;
    }
    #bransTab .nav-link.active {
        color: #ffffff !important;
        background-color: #2255a4 !important;
        border-color: #2255a4;
    }
    #bransTab .nav-link:hover:not(.active) {
        background-color: #e2e6ea !important;
    }
    .accordion-button:not(.collapsed) {
        background-color: #e8f0fe;
        color: #2255a4;
    }
</style>

<div class="page-wrapper">
    <div class="page-breadcrumb">
        <div class="row">
            <div class="col-12 d-flex no-block align-items-center">
                <h4 class="page-title"><i class="mdi mdi-format-list-bulleted-type text-primary"></i> Konu Havuzu Yönetimi</h4>
                <div class="ms-auto text-end">
                    <a href="index.php" class="btn btn-dark btn-sm rounded-pill px-3 me-2">
                        <i class="mdi mdi-view-dashboard"></i> Geri Dön
                    </a>
                    <button type="button" class="btn btn-success btn-sm rounded-pill px-3" data-bs-toggle="modal" data-bs-target="#konuModal" onclick="yeniKonuFormu()">
                        <i class="mdi mdi-plus"></i> Yeni Konu Ekle
                    </button>
                </div>
            </div>
        </div>
    </div>

    <div class="container-fluid">
        <?php if ($mesaj): ?>
            <div class="alert alert-<?= $mesaj_turu ?> alert-dismissible fade show shadow-sm" role="alert">
                <i class="mdi mdi-check-circle me-2"></i> <?= $mesaj ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <div class="card shadow-sm border-0 rounded-3">
            <div class="card-body">
                <ul class="nav nav-tabs" id="bransTab" role="tablist">
                    <?php foreach ($branslar as $index => $b_adi): ?>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link <?= $index === 0 ? 'active' : '' ?>" id="tab-<?= $index ?>" data-bs-toggle="tab" data-bs-target="#content-<?= $index ?>" type="button" role="tab">
                                <?= $b_adi ?>
                            </button>
                        </li>
                    <?php endforeach; ?>
                </ul>

                <div class="tab-content border border-top-0 p-3 bg-white" id="bransTabContent">
                    <?php foreach ($branslar as $index => $b_adi): ?>
                        <div class="tab-pane fade <?= $index === 0 ? 'show active' : '' ?>" id="content-<?= $index ?>" role="tabpanel">
                            
                            <div class="accordion accordion-flush" id="accordion-<?= $index ?>">
                                <?php 
                                $dersler = $duzenli_liste[$b_adi] ?? [];
                                $d_idx = 0;
                                foreach ($dersler as $d_adi => $konu_listesi): 
                                    $accId = "acc-".$index."-".$d_idx;
                                ?>
                                    <div class="accordion-item border mb-2 rounded shadow-none">
                                        <h2 class="accordion-header">
                                            <button class="accordion-button collapsed fw-bold text-dark bg-light" type="button" data-bs-toggle="collapse" data-bs-target="#<?= $accId ?>">
                                                <?= $d_adi ?> <span class="badge bg-secondary ms-2 opacity-75"><?= count($konu_listesi) ?> Konu</span>
                                            </button>
                                        </h2>
                                        <div id="<?= $accId ?>" class="accordion-collapse collapse" data-bs-parent="#accordion-<?= $index ?>">
                                            <div class="accordion-body p-3">
                                                
                                                <div class="d-flex justify-content-between align-items-center mb-3">
                                                    <h6 class="mb-0 text-muted small fw-bold"><?= $d_adi ?> - Konu Listesi</h6>
                                                    <button type="button" class="btn btn-outline-success btn-sm fw-bold px-3" onclick="yeniKonuFormu('<?= addslashes($b_adi) ?>', '<?= addslashes($d_adi) ?>')">
                                                        <i class="mdi mdi-plus-circle"></i> Bu Derse Konu Ekle
                                                    </button>
                                                </div>

                                                <table class="table table-sm table-hover mb-0 border">
                                                    <thead class="table-light">
                                                        <tr>
                                                            <th class="ps-3">Konu Başlığı</th>
                                                            <th width="150" class="text-center">İşlemler</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <?php foreach ($konu_listesi as $k_item): ?>
                                                            <tr>
                                                                <td class="ps-3 align-middle"><?= htmlspecialchars($k_item['konu']) ?></td>
                                                                <td class="text-center align-middle">
                                                                    <button type="button" class="btn btn-cyan btn-sm text-black" onclick='duzenle(<?= json_encode($k_item) ?>)' title="Düzenle">
                                                                        <i class="bi bi-pencil-fill text-warning"></i>
                                                                    </button>
                                                                    <a href="?sil=<?= $k_item['id'] ?>" class="btn btn-black btn-sm text-white" onclick="return confirm('Bu konu silinecek, onaylıyor musunuz?')" title="Sil">
                                                                        <i class="bi bi-trash-fill text-danger"></i>
                                                                    </a>
                                                                </td>
                                                            </tr>
                                                        <?php endforeach; ?>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>
                                    </div>
                                <?php $d_idx++; endforeach; ?>
                            </div>

                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="konuModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form action="" method="POST" class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalBaslik"><i class="mdi mdi-plus-circle me-2"></i>Yeni Konu Ekle</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="konu_id" id="form_konu_id">
                
                <div class="mb-3">
                    <label class="form-label fw-bold">1. Sınav Türü (Branş)</label>
                    <select name="brans" id="form_brans" class="form-select border-primary" required onchange="handleBransChange(this.value)">
                        <option value="">-- Branş Seçin --</option>
                        <?php foreach($branslar as $b) echo "<option value='$b'>$b</option>"; ?>
                        <option value="YENI_BRANS" class="text-primary fw-bold">+ Yeni Branş Ekle</option>
                    </select>
                    <input type="text" name="yeni_brans" id="yeni_brans_input" class="form-control mt-2" placeholder="Yeni Branş Adı Yazın" style="display:none;">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold">2. Ders Adı</label>
                    <select name="ders" id="form_ders" class="form-select border-primary" required onchange="handleDersChange(this.value)">
                        <option value="">-- Önce Branş Seçin --</option>
                    </select>
                    <input type="text" name="yeni_ders" id="yeni_ders_input" class="form-control mt-2" placeholder="Yeni Ders Adı Yazın" style="display:none;">
                </div>

                <div class="mb-3">
                    <label class="form-label fw-bold text-danger">3. Konu Adı</label>
                    <textarea name="konu" id="form_konu" class="form-control border-danger" rows="3" placeholder="Konuyu yazın..." required></textarea>
                </div>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Kapat</button>
                <button type="submit" class="btn btn-primary px-4"><i class="mdi mdi-content-save me-1"></i>Kaydet</button>
            </div>
        </form>
    </div>
</div>

<script>
const branchMapping = <?= json_encode($brans_ders_mapping) ?>;

function handleBransChange(val) {
    const input = document.getElementById('yeni_brans_input');
    if(val === 'YENI_BRANS') {
        input.style.display = 'block';
        input.required = true;
    } else {
        input.style.display = 'none';
        input.required = false;
    }
    updateDersDropdown(val);
}

function handleDersChange(val) {
    const input = document.getElementById('yeni_ders_input');
    if(val === 'YENI_DERS') {
        input.style.display = 'block';
        input.required = true;
    } else {
        input.style.display = 'none';
        input.required = false;
    }
}

function updateDersDropdown(selectedBranch, selectedDers = '') {
    const dersSelect = document.getElementById('form_ders');
    dersSelect.innerHTML = '<option value="">-- Ders Seçin --</option>';
    
    if (selectedBranch && branchMapping[selectedBranch]) {
        branchMapping[selectedBranch].forEach(ders => {
            const option = document.createElement('option');
            option.value = ders;
            option.text = ders;
            if(ders === selectedDers) option.selected = true;
            dersSelect.appendChild(option);
        });
    }
    
    const yeniOpt = document.createElement('option');
    yeniOpt.value = "YENI_DERS";
    yeniOpt.text = "+ Yeni Ders Ekle";
    yeniOpt.className = "text-success fw-bold";
    if(selectedDers === 'YENI_DERS') yeniOpt.selected = true;
    dersSelect.appendChild(yeniOpt);
}

function yeniKonuFormu(brans = '', ders = '') {
    document.getElementById('modalBaslik').innerHTML = '<i class="mdi mdi-plus-circle me-2"></i>Yeni Konu Ekle';
    document.getElementById('form_konu_id').value = "";
    document.getElementById('form_brans').value = brans;
    document.getElementById('yeni_brans_input').style.display = 'none';
    document.getElementById('yeni_ders_input').style.display = 'none';
    
    updateDersDropdown(brans, ders);
    document.getElementById('form_konu').value = "";
    
    var myModal = new bootstrap.Modal(document.getElementById('konuModal'));
    myModal.show();
}

function duzenle(data) {
    document.getElementById('modalBaslik').innerHTML = '<i class="mdi mdi-pencil me-2"></i>Konuyu Düzenle';
    document.getElementById('form_konu_id').value = data.id;
    document.getElementById('form_brans').value = data.brans;
    document.getElementById('yeni_brans_input').style.display = 'none';
    document.getElementById('yeni_ders_input').style.display = 'none';
    
    updateDersDropdown(data.brans, data.ders);
    document.getElementById('form_konu').value = data.konu;
    
    var myModal = new bootstrap.Modal(document.getElementById('konuModal'));
    myModal.show();
}
</script>

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