<?php

// Handle Add Category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_category'])) {
    $name = trim($_POST['category_name']);
    if (!empty($name)) {
        $stmt = $connection->prepare("INSERT INTO inventory_categories (name) VALUES (?)");
        $stmt->bind_param("s", $name);
        if ($stmt->execute()) {
            $_SESSION['msg'] = "Category added successfully.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Error adding category.";
            $_SESSION['type'] = "danger";
        }
    }
    header("Location: inventory_categories");
    exit;
}
// Handle Edit Category
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_category'])) {
    $id = (int)$_POST['edit_id'];
    $name = trim($_POST['edit_name']);
    
    if (!empty($name)) {
        $stmt = $connection->prepare("UPDATE inventory_categories SET name = ? WHERE id = ?");
        $stmt->bind_param("si", $name, $id);
        if ($stmt->execute()) {
            $_SESSION['msg'] = "Category updated.";
            $_SESSION['type'] = "success";
        } else {
            $_SESSION['msg'] = "Failed to update category.";
            $_SESSION['type'] = "danger";
        }
    }
    header("Location: inventory_categories");
    exit;
}


// Optional: Handle Delete Category
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    // Check if any item uses this category
    $check = $connection->query("SELECT id FROM inventory_items WHERE category_id = $id LIMIT 1");
    if ($check->num_rows > 0) {
        $_SESSION['msg'] = "Cannot delete category. It's in use by inventory items.";
        $_SESSION['type'] = "warning";
    } else {
        $connection->query("DELETE FROM inventory_categories WHERE id = $id");
        $_SESSION['msg'] = "Category deleted.";
        $_SESSION['type'] = "danger";
    }
    header("Location: inventory_categories");
    exit;
}


// Fetch categories
$categories = $connection->query("SELECT * FROM inventory_categories ORDER BY id DESC");
?>

<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading d-flex justify-content-between align-items-center'>
            <h4 class='text-center'>Inventory Categories</h4>
            <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#addCategoryModal">
                <i class="fa fa-plus"></i> Add Category
            </button>
        </div>

        <div class='panel-body' style='padding: 20px;'>
            <table class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Category Name</th>
                        <th> Created on</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php $sn = 1; while ($row = $categories->fetch_assoc()): ?>
                        <tr>
                            <td><?= $sn++ ?></td>
                            <td><?= htmlspecialchars($row['name']) ?></td>
                            <td><?= date("d M Y, h:i A", strtotime($row['created_at'])) ?></td>
                            <td>
    <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#editCategoryModal<?= $row['id'] ?>">
        <i class="fas fa-edit"></i> Edit
    </button>

    <a href="?delete=<?= $row['id'] ?>" onclick="return confirm('Delete this category?')" class="btn btn-sm btn-danger">
        <i class="fa fa-trash"></i>
    </a>
</td>

                        </tr>
                    <?php endwhile; ?>
                    <?php if ($categories->num_rows === 0): ?>
                        <tr><td colspan="4" class="text-center text-muted">No categories found.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php
$categories->data_seek(0); // Reset pointer to start
while ($row = $categories->fetch_assoc()):
?>
<!-- Edit Modal for Category ID <?= $row['id'] ?> -->
<div class="modal fade" id="editCategoryModal<?= $row['id'] ?>" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
        <form method="POST" action="">
            <div class="modal-header bg-info text-white">
                <h5 class="modal-title">Edit Category</h5>
                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
            </div>

            <div class="modal-body">
                <input type="hidden" name="edit_id" value="<?= $row['id'] ?>">
                <div class="form-group">
                    <label>Category Name</label>
                    <input type="text" name="edit_name" class="form-control" value="<?= htmlspecialchars($row['name']) ?>" required>
                </div>
            </div>

            <div class="modal-footer">
                <button type="submit" name="edit_category" class="btn btn-info">
                    <i class="fa fa-save"></i> Update
                </button>
            </div>
        </form>
    </div>
  </div>
</div>
<?php endwhile; ?>

        </div>
    </div>
</div>

<!-- ✅ Add Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1" role="dialog" aria-labelledby="addCategoryModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
        <form method="POST" action="">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="addCategoryModalLabel">Add New Category</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span>&times;</span>
                </button>
            </div>

            <div class="modal-body">
                <div class="form-group">
                    <label>Category Name <span class="text-danger">*</span></label>
                    <input type="text" name="category_name" class="form-control" required>
                </div>
            </div>

            <div class="modal-footer">
                <button type="submit" name="add_category" class="btn btn-success">
                    <i class="fa fa-save"></i> Save
                </button>
            </div>
        </form>
    </div>
  </div>
</div>
