<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Kategori';

// ---------- HANDLE POST (Tambah / Edit / Hapus) ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'save') {
        $id       = $_POST['id'] ?? '';
        $kode     = trim($_POST['kode']);
        $nama     = trim($_POST['nama']);
        $tipe     = $_POST['tipe'];
        $kelompok = $_POST['kelompok'];
        $ket      = trim($_POST['keterangan']);
        $status   = $_POST['status'];

        if ($id) {
            $stmt = $pdo->prepare("UPDATE kategori SET kode=:kode, nama=:nama, tipe=:tipe, kelompok=:kelompok, keterangan=:ket, status=:status WHERE id=:id");
            $stmt->execute(['kode'=>$kode,'nama'=>$nama,'tipe'=>$tipe,'kelompok'=>$kelompok,'ket'=>$ket,'status'=>$status,'id'=>$id]);
            flash('success', 'Kategori berhasil diperbarui.');
        } else {
            $stmt = $pdo->prepare("INSERT INTO kategori (kode,nama,tipe,kelompok,keterangan,status) VALUES (:kode,:nama,:tipe,:kelompok,:ket,:status)");
            $stmt->execute(['kode'=>$kode,'nama'=>$nama,'tipe'=>$tipe,'kelompok'=>$kelompok,'ket'=>$ket,'status'=>$status]);
            flash('success', 'Kategori berhasil ditambahkan.');
        }
    } elseif ($action === 'delete') {
        $id = $_POST['id'];
        $cek = $pdo->prepare("SELECT COUNT(*) FROM transaksi WHERE kategori_id=:id");
        $cek->execute(['id'=>$id]);
        if ($cek->fetchColumn() > 0) {
            flash('error', 'Kategori tidak dapat dihapus karena sudah dipakai pada transaksi. Anda bisa menonaktifkannya.');
        } else {
            $pdo->prepare("DELETE FROM kategori WHERE id=:id")->execute(['id'=>$id]);
            flash('success', 'Kategori berhasil dihapus.');
        }
    }
    header('Location: kategori.php');
    exit;
}

$data = $pdo->query("SELECT * FROM kategori ORDER BY tipe, nama")->fetchAll();

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Master Kategori Pemasukan &amp; Pengeluaran</h5>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalKategori" onclick="resetForm()">
        <i class="bi bi-plus-lg"></i> Tambah Kategori
    </button>
</div>

<div class="card">
    <div class="card-body">
        <table class="table table-hover datatable w-100">
            <thead>
                <tr><th>Kode</th><th>Nama Kategori</th><th>Tipe</th><th>Kelompok</th><th>Status</th><th>Aksi</th></tr>
            </thead>
            <tbody>
            <?php foreach ($data as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['kode']) ?></td>
                    <td><?= htmlspecialchars($row['nama']) ?></td>
                    <td><span class="badge <?= $row['tipe']==='pemasukan' ? 'text-bg-success' : 'text-bg-danger' ?>"><?= ucfirst($row['tipe']) ?></span></td>
                    <td><?= ucfirst($row['kelompok']) ?></td>
                    <td><span class="badge <?= $row['status']==='aktif' ? 'text-bg-success' : 'text-bg-secondary' ?>"><?= ucfirst($row['status']) ?></span></td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick='editRow(<?= htmlspecialchars(json_encode($row), ENT_QUOTES) ?>)'><i class="bi bi-pencil"></i></button>
                        <form method="POST" class="d-inline" onsubmit="return confirmDelete()">
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                            <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- MODAL -->
<div class="modal fade" id="modalKategori" tabindex="-1">
    <div class="modal-dialog">
        <form method="POST" class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">Tambah Kategori</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" id="f_id">
                <div class="mb-3">
                    <label class="form-label">Kode</label>
                    <input type="text" name="kode" id="f_kode" class="form-control" placeholder="contoh: PK-ATK">
                </div>
                <div class="mb-3">
                    <label class="form-label">Nama Kategori</label>
                    <input type="text" name="nama" id="f_nama" class="form-control" required>
                </div>
                <div class="row">
                    <div class="col-6 mb-3">
                        <label class="form-label">Tipe</label>
                        <select name="tipe" id="f_tipe" class="form-select" required>
                            <option value="pemasukan">Pemasukan</option>
                            <option value="pengeluaran">Pengeluaran</option>
                        </select>
                    </div>
                    <div class="col-6 mb-3">
                        <label class="form-label">Kelompok</label>
                        <select name="kelompok" id="f_kelompok" class="form-select" required>
                            <option value="umum">Umum</option>
                            <option value="spp">SPP</option>
                        </select>
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Keterangan</label>
                    <textarea name="keterangan" id="f_keterangan" class="form-control" rows="2"></textarea>
                </div>
                <div class="mb-3">
                    <label class="form-label">Status</label>
                    <select name="status" id="f_status" class="form-select">
                        <option value="aktif">Aktif</option>
                        <option value="nonaktif">Nonaktif</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Batal</button>
                <button type="submit" class="btn btn-primary">Simpan</button>
            </div>
        </form>
    </div>
</div>

<script>
function resetForm() {
    document.getElementById('modalTitle').innerText = 'Tambah Kategori';
    document.getElementById('f_id').value = '';
    document.getElementById('f_kode').value = '';
    document.getElementById('f_nama').value = '';
    document.getElementById('f_tipe').value = 'pemasukan';
    document.getElementById('f_kelompok').value = 'umum';
    document.getElementById('f_keterangan').value = '';
    document.getElementById('f_status').value = 'aktif';
}
function editRow(row) {
    document.getElementById('modalTitle').innerText = 'Edit Kategori';
    document.getElementById('f_id').value = row.id;
    document.getElementById('f_kode').value = row.kode;
    document.getElementById('f_nama').value = row.nama;
    document.getElementById('f_tipe').value = row.tipe;
    document.getElementById('f_kelompok').value = row.kelompok;
    document.getElementById('f_keterangan').value = row.keterangan;
    document.getElementById('f_status').value = row.status;
    new bootstrap.Modal(document.getElementById('modalKategori')).show();
}
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>