34567-vm/taxes/create.php
2025-10-02 20:43:00 +00:00

49 lines
1.3 KiB
PHP

<?php
require_once '../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);
$name = $data['name'] ?? null;
$rate = $data['rate'] ?? null;
if (!$name || !isset($rate)) {
http_response_code(400);
echo json_encode(['error' => 'Missing required fields: name, rate']);
exit;
}
if (!is_numeric($rate) || $rate < 0 || $rate > 100) {
http_response_code(400);
echo json_encode(['error' => 'Invalid rate. Must be a number between 0 and 100.']);
exit;
}
try {
$pdo = db();
$stmt = $pdo->prepare("INSERT INTO taxes (name, rate) VALUES (?, ?)");
$stmt->execute([$name, $rate]);
$id = $pdo->lastInsertId();
http_response_code(201);
echo json_encode(['success' => 'Tax created successfully', 'id' => $id]);
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) { // Duplicate entry
http_response_code(409);
echo json_encode(['error' => 'A tax with this name already exists.']);
} else {
http_response_code(500);
echo json_encode(['error' => 'Database error: ' . $e->getMessage()]);
}
}