<?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'])) {
        $kode = $_POST['kode'];
        $nama = $_POST['nama'];
        $cf_pakar = isset($_POST['cf_pakar']) ? (float)$_POST['cf_pakar'] : 0.4;
        $tipe = $_POST['tipe'];
        $pernyataan = $_POST['pernyataan'];

        if ($_POST['action'] === 'add') {
            $stmt = $pdo->prepare("INSERT INTO gejala (kode, nama, cf_pakar, tipe, pernyataan) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute(array($kode, $nama, $cf_pakar, $tipe, $pernyataan));
            setFlash('success', 'Gejala berhasil ditambahkan.');
        } elseif ($_POST['action'] === 'edit') {
            $id = $_POST['id'];
            $stmt = $pdo->prepare("UPDATE gejala SET kode = ?, nama = ?, cf_pakar = ?, tipe = ?, pernyataan = ? WHERE id = ?");
            $stmt->execute(array($kode, $nama, $cf_pakar, $tipe, $pernyataan, $id));
            setFlash('success', 'Gejala berhasil diupdate.');
        } elseif ($_POST['action'] === 'delete') {
            $id = $_POST['id'];
            $stmt = $pdo->prepare("DELETE FROM gejala WHERE id = ?");
            $stmt->execute(array($id));
            setFlash('success', 'Gejala berhasil dihapus.');
        }
        redirect('data-gejala.php');
    }
}

$title = "Data Gejala";
require_once 'includes/header.php';

// Pagination Settings
$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Count Total
$totalRows = $pdo->query("SELECT COUNT(*) FROM gejala")->fetchColumn();
$totalPages = ceil($totalRows / $limit);

// Natural Sort: Order by type, then numerical part of code
$gejala = $pdo->prepare("
    SELECT * FROM gejala 
    ORDER BY tipe ASC, CAST(SUBSTR(kode, 3) AS UNSIGNED) ASC 
    LIMIT :limit OFFSET :offset
");
$gejala->bindValue(':limit', $limit, PDO::PARAM_INT);
$gejala->bindValue(':offset', $offset, PDO::PARAM_INT);
$gejala->execute();
$gejala_list_result = $gejala->fetchAll();
?>

<div class="flex justify-between items-center mb-8">
    <div>
        <h3 class="text-xl font-bold text-slate-800">Manajemen Gejala</h3>
        <p class="text-slate-500 text-sm">Kelola daftar gejala kesehatan mental (PT: Pola Tidur, AD: Aktifitas Digital).</p>
    </div>
    <button onclick="openModal('addModal')" 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>
        Tambah Gejala
    </button>
</div>

<div class="card">
    <div class="overflow-x-auto">
        <table class="w-full text-left">
            <thead class="bg-slate-50 border-b border-slate-200">
                <tr>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Kode</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Nama Gejala</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Pernyataan</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">Tipe</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest">CF Pakar</th>
                    <th class="px-8 py-4 text-xs font-bold text-slate-500 uppercase tracking-widest text-right">Aksi</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php if (empty($gejala_list_result)): ?>
                    <tr>
                        <td colspan="6" class="px-8 py-10 text-center text-slate-400 italic">Belum ada data gejala.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($gejala_list_result as $g): ?>
                        <tr class="hover:bg-slate-50 transition-colors text-sm">
                            <td class="px-8 py-4 font-mono font-bold text-primary"><?= $g['kode'] ?></td>
                            <td class="px-8 py-4 text-slate-800 leading-relaxed"><?= $g['nama'] ?></td>
                            <td class="px-8 py-4 text-slate-600 leading-relaxed"><?= $g['pernyataan'] ?></td>
                            <td class="px-8 py-4">
                                <span class="px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider <?= $g['tipe'] === 'PT' ? 'bg-purple-100 text-purple-600' : 'bg-orange-100 text-orange-600' ?>">
                                    <?= $g['tipe'] ?>
                                </span>
                            </td>
                            <td class="px-8 py-4 font-mono font-bold text-slate-600"><?= number_format($g['cf_pakar'], 2) ?></td>
                            <td class="px-8 py-4 text-right space-x-2">
                                <button onclick="editGejala(<?= htmlspecialchars(json_encode($g)) ?>)" class="font-bold text-primary hover:text-primary-dark">Edit</button>
                                <form action="" method="POST" class="inline" onsubmit="return confirm('Hapus gejala ini?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $g['id'] ?>">
                                    <button type="submit" class="font-bold text-red-500 hover:text-red-600">Hapus</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?= renderPagination($page, $totalPages, 'data-gejala.php?') ?>

<!-- Modal -->
<div id="gejalaModal" 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-xl p-8 shadow-2xl">
        <h3 id="modalTitle" class="text-xl font-bold text-slate-800 mb-6">Tambah Gejala</h3>
        <form action="" method="POST" class="space-y-5">
            <input type="hidden" name="action" id="formAction" value="add">
            <input type="hidden" name="id" id="formId">
            
            <div class="grid grid-cols-3 gap-4">
                <div class="col-span-1">
                    <label class="block text-sm font-bold text-slate-700 mb-2">Kode</label>
                    <input type="text" name="kode" id="formKode" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="G01">
                </div>
                <div class="col-span-2">
                    <label class="block text-sm font-bold text-slate-700 mb-2">Tipe</label>
                    <select name="tipe" id="formTipe" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all bg-white appearance-none">
                        <option value="PT">Pola Tidur (PT)</option>
                        <option value="AD">Aktifitas Digital (AD)</option>
                    </select>
                </div>
            </div>
            
            <div class="grid grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">Nama Gejala</label>
                    <input type="text" name="nama" id="formNama" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Deskripsi gejala...">
                </div>
                <div>
                    <label class="block text-sm font-bold text-slate-700 mb-2">CF Pakar (0.0 - 1.0)</label>
                    <input type="number" step="0.1" min="0" max="1" name="cf_pakar" id="formCFPakar" required class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Misal: 0.8">
                </div>
            </div>
            
            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Pernyataan</label>
                <textarea name="pernyataan" id="formPernyataan" required rows="2" class="w-full px-5 py-3 rounded-xl border border-slate-200 focus:border-primary outline-none transition-all" placeholder="Pernyataan yang ditampilkan ke user..."></textarea>
            </div>

            <div class="flex gap-4 pt-4">
                <button type="button" onclick="closeModal('gejalaModal')" 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) {
    const el = document.getElementById('gejalaModal');
    el.classList.remove('hidden');
    el.classList.add('flex');
    if (id === 'addModal') {
        document.getElementById('modalTitle').innerText = 'Tambah Gejala';
        document.getElementById('formAction').value = 'add';
        document.querySelector('#gejalaModal form').reset();
    }
}
function closeModal() {
    document.getElementById('gejalaModal').classList.add('hidden');
    document.getElementById('gejalaModal').classList.remove('flex');
}
function editGejala(data) {
    document.getElementById('gejalaModal').classList.remove('hidden');
    document.getElementById('gejalaModal').classList.add('flex');
    document.getElementById('modalTitle').innerText = 'Edit Gejala';
    document.getElementById('formAction').value = 'edit';
    
    document.getElementById('formId').value = data.id;
    document.getElementById('formKode').value = data.kode;
    document.getElementById('formNama').value = data.nama;
    document.getElementById('formTipe').value = data.tipe;
    document.getElementById('formCFPakar').value = data.cf_pakar;
    document.getElementById('formPernyataan').value = data.pernyataan || '';
}
</script>

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