<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$errors = [];
$editCategory = null;

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];
    $stmt = $pdo->prepare('SELECT id, name, description, is_active FROM categories WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editCategory = $stmt->fetch();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    if ($name === '') {
        $errors['name'] = 'Nama kategori wajib diisi.';
    }

    if (!$errors) {
        if ($action === 'create') {
            $stmt = $pdo->prepare('INSERT INTO categories (name, description, is_active) VALUES (?, ?, ?)');
            $stmt->execute([$name, $description, $isActive]);
            flash_message('success', 'Kategori berhasil ditambahkan.');
            redirect(base_url('admin/categories.php'));
        }

        if ($action === 'update') {
            $id = (int) ($_POST['id'] ?? 0);
            $stmt = $pdo->prepare('UPDATE categories SET name = ?, description = ?, is_active = ? WHERE id = ?');
            $stmt->execute([$name, $description, $isActive, $id]);
            flash_message('success', 'Kategori berhasil diperbarui.');
            redirect(base_url('admin/categories.php'));
        }
    }

    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $pdo->prepare('DELETE FROM categories WHERE id = ?');
        $stmt->execute([$id]);
        flash_message('success', 'Kategori berhasil dihapus.');
        redirect(base_url('admin/categories.php'));
    }
}

$categories = $pdo->query('SELECT * FROM categories ORDER BY created_at DESC')->fetchAll();
?>

<h2 class="fw-bold mb-4">Kategori</h2>

<div class="row g-4">
    <div class="col-lg-4">
        <div class="card shadow-sm">
            <div class="card-body">
                <h5 class="fw-bold mb-3"><?= $editCategory ? 'Edit Kategori' : 'Tambah Kategori'; ?></h5>
                <form method="post">
                    <input type="hidden" name="action" value="<?= $editCategory ? 'update' : 'create'; ?>">
                    <?php if ($editCategory): ?>
                        <input type="hidden" name="id" value="<?= (int) $editCategory['id']; ?>">
                    <?php endif; ?>
                    <label>Nama Kategori</label>
                    <input class="form-control" type="text" name="name" value="<?= sanitize($editCategory['name'] ?? $name ?? ''); ?>" required>
                    <?php if (!empty($errors['name'])): ?><small class="error"><?= sanitize($errors['name']); ?></small><?php endif; ?>

                    <label>Deskripsi</label>
                    <textarea class="form-control" name="description" rows="3"><?= sanitize($editCategory['description'] ?? $description ?? ''); ?></textarea>

                    <div class="form-check mt-2">
                        <input class="form-check-input" type="checkbox" name="is_active" id="active" <?= (int) ($editCategory['is_active'] ?? 1) === 1 ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="active">Aktif</label>
                    </div>

                    <button class="btn mt-3" type="submit">Simpan</button>
                    <?php if ($editCategory): ?>
                        <a class="btn btn-sm" href="<?= base_url('admin/categories.php'); ?>">Batal</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-8">
        <div class="card shadow-sm">
            <div class="card-body table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th>Nama</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($categories as $category): ?>
                            <tr>
                                <td><?= sanitize($category['name']); ?></td>
                                <td><?= (int) $category['is_active'] === 1 ? 'Aktif' : 'Nonaktif'; ?></td>
                                <td>
                                    <a class="btn btn-sm" href="<?= base_url('admin/categories.php?edit=' . (int) $category['id']); ?>">Edit</a>
                                    <button class="btn btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal<?= (int) $category['id']; ?>">Hapus</button>
                                </td>
                            </tr>
                            <div class="modal fade" id="deleteModal<?= (int) $category['id']; ?>" tabindex="-1" aria-hidden="true">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">Hapus Kategori</h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">Yakin hapus kategori <?= sanitize($category['name']); ?>?</div>
                                        <div class="modal-footer">
                                            <form method="post">
                                                <input type="hidden" name="action" value="delete">
                                                <input type="hidden" name="id" value="<?= (int) $category['id']; ?>">
                                                <button class="btn" type="submit">Ya, Hapus</button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_admin.php'; ?>
