<?php
$page_title = 'Kategori Aset';
require_once('includes/load.php');
page_require_level(4);

$db = MySqli_DB::getInstance();

// Proses form saat data dikirimkan
if (isset($_POST['add_category'])) {
    $req_field = array('category-name');
    validate_fields($req_field);
    $cat_name = remove_junk($db->escape($_POST['category-name']));
    if (empty($errors)) {
        $sql  = "INSERT INTO assets_categories (category_name) VALUES ('{$cat_name}')";
        if ($db->query($sql)) {
            $session->msg("s", "Kategori berhasil ditambahkan.");
            redirect('assets_categories.php', false);
        } else {
            $session->msg("d", "Gagal menambahkan kategori: " . $db->error());
            redirect('assets_categories.php', false);
        }
    } else {
        $session->msg("d", $errors);
        redirect('assets_categories.php', false);
    }
}

// Proses edit kategori
if (isset($_POST['update_category'])) {
    $req_field = array('category-name', 'id');
    validate_fields($req_field);
    $cat_id = (int)$db->escape($_POST['id']);
    $cat_name = remove_junk($db->escape($_POST['category-name']));

    if (empty($errors)) {
        $sql = "UPDATE assets_categories SET category_name = '{$cat_name}' WHERE id = '{$cat_id}'";
        if ($db->query($sql)) {
            $session->msg("s", "Kategori berhasil diperbarui.");
            redirect('assets_categories.php', false);
        } else {
            $session->msg("d", "Gagal memperbarui kategori: " . $db->error());
            redirect('assets_categories.php', false);
        }
    } else {
        $session->msg("d", $errors);
        redirect('assets_categories.php', false);
    }
}

// Proses hapus kategori
if (isset($_GET['delete_id'])) {
    $cat_id = (int)$db->escape($_GET['delete_id']);
    $sql = "DELETE FROM assets_categories WHERE id = '{$cat_id}'";
    if ($db->query($sql)) {
        $session->msg("s", "Kategori berhasil dihapus.");
        redirect('assets_categories.php', false);
    } else {
        $session->msg("d", "Gagal menghapus kategori: " . $db->error());
        redirect('assets_categories.php', false);
    }
}

// Ambil semua kategori dari database
$categories = find_by_sql("SELECT * FROM assets_categories ORDER BY category_name ASC");

?>
<?php include_once('layouts/header.php'); ?>

<div class="row">
    <div class="col-md-12">
        <?php echo display_msg($msg); ?>
    </div>
</div>

<div class="row">
    <div class="col-md-5">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-plus"></span>
                    <span>Tambah Kategori</span>
                </strong>
            </div>
            <div class="panel-body">
                <form method="post" action="assets_categories.php">
                    <div class="form-group">
                        <input type="text" class="form-control" name="category-name" placeholder="Nama Kategori" required>
                    </div>
                    <button type="submit" name="add_category" class="btn btn-primary">Tambah Kategori</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-md-7">
        <div class="panel panel-default">
            <div class="panel-heading">
                <strong>
                    <span class="glyphicon glyphicon-th"></span>
                    <span>Daftar Kategori</span>
                </strong>
            </div>
            <div class="panel-body">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th class="text-center" style="width: 50px;">#</th>
                            <th>Kategori</th>
                            <th class="text-center" style="width: 100px;">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($categories)): ?>
                            <?php foreach ($categories as $i => $category): ?>
                                <tr>
                                    <td class="text-center"><?php echo (int)$i + 1; ?></td>
                                    <td>
                                        <span id="cat-name-<?php echo $category['id']; ?>"><?php echo remove_junk($category['category_name']); ?></span>
                                        <form id="edit-form-<?php echo $category['id']; ?>" class="hidden" method="post" action="assets_categories.php" style="display:inline;">
                                            <input type="hidden" name="id" value="<?php echo (int)$category['id']; ?>">
                                            <input type="text" name="category-name" value="<?php echo htmlspecialchars($category['category_name']); ?>" required>
                                            <button type="submit" name="update_category" class="btn btn-xs btn-success">Simpan</button>
                                        </form>
                                    </td>
                                    <td class="text-center">
                                        <div class="btn-group">
                                            <button type="button" class="btn btn-xs btn-warning edit-btn" data-id="<?php echo $category['id']; ?>" title="Edit">
                                                <i class="glyphicon glyphicon-pencil"></i>
                                            </button>
                                            <a href="assets_categories.php?delete_id=<?php echo (int)$category['id']; ?>" class="btn btn-xs btn-danger" title="Hapus" onclick="return confirm('Apakah Anda yakin ingin menghapus kategori ini?');">
                                                <i class="glyphicon glyphicon-remove"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="3" class="text-center">Tidak ada kategori ditemukan.</td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const editButtons = document.querySelectorAll('.edit-btn');
    editButtons.forEach(button => {
        button.addEventListener('click', function() {
            const id = this.getAttribute('data-id');
            const editForm = document.getElementById(`edit-form-${id}`);
            const categoryNameSpan = document.getElementById(`cat-name-${id}`);
            
            // Toggle visibility
            if (editForm.classList.contains('hidden')) {
                editForm.classList.remove('hidden');
                categoryNameSpan.style.display = 'none';
                this.innerHTML = '<i class="glyphicon glyphicon-remove"></i>';
                this.setAttribute('title', 'Batal');
            } else {
                editForm.classList.add('hidden');
                categoryNameSpan.style.display = 'inline';
                this.innerHTML = '<i class="glyphicon glyphicon-pencil"></i>';
                this.setAttribute('title', 'Edit');
            }
        });
    });
});
</script>

<?php include_once('layouts/footer.php'); ?>