37 lines
1.1 KiB
PHP
37 lines
1.1 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../db/config.php';
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo json_encode(['error' => 'Method Not Allowed']);
|
|
exit;
|
|
}
|
|
|
|
$data = json_decode(file_get_contents('php://input'), true);
|
|
|
|
if (empty($data['name']) || !isset($data['price']) || !isset($data['cost']) || !isset($data['quantity'])) {
|
|
http_response_code(400);
|
|
echo json_encode(['error' => 'Missing required fields: name, price, cost, and quantity']);
|
|
exit;
|
|
}
|
|
|
|
$name = $data['name'];
|
|
$description = $data['description'] ?? null;
|
|
$price = $data['price'];
|
|
$cost = $data['cost'];
|
|
$quantity = $data['quantity'];
|
|
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("INSERT INTO products (name, description, price, cost, quantity) VALUES (?, ?, ?, ?, ?)");
|
|
$stmt->execute([$name, $description, $price, $cost, $quantity]);
|
|
|
|
http_response_code(201);
|
|
echo json_encode(['message' => 'Product created successfully', 'id' => $pdo->lastInsertId()]);
|
|
} catch (PDOException $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
|
|
}
|