<?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'];
        $tipe = $_POST['tipe'];

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

$title = "Data Diagnosa";
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 diagnosa")->fetchColumn();
$totalPages = ceil($totalRows / $limit);

$diagnosa_query = $pdo->prepare("SELECT * FROM diagnosa ORDER BY kode ASC LIMIT :limit OFFSET :offset");
$diagnosa_query->bindValue(':limit', $limit, PDO::PARAM_INT);
$diagnosa_query->bindValue(':offset', $offset, PDO::PARAM_INT);
$diagnosa_query->execute();
$diagnosa = $diagnosa_query->fetchAll();
?>

<div class="flex justify-between items-center mb-8">
    <div>
        <h3 class="text-xl font-bold text-slate-800">Manajemen Jenis Diagnosa</h3>
        <p class="text-slate-500 text-sm">Definisikan kategori gangguan kesehatan mental.</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 Diagnosa
    </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 Diagnosa</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 text-right">Aksi</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-slate-100">
                <?php if (empty($diagnosa)): ?>
                    <tr>
                        <td colspan="4" class="px-8 py-10 text-center text-slate-400 italic">Belum ada data diagnosa.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($diagnosa as $d): ?>
                        <tr class="hover:bg-slate-50 transition-colors text-sm">
                            <td class="px-8 py-4 font-mono font-bold text-primary"><?= $d['kode'] ?></td>
                            <td class="px-8 py-4 font-bold text-slate-800"><?= $d['nama'] ?></td>
                            <td class="px-8 py-4">
                                <span class="px-3 py-1 rounded-full text-[10px] font-bold uppercase tracking-wider <?= $d['tipe'] === 'PT' ? 'bg-purple-100 text-purple-600' : 'bg-orange-100 text-orange-600' ?>">
                                    <?= $d['tipe'] ?>
                                </span>
                            </td>
                            <td class="px-8 py-4 text-right space-x-2">
                                <button onclick="editDiagnosa(<?= htmlspecialchars(json_encode($d)) ?>)" class="font-bold text-primary hover:text-primary-dark">Edit</button>
                                <form action="" method="POST" class="inline" onsubmit="return confirm('Hapus diagnosa ini?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $d['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-diagnosa.php?') ?>

<!-- Modal -->
<div id="diagnosaModal" 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="modalTitle" class="text-xl font-bold text-slate-800 mb-6">Tambah Diagnosa</h3>
        <form action="" method="POST" class="space-y-6">
            <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="D01">
                </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">Personal Terbuka (PT)</option>
                        <option value="AD">Anxiety Disorder (AD)</option>
                    </select>
                </div>
            </div>
            
            <div>
                <label class="block text-sm font-bold text-slate-700 mb-2">Nama Kondisi / Diagnosa</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="Misal: Generalized Anxiety Disorder">
            </div>

            <div class="flex gap-4 pt-4">
                <button type="button" onclick="closeModal()" 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 Data</button>
            </div>
        </form>
    </div>
</div>

<script>
function openModal(id) {
    const el = document.getElementById('diagnosaModal');
    el.classList.remove('hidden');
    el.classList.add('flex');
    if (id === 'addModal') {
        document.getElementById('modalTitle').innerText = 'Tambah Diagnosa';
        document.getElementById('formAction').value = 'add';
        document.querySelector('#diagnosaModal form').reset();
    }
}
function closeModal() {
    document.getElementById('diagnosaModal').classList.add('hidden');
    document.getElementById('diagnosaModal').classList.remove('flex');
}
function editDiagnosa(data) {
    document.getElementById('diagnosaModal').classList.remove('hidden');
    document.getElementById('diagnosaModal').classList.add('flex');
    document.getElementById('modalTitle').innerText = 'Edit Diagnosa';
    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;
}
</script>

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