34788-vm/order_handler.php
2025-10-08 11:45:34 +00:00

64 lines
2.0 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
// Protect this page - redirect to login if user is not logged in
if (!isset($_SESSION['user'])) {
header('Location: login.php');
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$user_id = $_SESSION['user']['id'];
$fuel_type = $_POST['fuel_type'];
$quantity = $_POST['quantity'];
// Validate input
if (empty($fuel_type) || empty($quantity) || !is_numeric($quantity) || $quantity <= 0) {
$_SESSION['order_error'] = "Invalid input.";
header('Location: dashboard.php');
exit;
}
try {
$pdoconn = db();
// Fetch the latest price
$stmt = $pdoconn->query("SELECT * FROM prices ORDER BY updated_at DESC LIMIT 1");
$latest_prices = $stmt->fetch();
if (!$latest_prices) {
$_SESSION['order_error'] = "Could not retrieve latest prices. Please try again later.";
header('Location: dashboard.php');
exit;
}
$price = ($fuel_type === 'petrol') ? $latest_prices['petrol_price'] : $latest_prices['diesel_price'];
$total_price = $quantity * $price;
// Insert the order
$sql = "INSERT INTO orders (user_id, fuel_type, quantity, total_price) VALUES (:user_id, :fuel_type, :quantity, :total_price)";
$stmt = $pdoconn->prepare($sql);
$stmt->execute([
':user_id' => $user_id,
':fuel_type' => $fuel_type,
':quantity' => $quantity,
':total_price' => $total_price
]);
$_SESSION['order_success'] = "Your order has been placed successfully!";
header('Location: dashboard.php');
exit;
} catch (PDOException $e) {
error_log("Order submission failed: " . $e->getMessage());
$_SESSION['order_error'] = "There was an error placing your order. Please try again.";
header('Location: dashboard.php');
exit;
}
} else {
// Redirect if accessed directly
header('Location: dashboard.php');
exit;
}
?>