<?php
$conn = mysqli_connect("localhost","root","","ecommerce");
$type = $_GET['type'] ?? 'category';

/* INSERT */
if(isset($_POST['add'])){
    $name = $_POST['name'];
    $position = $_POST['position'];
    mysqli_query($conn,"INSERT INTO masters(type,name,position,status)
    VALUES('$type','$name','$position',1)");
    header("Location: masters.php?type=$type");
}

/* DELETE */
if(isset($_GET['delete'])){
    $id=$_GET['delete'];
    mysqli_query($conn,"DELETE FROM masters WHERE id=$id");
    header("Location: masters.php?type=$type");
}

/* FETCH */
$data = mysqli_query($conn,"SELECT * FROM masters WHERE type='$type' ORDER BY position ASC");

include 'layout.php';
?>

<h4 class="mb-3 text-capitalize"><?= $type ?> Manager</h4>

<form method="post" class="row g-2 mb-4">
<div class="col-md-5">
<input type="text" name="name" class="form-control" placeholder="Enter name" required>
</div>
<div class="col-md-3">
<input type="number" name="position" class="form-control" placeholder="Position" required>
</div>
<div class="col-md-2">
<button name="add" class="btn btn-primary">Add</button>
</div>
</form>

<table class="table table-bordered table-striped">
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Status</th>
<th>Action</th>
</tr>

<?php while($row=mysqli_fetch_assoc($data)): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['name'] ?></td>
<td><?= $row['position'] ?></td>
<td><?= $row['status'] ?></td>
<td>
<a href="masters.php?type=<?= $type ?>&delete=<?= $row['id'] ?>"
onclick="return confirm('Delete?')" class="btn btn-sm btn-danger">Delete</a>
</td>
</tr>
<?php endwhile; ?>
</table>
