<?php
require_once '../../includes/config.php';

// Check if admin is logged in
if (!isAdminLoggedIn()) {
    redirect(SITE_URL . 'admin/login.php');
}

$pageTitle = "Kelola Kategori";

// Delete category if requested
if (isset($_GET['delete'])) {
    $category_id = (int)$_GET['delete'];
    
    try {
        $conn = connectDB();
        
        // Check if the category exists
        $stmt = $conn->prepare("SELECT * FROM categories WHERE category_id = :category_id");
        $stmt->bindParam(':category_id', $category_id);
        $stmt->execute();
        
        if ($stmt->fetch(PDO::FETCH_ASSOC)) {
            // Delete category (products will have their category_id set to NULL due to foreign key constraint)
            $stmt = $conn->prepare("DELETE FROM categories WHERE category_id = :category_id");
            $stmt->bindParam(':category_id', $category_id);
            $stmt->execute();
            
            $success = "Kategori berhasil dihapus";
        }
    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}

// Success message from add/edit pages
if (isset($_GET['success'])) {
    if ($_GET['success'] === 'added') {
        $success = "Kategori berhasil ditambahkan";
    } elseif ($_GET['success'] === 'updated') {
        $success = "Kategori berhasil diperbarui";
    }
}

// Get categories with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

try {
    $conn = connectDB();
    
    // Count total categories
    $stmt = $conn->query("SELECT COUNT(*) as total FROM categories");
    $totalCategories = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    $totalPages = ceil($totalCategories / $limit);
    
    // Get categories for current page
    $stmt = $conn->prepare("SELECT * FROM categories ORDER BY category_id ASC LIMIT :offset, :limit");
    $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $error = "Error: " . $e->getMessage();
}

include '../header.php';
?>

<div class="admin-header">
    <h1>Kelola Kategori</h1>
    <div>
        <a href="add.php" class="btn"><i class="fas fa-plus"></i> Tambah Kategori</a>
    </div>
</div>

<?php if (isset($success)): ?>
    <div class="success"><?php echo $success; ?></div>
<?php endif; ?>

<?php if (isset($error)): ?>
    <div class="error"><?php echo $error; ?></div>
<?php endif; ?>

<div class="admin-content-box">
    <div class="table-responsive">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Nama Kategori</th>
                    <th>Deskripsi</th>
                    <th>Jumlah Produk</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($categories)): ?>
                    <tr>
                        <td colspan="5" class="text-center">Belum ada kategori</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($categories as $category): ?>
                        <?php
                        // Get product count for this category
                        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM products WHERE category_id = :category_id");
                        $stmt->bindParam(':category_id', $category['category_id']);
                        $stmt->execute();
                        $productCount = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
                        ?>
                        <tr>
                            <td><?php echo $category['category_id']; ?></td>
                            <td><?php echo $category['name']; ?></td>
                            <td><?php echo substr($category['description'], 0, 100) . (strlen($category['description']) > 100 ? '...' : ''); ?></td>
                            <td><?php echo $productCount; ?></td>
                            <td>
                                <a href="edit.php?id=<?php echo $category['category_id']; ?>" class="action-btn edit-btn" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="index.php?delete=<?php echo $category['category_id']; ?>" class="action-btn delete-btn delete-confirm" title="Hapus">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php if ($totalPages > 1): ?>
        <div class="pagination">
            <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>" class="page-link">&laquo; Sebelumnya</a>
            <?php endif; ?>
            
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <a href="?page=<?php echo $i; ?>" class="page-link <?php echo ($page == $i) ? 'active' : ''; ?>">
                    <?php echo $i; ?>
                </a>
            <?php endfor; ?>
            
            <?php if ($page < $totalPages): ?>
                <a href="?page=<?php echo $page + 1; ?>" class="page-link">Berikutnya &raquo;</a>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>

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