<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../includes/functions.php';
requirePermission('category_management');

$pdo = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add' || $action === 'edit') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name']);
        $type = $_POST['type'];
        $description = trim($_POST['description']);
        $status = isset($_POST['status']) ? 1 : 0;

        if (empty($name)) {
            $_SESSION['error'] = 'Category name is required.';
        } else {
            try {
                if ($action === 'add') {
                    $stmt = $pdo->prepare("INSERT INTO categories (category_name, category_type, description, status) VALUES (?,?,?,?)");
                    $stmt->execute([$name, $type, $description, $status]);
                    $_SESSION['success'] = 'Category added successfully.';
                } else {
                    $stmt = $pdo->prepare("UPDATE categories SET category_name=?, category_type=?, description=?, status=? WHERE id=?");
                    $stmt->execute([$name, $type, $description, $status, $id]);
                    $_SESSION['success'] = 'Category updated successfully.';
                }
            } catch (PDOException $e) {
                $_SESSION['error'] = 'Error: ' . $e->getMessage();
            }
        }
        header('Location: categories.php');
        exit;
    }

    if ($action === 'delete') {
        $id = (int)$_POST['id'];
        $check = $pdo->prepare("SELECT COUNT(*) FROM products WHERE category_id=?");
        $check->execute([$id]);
        if ($check->fetchColumn() > 0) {
            $_SESSION['error'] = 'Cannot delete: this category is used by products.';
        } else {
            $stmt = $pdo->prepare("DELETE FROM categories WHERE id=?");
            $stmt->execute([$id]);
            $_SESSION['success'] = 'Category deleted successfully.';
        }
        header('Location: categories.php');
        exit;
    }
}

$categories = $pdo->query("SELECT c.*, (SELECT COUNT(*) FROM products WHERE category_id=c.id) as product_count FROM categories c ORDER BY c.category_type, c.category_name")->fetchAll();
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<div class="content-wrapper">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="page-title mb-0"><i class="fas fa-tags me-2"></i>Categories</h4>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#categoryModal" onclick="resetCategoryForm()"><i class="fas fa-plus me-1"></i>Add Category</button>
        </div>

        <?php if (isset($_SESSION['success'])): ?><div class="alert alert-success alert-dismissible"><?= $_SESSION['success']; unset($_SESSION['success']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
        <?php if (isset($_SESSION['error'])): ?><div class="alert alert-danger alert-dismissible"><?= $_SESSION['error']; unset($_SESSION['error']); ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="card">
            <div class="card-body">
                <div class="table-responsive">
                    <table id="categoriesTable" class="table table-hover datatable">
                        <thead><tr><th>Name</th><th>Type</th><th>Description</th><th>Products</th><th>Status</th><th>Actions</th></tr></thead>
                        <tbody>
                            <?php foreach ($categories as $c): ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($c['category_name']) ?></strong></td>
                                <td><span class="badge bg-<?= $c['category_type'] == 'Phone' ? 'primary' : ($c['category_type'] == 'Accessory' ? 'success' : 'warning') ?>"><?= $c['category_type'] ?></span></td>
                                <td><?= htmlspecialchars($c['description'] ?? '-') ?></td>
                                <td><span class="badge bg-secondary"><?= (int)$c['product_count'] ?></span></td>
                                <td><?= $c['status'] ? '<span class="badge badge-completed">Active</span>' : '<span class="badge badge-cancelled">Inactive</span>' ?></td>
                                <td>
                                    <button class="btn btn-sm btn-info" onclick="editCategory(<?= htmlspecialchars(json_encode($c)) ?>)"><i class="fas fa-edit"></i></button>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this category?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $c['id'] ?>">
                                        <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                    </form>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Category Modal -->
<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" id="catAction" value="add">
                <input type="hidden" name="id" id="catId" value="0">
                <div class="modal-header"><h5 class="modal-title" id="catModalTitle">Add Category</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Category Name *</label>
                        <input type="text" name="name" id="catName" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Type *</label>
                        <select name="type" id="catType" class="form-select" required>
                            <option value="Phone">Phone</option>
                            <option value="Accessory">Accessory</option>
                            <option value="Spare Part">Spare Part</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" id="catDesc" class="form-control" rows="2"></textarea>
                    </div>
                    <div class="form-check">
                        <input type="checkbox" name="status" id="catStatus" class="form-check-input" checked>
                        <label class="form-check-label">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">Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetCategoryForm() {
    $('#catAction').val('add');
    $('#catId').val(0);
    $('#catModalTitle').text('Add Category');
    $('#catName').val('');
    $('#catType').val('Phone');
    $('#catDesc').val('');
    $('#catStatus').prop('checked', true);
}
function editCategory(c) {
    $('#catAction').val('edit');
    $('#catId').val(c.id);
    $('#catModalTitle').text('Edit Category: ' + c.category_name);
    $('#catName').val(c.category_name);
    $('#catType').val(c.category_type);
    $('#catDesc').val(c.description);
    $('#catStatus').prop('checked', c.status == 1);
    $('#categoryModal').modal('show');
}
</script>

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