<?php
/**
 * Admin Categories Management
 * Digital Marketplace
 */

require_once __DIR__ . '/../config/database.php';
require_login();

if (!isset($_SESSION['is_admin']) || !$_SESSION['is_admin']) {
    header('Location: ' . BASE_URL . '/index.php');
    exit;
}

$page_title = 'Categories';

// Handle delete
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        // Check if category has products
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE category_id = ?");
        $stmt->execute([$id]);
        $product_count = $stmt->fetchColumn();
        
        if ($product_count > 0) {
            set_flash_message('Cannot delete category with products. Move products first.', 'error');
        } else {
            $stmt = $pdo->prepare("DELETE FROM categories WHERE id = ?");
            $stmt->execute([$id]);
            set_flash_message('Category deleted successfully!', 'success');
        }
    } catch (PDOException $e) {
        set_flash_message('Failed to delete category.', 'error');
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Handle add/edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        set_flash_message('Invalid request.', 'error');
    } else {
        $id = (int)($_POST['id'] ?? 0);
        $name = sanitize($_POST['name'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $parent_id = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;
        $sort_order = (int)($_POST['sort_order'] ?? 0);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        if (empty($name)) {
            set_flash_message('Category name is required.', 'error');
        } else {
            try {
                if ($id) {
                    // Update
                    $slug = generate_unique_slug($pdo, $name, 'categories', 'slug', $id);
                    $stmt = $pdo->prepare("UPDATE categories SET name = ?, slug = ?, description = ?, parent_id = ?, sort_order = ?, is_active = ?, updated_at = NOW() WHERE id = ?");
                    $stmt->execute([$name, $slug, $description, $parent_id, $sort_order, $is_active, $id]);
                    set_flash_message('Category updated successfully!', 'success');
                } else {
                    // Insert
                    $slug = generate_unique_slug($pdo, $name, 'categories');
                    $stmt = $pdo->prepare("INSERT INTO categories (name, slug, description, parent_id, sort_order, is_active, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())");
                    $stmt->execute([$name, $slug, $description, $parent_id, $sort_order, $is_active]);
                    set_flash_message('Category added successfully!', 'success');
                }
            } catch (PDOException $e) {
                set_flash_message('Failed to save category.', 'error');
            }
        }
    }
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Get categories
$categories = get_all_categories(false);

// Get category for edit
$edit_category = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM categories WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_category = $stmt->fetch();
}

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

<div class="admin-content">
    <div class="admin-header d-flex justify-content-between align-items-center">
        <h1><i class="fas fa-tags me-2"></i>Categories</h1>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#categoryModal">
            <i class="fas fa-plus me-2"></i>Add Category
        </button>
    </div>
    
    <!-- Categories Table -->
    <div class="card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Name</th>
                            <th>Slug</th>
                            <th>Products</th>
                            <th>Order</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($categories as $category): 
                            $stmt = $pdo->prepare("SELECT COUNT(*) FROM products WHERE category_id = ?");
                            $stmt->execute([$category['id']]);
                            $product_count = $stmt->fetchColumn();
                        ?>
                        <tr>
                            <td>
                                <strong><?php echo sanitize($category['name']); ?></strong>
                                <?php if ($category['description']): ?>
                                <small class="d-block text-muted"><?php echo truncate($category['description'], 50); ?></small>
                                <?php endif; ?>
                            </td>
                            <td><code><?php echo $category['slug']; ?></code></td>
                            <td><?php echo $product_count; ?></td>
                            <td><?php echo $category['sort_order']; ?></td>
                            <td>
                                <span class="badge bg-<?php echo $category['is_active'] ? 'success' : 'secondary'; ?>">
                                    <?php echo $category['is_active'] ? 'Active' : 'Inactive'; ?>
                                </span>
                            </td>
                            <td>
                                <a href="?edit=<?php echo $category['id']; ?>" class="btn btn-sm btn-primary" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?delete=<?php echo $category['id']; ?>" class="btn btn-sm btn-danger confirm-delete" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Category Modal -->
<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content bg-dark">
            <div class="modal-header">
                <h5 class="modal-title"><?php echo $edit_category ? 'Edit Category' : 'Add Category'; ?></h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <?php echo csrf_field(); ?>
                    
                    <?php if ($edit_category): ?>
                    <input type="hidden" name="id" value="<?php echo $edit_category['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="mb-3">
                        <label class="form-label">Name <span class="text-danger">*</span></label>
                        <input type="text" name="name" class="form-control" 
                               value="<?php echo $edit_category ? sanitize($edit_category['name']) : ''; ?>" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3"><?php echo $edit_category ? sanitize($edit_category['description']) : ''; ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Parent Category</label>
                        <select name="parent_id" class="form-select">
                            <option value="">None</option>
                            <?php foreach ($categories as $cat): 
                                if ($edit_category && $cat['id'] === $edit_category['id']) continue;
                            ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo ($edit_category && $edit_category['parent_id'] == $cat['id']) ? 'selected' : ''; ?>>
                                <?php echo sanitize($cat['name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Sort Order</label>
                        <input type="number" name="sort_order" class="form-control" 
                               value="<?php echo $edit_category ? $edit_category['sort_order'] : '0'; ?>" min="0">
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="is_active" id="is_active" 
                               <?php echo (!$edit_category || $edit_category['is_active']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">Active</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><?php echo $edit_category ? 'Update' : 'Add'; ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if ($edit_category): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    var modal = new bootstrap.Modal(document.getElementById('categoryModal'));
    modal.show();
});
</script>
<?php endif; ?>

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