<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
include('con.php');
include('header.php');

/* ===== LOGIN CHECK ===== */
if (!isset($_SESSION['phone'])) {
    header("Location: login.php");
    exit;
}

$username = $_SESSION['phone'];

/* ===== ADMIN CHECK ===== */
if ($username != "9803416023") {
    http_response_code(404);
    echo "<h2 style='text-align:center;margin-top:100px;'>404 - Page Not Found</h2>";
    exit;
}

$successMsg = null;
$errorMsg = null;

/* ===== UPDATE PRICE ===== */
if (isset($_POST['update_price'])) {

    $id      = intval($_POST['id']);
    $service = trim($_POST['service']);
    $rate    = floatval($_POST['rate']);

    if ($id <= 0 || empty($service) || $rate < 0) {
        $errorMsg = "Invalid input.";
    } else {

        $stmt = $ahk_conn->prepare("UPDATE price SET service=?, rate=? WHERE id=?");
        $stmt->bind_param("sdi", $service, $rate, $id);

        if ($stmt->execute()) {
            $successMsg = "Price updated successfully.";
        } else {
            $errorMsg = "Update failed.";
        }
    }
}

/* ===== DELETE PRICE ===== */
if (isset($_POST['delete_price'])) {

    $id = intval($_POST['id']);

    if ($id > 0) {
        $stmt = $ahk_conn->prepare("DELETE FROM price WHERE id=?");
        $stmt->bind_param("i", $id);

        if ($stmt->execute()) {
            $successMsg = "Price deleted successfully.";
        } else {
            $errorMsg = "Delete failed.";
        }
    }
}

/* ===== FETCH PRICE LIST ===== */
$result = mysqli_query($ahk_conn, "SELECT id, service, rate FROM price ORDER BY id DESC");
?>

<!DOCTYPE html>
<html>
<head>
<title>Price Management</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
.card-box{
    background:#fff;
    padding:25px;
    border-radius:15px;
    box-shadow:0 8px 25px rgba(0,0,0,.1)
}
</style>
</head>

<body class="bg-light">

<div class="container py-5">
<div class="card-box">

<h4 class="mb-4 text-primary">Price Management</h4>

<table class="table table-bordered text-center align-middle">
<thead class="table-dark">
<tr>
<th>ID</th>
<th>Service</th>
<th>Rate (₹)</th>
<th width="180">Action</th>
</tr>
</thead>
<tbody>

<?php if (mysqli_num_rows($result) > 0): ?>
<?php while ($row = mysqli_fetch_assoc($result)): ?>
<tr>

<form method="POST" class="d-inline">
<td><?= $row['id'] ?></td>

<td>
<input type="text" name="service"
value="<?= htmlspecialchars($row['service']) ?>"
class="form-control" required>
</td>

<td>
<input type="number" step="0.01" name="rate"
value="<?= $row['rate'] ?>"
class="form-control" required>
</td>

<td>
<input type="hidden" name="id" value="<?= $row['id'] ?>">

<button type="submit" name="update_price"
class="btn btn-success btn-sm">
Update
</button>

<button type="button"
class="btn btn-danger btn-sm"
onclick="confirmDelete(<?= $row['id'] ?>)">
Delete
</button>
</td>
</form>

</tr>
<?php endwhile; ?>
<?php else: ?>
<tr>
<td colspan="4">No Price Records Found</td>
</tr>
<?php endif; ?>

</tbody>
</table>

</div>
</div>

<!-- Hidden Delete Form -->
<form method="POST" id="deleteForm">
<input type="hidden" name="id" id="delete_id">
<input type="hidden" name="delete_price" value="1">
</form>

<script>
function confirmDelete(id) {
    Swal.fire({
        title: 'Are you sure?',
        text: "This record will be permanently deleted!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById("delete_id").value = id;
            document.getElementById("deleteForm").submit();
        }
    });
}
</script>

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

<?php if ($errorMsg): ?>
<script>
Swal.fire({
    icon: 'error',
    title: 'Error',
    text: <?= json_encode($errorMsg) ?>
});
</script>
<?php endif; ?>

<?php include('footer.php'); ?>
</body>
</html>