<?php
$admin_title = "Kelola Kategori Produk";
require_once 'includes/header.php';

$error = '';
$success = '';

// Handle Add Category
if (isset($_POST['add_category'])) {
    $name = trim($_POST['name']);
    if (empty($name)) {
        $error = "Nama kategori wajib diisi.";
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO categories (name) VALUES (?)");
            $stmt->execute([$name]);
            $success = "Kategori '$name' berhasil ditambahkan!";
        } catch (PDOException $e) {
            if ($e->errorInfo[1] == 1062) {
                $error = "Kategori '$name' sudah ada.";
            } else {
                $error = "Gagal menambahkan kategori: " . $e->getMessage();
            }
        }
    }
}

// Handle Delete Category
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    try {
        // Fetch category name
        $stmt = $pdo->prepare("SELECT name FROM categories WHERE id = ?");
        $stmt->execute([$id]);
        $cat = $stmt->fetch();
        
        if ($cat) {
            $cat_name = $cat['name'];
            
            // Check if there are products using this category
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE category = ?");
            $stmt->execute([$cat_name]);
            $product_count = $stmt->fetchColumn();
            
            if ($product_count > 0) {
                $error = "Kategori '$cat_name' tidak bisa dihapus karena sedang digunakan oleh $product_count produk. Silakan ubah kategori produk tersebut terlebih dahulu.";
            } else {
                $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
                $stmt->execute([$id]);
                $success = "Kategori '$cat_name' berhasil dihapus!";
            }
        }
    } catch (Exception $e) {
        $error = "Gagal menghapus kategori: " . $e->getMessage();
    }
}

// Fetch all categories
try {
    $stmt = $pdo->query("SELECT c.*, (SELECT COUNT(*) FROM products WHERE category = c.name) as product_count FROM categories c ORDER BY name ASC");
    $categories = $stmt->fetchAll();
} catch (Exception $e) {
    $error = "Gagal memuat kategori: " . $e->getMessage();
    $categories = [];
}
?>

<?php if (!empty($error)): ?>
    <div style="background-color: rgba(239, 68, 68, 0.15); border: 1px solid var(--error); color: #f87171; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-exclamation-circle" style="margin-right: 5px;"></i> <?php echo $error; ?>
    </div>
<?php endif; ?>

<?php if (!empty($success)): ?>
    <div style="background-color: rgba(16, 185, 129, 0.15); border: 1px solid var(--success); color: #34d399; padding: 12px 15px; border-radius: 6px; font-size: 13px; margin-bottom: 20px;">
        <i class="fas fa-check-circle" style="margin-right: 5px;"></i> <?php echo $success; ?>
    </div>
<?php endif; ?>

<div class="grid-split-admin">
    <!-- Form Tambah -->
    <div class="form-card" style="margin-bottom: 0;">
        <h3 style="font-size: 16px; font-weight: 700; color: var(--primary); border-bottom: 1px solid var(--border-color); padding-bottom: 8px; margin-bottom: 20px; text-transform: uppercase;">Tambah Kategori</h3>
        
        <form action="" method="POST">
            <div class="form-group">
                <label for="name">Nama Kategori *</label>
                <input type="text" id="name" name="name" class="form-control" placeholder="Contoh: Andesit Bakar" required>
            </div>
            
            <button type="submit" name="add_category" class="btn-submit">Tambah Kategori</button>
        </form>
    </div>

    <!-- Tabel Kategori -->
    <div class="table-card">
        <h3 style="font-size: 16px; font-weight: 700; color: var(--primary); border-bottom: 1px solid var(--border-color); padding-bottom: 8px; margin-bottom: 20px; text-transform: uppercase;">Daftar Kategori Produk</h3>
        
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>Nama Kategori</th>
                        <th style="text-align: center;">Jumlah Produk</th>
                        <th style="text-align: center;">Aksi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($categories) > 0): ?>
                        <?php foreach ($categories as $cat): ?>
                            <tr>
                                <td style="font-weight: 600; color: var(--text-dark);"><?php echo htmlspecialchars($cat['name']); ?></td>
                                <td style="text-align: center;">
                                    <span class="badge badge-read" style="background-color: var(--bg-light); color: var(--secondary); font-size:12px; padding: 4px 10px;">
                                        <?php echo $cat['product_count']; ?>
                                    </span>
                                </td>
                                <td style="text-align: center;">
                                    <a href="?delete=<?php echo $cat['id']; ?>" class="action-btn btn-delete" onclick="return confirm('Apakah Anda yakin ingin menghapus kategori &quot;<?php echo htmlspecialchars($cat['name']); ?>&quot;?');" title="Hapus Kategori">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="3" style="text-align: center; color: var(--text-muted);">Belum ada kategori terdaftar.</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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