<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");
require_once 'db.php';
try {
// Ensure it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception("Invalid request method");
}
// Get the raw POST data
$rawData = file_get_contents("php://input");
$data = json_decode($rawData, true);
// Validate required fields
$requiredFields = [
'user_id', 'name', 'phone', 'state',
'district', 'full_address', 'products'
];
foreach ($requiredFields as $field) {
if (!isset($data[$field]) || empty($data[$field])) {
throw new Exception("Missing required field: $field");
}
}
// Validate products is an array and not empty
if (!is_array($data['products']) || empty($data['products'])) {
throw new Exception("No products selected");
}
// Prepare the order data
$userId = $data['user_id'];
$name = $data['name'];
$phone = $data['phone'];
$state = $data['state'];
$district = $data['district'];
$fullAddress = $data['full_address'];
$products = json_encode($data['products']);
// Insert order into database
$query = "INSERT INTO medicine_orders (
user_id, name, phone, state, district,
full_address, products, order_date, status
) VALUES (
:user_id, :name, :phone, :state, :district,
:full_address, :products, NOW(), 'Pending'
)";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':user_id', $userId);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':phone', $phone);
$stmt->bindParam(':state', $state);
$stmt->bindParam(':district', $district);
$stmt->bindParam(':full_address', $fullAddress);
$stmt->bindParam(':products', $products);
$stmt->execute();
// Get the ID of the newly inserted order
$orderId = $pdo->lastInsertId();
// Return success response
echo json_encode([
'status' => 'success',
'message' => 'Order submitted successfully',
'order_id' => $orderId
]);
} catch (Exception $e) {
// Handle any errors
http_response_code(400);
echo json_encode([
'status' => 'error',
'message' => $e->getMessage()
]);
}
?>