<?php
include('con.php');

$msg = '';

/* Handle status update only */
if (isset($_POST['update_status'])) {
    $id = intval($_POST['history_id']);
    $status = intval($_POST['status']);

    mysqli_query($ahk_conn, "UPDATE mvcc SET status='$status' WHERE id='$id'");
    $msg = "Status updated successfully!";
}

/* Fetch MVCC records */
$result = mysqli_query(
    $ahk_conn,
    "SELECT * FROM mvcc 
WHERE status = 0 OR status = 1
ORDER BY id DESC"
);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MVCC History (Admin)</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>

<body>
<div class="container mt-5">
<h4 class="text-center mb-4 text-primary">MVCC Requests</h4>

<?php if ($msg): ?>
<script>
Swal.fire({
    icon: 'success',
    title: 'Done',
    text: <?php echo json_encode($msg); ?>
});
</script>
<?php endif; ?>

<table class="table table-bordered table-striped align-middle text-center">
<thead class="table-dark">
<tr>
    <th>ID</th>
    <th>Name</th>
    <th>EPIC No</th>
    <th>Mobile No</th>
    <th>Date</th>
    <th>Status</th>
    <th>Update Status</th>
</tr>
</thead>

<tbody>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<tr>
    <td><?php echo $row['id']; ?></td>
    <td><?php echo htmlspecialchars($row['name']); ?></td>
    <td><?php echo htmlspecialchars($row['epicno']); ?></td>
    <td><?php echo htmlspecialchars($row['mobileno']); ?></td>
    <td><?php echo htmlspecialchars($row['date']); ?></td>

    <td>
        <?php
        if ($row['status'] == 0) echo "<span class='badge bg-warning'>Pending</span>";
        elseif ($row['status'] == 1) echo "<span class='badge bg-info'>Processing</span>";
        elseif ($row['status'] == 2) echo "<span class='badge bg-success'>Completed</span>";
        ?>
    </td>

    <td>
        <form method="POST">
            <select name="status" class="form-select mb-1">
                <option value="0" <?= ($row['status']==0)?'selected':''; ?>>Pending</option>
                <option value="1" <?= ($row['status']==1)?'selected':''; ?>>Processing</option>
                <option value="2" <?= ($row['status']==2)?'selected':''; ?>>Completed</option>
            </select>

            <input type="hidden" name="history_id" value="<?php echo $row['id']; ?>">

            <button type="submit" name="update_status" class="btn btn-sm btn-primary w-100">
                Update
            </button>
        </form>
    </td>
</tr>
<?php endwhile; ?>
</tbody>
</table>

</div>
</body>
</html>
