<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
checkAdmin();

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add_rule') {
            $kode = $_POST['kode'];
            $id_diagnosa = $_POST['id_diagnosa'];
            $tipe = $_POST['tipe'];
            $deskripsi = $_POST['deskripsi'];

            $stmt = $pdo->prepare("INSERT INTO aturan (kode, id_diagnosa, tipe, deskripsi) VALUES (?, ?, ?, ?)");
            $stmt->execute(array($kode, $id_diagnosa, $tipe, $deskripsi));
            setFlash('success', 'Aturan berhasil dibuat.');
        } elseif ($_POST['action'] === 'delete_rule') {
            $id = $_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM aturan WHERE id = ?");
            $stmt->execute(array($id));
            setFlash('success', 'Aturan dihapus.');
        } elseif ($_POST['action'] === 'add_symptom') {
            $id_aturan = $_POST['id_aturan'];
            $id_gejala = $_POST['id_gejala'];
            $cf_rule = (float)$_POST['cf_rule'];

            $stmt = $pdo->prepare("INSERT INTO detail_aturan (id_aturan, id_gejala, cf_rule) VALUES (?, ?, ?)");
            $stmt->execute(array($id_aturan, $id_gejala, $cf_rule));
            setFlash('success', 'Gejala ditambahkan ke aturan.');
        } elseif ($_POST['action'] === 'delete_symptom') {
            $id = $_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM detail_aturan WHERE id = ?");
            $stmt->execute(array($id));
            setFlash('success', 'Gejala dihapus dari aturan.');
        }
        redirect('data-rule.php');
    }
}

$title = "Data Aturan & Basis Pengetahuan";
require_once 'includes/header.php';

$aturan = $pdo->query("
    SELECT a.*, d.nama as diagnosa_nama 
    FROM aturan a 
    JOIN diagnosa d ON a.id_diagnosa = d.id 
    ORDER BY a.kode ASC
")->fetchAll();

$diagnosa_list = $pdo->query("SELECT * FROM diagnosa ORDER BY nama ASC")->fetchAll();
$gejala_list = $pdo->query("SELECT * FROM gejala ORDER BY kode ASC")->fetchAll();
?>

<div class="flex justify-between items-center mb-8">
    <div>
        <h3 class="text-xl font-bold text-slate-800">Basis Pengetahuan</h3>
        <p class="text-slate-500 text-sm">Hubungkan gejala dengan kriteria diagnosa menggunakan Certainty Factor.</p>
    </div>
    <button onclick="openModal('addRuleModal')" class="btn-primary flex items-center gap-2">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
        </svg>
        Buat Aturan Baru
    </button>
</div>

<div class="mb-8">
    <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest mb-4">Aturan Interpretasi Hasil (R2-R4, R6-R8, R9-R11)</h4>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <?php foreach ($diagnosa_list as $dl): ?>
            <div class="card p-6 border-t-4 border-<?= $dl['tipe'] === 'FINAL' ? 'primary' : ($dl['tipe'] === 'PT' ? 'purple-500' : 'orange-500') ?>">
                <h5 class="font-bold text-slate-800 mb-4"><?= $dl['nama'] ?></h5>
                <div class="space-y-3">
                    <?php
                    $stmt_cat = $pdo->prepare("SELECT * FROM kategori_cf WHERE id_diagnosa = ? ORDER BY min_cf ASC");
                    $stmt_cat->execute(array($dl['id']));
                    $cats = $stmt_cat->fetchAll();
                    foreach ($cats as $cat): ?>
                        <div class="flex justify-between items-center text-xs">
                            <span class="text-slate-500 font-medium"><?= $cat['nama'] ?></span>
                            <span class="bg-slate-100 px-2 py-0.5 rounded font-mono text-slate-600"><?= number_format($cat['min_cf'], 2) ?> - <?= number_format($cat['max_cf'], 2) ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<div class="flex justify-between items-center mb-6">
    <h4 class="text-sm font-bold text-slate-400 uppercase tracking-widest">Aturan Pemetaan Gejala (R1, R5)</h4>
</div>
<div class="space-y-8">
    <?php if (empty($aturan)): ?>
        <div class="card p-20 text-center">
            <p class="text-slate-400 italic">Belum ada aturan yang dikonfigurasi.</p>
        </div>
    <?php else: ?>
        <?php foreach ($aturan as $a): ?>
            <div class="card overflow-visible">
                <div class="bg-slate-50 px-8 py-5 border-b border-slate-200 flex justify-between items-center">
                    <div>
                        <span class="text-xs font-bold text-primary tracking-widest uppercase"><?= $a['kode'] ?></span>
                        <h4 class="text-lg font-bold text-slate-800"><?= $a['diagnosa_nama'] ?></h4>
                    </div>
                    <div class="flex gap-4">
                        <button onclick="openSymptomModal(<?= $a['id'] ?>, '<?= $a['kode'] ?>')" class="text-xs font-bold px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors">Tambah Gejala</button>
                        <form action="" method="POST" onsubmit="return confirm('Hapus seluruh aturan ini?')">
                            <input type="hidden" name="action" value="delete_rule">
                            <input type="hidden" name="id" value="<?= $a['id'] ?>">
                            <button type="submit" class="text-xs font-bold px-4 py-2 bg-red-100 text-red-600 rounded-lg hover:bg-red-200 transition-colors">Hapus Aturan</button>
                        </form>
                    </div>
                </div>
                <div class="p-0">
                    <table class="w-full text-left">
                        <thead class="bg-white border-b border-slate-100">
                            <tr>
                                <th class="px-8 py-3 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Gejala</th>
                                <th class="px-8 py-3 text-[10px] font-bold text-slate-400 uppercase tracking-widest">Weight (CF Rule)</th>
                                <th class="px-8 py-3 text-[10px] font-bold text-slate-400 uppercase tracking-widest text-right">Aksi</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <?php
                            $details = $pdo->prepare("
                                SELECT da.*, g.nama as gejala_nama, g.kode as gejala_kode 
                                FROM detail_aturan da
                                JOIN gejala g ON da.id_gejala = g.id
                                WHERE da.id_aturan = ?
                            ");
                            $details->execute(array($a['id']));
                            $rows = $details->fetchAll();

                            if (empty($rows)): ?>
                                <tr>
                                    <td colspan="3" class="px-8 py-6 text-sm text-slate-400 italic text-center">Belum ada gejala untuk aturan ini.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($rows as $r): ?>
                                    <tr class="text-sm">
                                        <td class="px-8 py-4">
                                            <span class="font-bold text-slate-700 mr-2"><?= $r['gejala_kode'] ?></span>
                                            <span class="text-slate-600"><?= $r['gejala_nama'] ?></span>
                                        </td>
                                        <td class="px-8 py-4">
                                            <span class="font-mono font-bold text-primary bg-primary/5 px-2 py-1 rounded"><?= number_format($r['cf_rule'], 2) ?></span>
                                        </td>
                                        <td class="px-8 py-4 text-right">
                                            <form action="" method="POST" class="inline">
                                                <input type="hidden" name="action" value="delete_symptom">
                                                <input type="hidden" name="id" value="<?= $r['id'] ?>">
                                                <button type="submit" class="text-red-400 hover:text-red-600">
                                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                    </svg>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- Rule Modal -->
<div id="addRuleModal" class="fixed inset-0 bg-slate-900/50 hidden items-center justify-center z-50 p-6">
    <div class="bg-white rounded-3xl w-full max-w-lg p-8 shadow-2xl">
        <h3 class="text-xl font-bold text-slate-800 mb-6 font-primary">Buat Aturan Baru</h3>
        <form action="" method="POST" class="space-y-5">
            <input type="hidden" name="action" value="add_rule">

            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Kode</label>
                    <input type="text" name="kode" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="R01">
                </div>
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Tipe</label>
                    <select name="tipe" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all appearance-none bg-white">
                        <option value="PT">Pola Tidur (PT)</option>
                        <option value="AD">Aktifitas Digital (AD)</option>
                        <option value="FINAL">Diagnosis Akhir (FINAL)</option>
                    </select>
                </div>
            </div>

            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Diagnosa Terkait</label>
                <select name="id_diagnosa" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all appearance-none bg-white">
                    <option value="">Pilih Diagnosa</option>
                    <?php foreach ($diagnosa_list as $dl): ?>
                        <option value="<?= $dl['id'] ?>"><?= $dl['nama'] ?> (<?= $dl['kode'] ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">DeskripsiAturan (Opsional)</label>
                <textarea name="deskripsi" rows="2" class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Penjelasan singkat aturan..."></textarea>
            </div>

            <div class="flex gap-4 pt-4">
                <button type="button" onclick="closeModal('addRuleModal')" class="flex-1 py-3 text-sm font-bold text-slate-500 hover:bg-slate-50 rounded-xl transition-colors">Batal</button>
                <button type="submit" class="flex-1 btn-primary py-3 text-sm">Simpan Aturan</button>
            </div>
        </form>
    </div>
</div>

<!-- Symptom Add Modal -->
<div id="addSymptomModal" class="fixed inset-0 bg-slate-900/50 hidden items-center justify-center z-50 p-6">
    <div class="bg-white rounded-3xl w-full max-w-lg p-8 shadow-2xl">
        <h3 id="symptomModalTitle" class="text-xl font-bold text-slate-800 mb-6 font-primary">Tambah Gejala ke Aturan</h3>
        <form action="" method="POST" class="space-y-5">
            <input type="hidden" name="action" value="add_symptom">
            <input type="hidden" name="id_aturan" id="symptom_id_aturan">

            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Pilih Gejala</label>
                <select name="id_gejala" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all appearance-none bg-white">
                    <option value="">Pilih Gejala</option>
                    <?php foreach ($gejala_list as $gl): ?>
                        <option value="<?= $gl['id'] ?>"><?= $gl['kode'] ?> - <?= $gl['nama'] ?> (<?= $gl['tipe'] ?>)</option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Certainty Factor (CF Rule / Pakar)</label>
                <p class="text-[10px] text-slate-500 mb-2 italic">Nilai antara 0.0 sampai 1.0 (Misal: 0.8 untuk sangat yakin)</p>
                <input type="number" step="0.01" min="0" max="1" name="cf_rule" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="0.8">
            </div>

            <div class="flex gap-4 pt-4">
                <button type="button" onclick="closeModal('addSymptomModal')" class="flex-1 py-3 text-sm font-bold text-slate-500 hover:bg-slate-50 rounded-xl transition-colors">Batal</button>
                <button type="submit" class="flex-1 btn-primary py-3 text-sm">Simpan Gejala</button>
            </div>
        </form>
    </div>
</div>

<script>
    function openModal(id) {
        document.getElementById(id).classList.remove('hidden');
        document.getElementById(id).classList.add('flex');
    }

    function closeModal(id) {
        document.getElementById(id).classList.add('hidden');
        document.getElementById(id).classList.remove('flex');
    }

    function openSymptomModal(id_aturan, kode_aturan) {
        document.getElementById('symptom_id_aturan').value = id_aturan;
        document.getElementById('symptomModalTitle').innerText = 'Tambah Gejala ke Aturan ' + kode_aturan;
        openModal('addSymptomModal');
    }
</script>

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