37241-vm/api/fee_structures_post.php
2026-01-03 08:40:36 +00:00

97 lines
3.3 KiB
PHP

<?php
// api/fee_structures_post.php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../includes/uuid.php';
$response = [
'status' => 'error',
'message' => 'Invalid request.'
];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
if (json_last_error() !== JSON_ERROR_NONE) {
$response['message'] = 'Invalid JSON payload.';
http_response_code(400);
echo json_encode($response);
exit;
}
// Basic validation
if (empty($input['name']) || empty($input['academic_year']) || empty($input['lines']) || !is_array($input['lines'])) {
$response['message'] = 'Missing required fields: name, academic_year, and lines array.';
http_response_code(400);
echo json_encode($response);
exit;
}
$pdo = db();
$pdo->beginTransaction();
try {
$fee_structure_id = uuid_v4();
$status = $input['status'] ?? 'Draft';
$stmt = $pdo->prepare(
"INSERT INTO fee_structures (id, name, academic_year, status) VALUES (?, ?, ?, ?)"
);
$stmt->execute([$fee_structure_id, $input['name'], $input['academic_year'], $status]);
$lines = [];
foreach ($input['lines'] as $line) {
if (empty($line['description']) || !isset($line['amount']) || empty($line['revenue_account_code'])) {
throw new Exception('Each line must have a description, amount, and revenue_account_code.');
}
// Get revenue_account_id from code
$stmt_acc = $pdo->prepare("SELECT id FROM accounts WHERE account_code = ? AND account_type = 'Revenue'");
$stmt_acc->execute([$line['revenue_account_code']]);
$revenue_account = $stmt_acc->fetch(PDO::FETCH_ASSOC);
if (!$revenue_account) {
throw new Exception("Invalid or non-revenue account code provided: {" . $line['revenue_account_code'] . "}");
}
$revenue_account_id = $revenue_account['id'];
$line_id = uuid_v4();
$stmt_line = $pdo->prepare(
"INSERT INTO fee_structure_lines (id, fee_structure_id, description, amount, revenue_account_id) VALUES (?, ?, ?, ?, ?)"
);
$stmt_line->execute([$line_id, $fee_structure_id, $line['description'], $line['amount'], $revenue_account_id]);
$lines[] = [
'id' => $line_id,
'description' => $line['description'],
'amount' => $line['amount'],
'revenue_account_code' => $line['revenue_account_code']
];
}
$pdo->commit();
$response['status'] = 'success';
$response['message'] = 'Fee structure created successfully.';
$response['data'] = [
'id' => $fee_structure_id,
'name' => $input['name'],
'academic_year' => $input['academic_year'],
'status' => $status,
'lines' => $lines
];
http_response_code(201);
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
$response['message'] = 'Error creating fee structure: ' . $e->getMessage();
http_response_code(500);
}
}
echo json_encode($response);