35776-vm/api/patients.php
2025-11-16 17:25:40 +00:00

64 lines
2.6 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../db/db_setup.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 received.';
echo json_encode($response);
exit;
}
// Basic validation
if (empty($input['first_name']) || empty($input['last_name']) || empty($input['date_of_birth']) || empty($input['gender']) || empty($input['contact_number'])) {
$response['message'] = 'All fields are required.';
} else {
try {
$pdo = db();
$stmt = $pdo->prepare("INSERT INTO patients (first_name, last_name, date_of_birth, gender, contact_number) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([
htmlspecialchars($input['first_name']),
htmlspecialchars($input['last_name']),
$input['date_of_birth'],
htmlspecialchars($input['gender']),
htmlspecialchars($input['contact_number'])
]);
$patientId = $pdo->lastInsertId();
$response = [
'status' => 'success',
'message' => 'Patient registered successfully.',
'patient' => [
'id' => $patientId,
'first_name' => htmlspecialchars($input['first_name']),
'last_name' => htmlspecialchars($input['last_name']),
'date_of_birth' => $input['date_of_birth'],
'gender' => htmlspecialchars($input['gender']),
'contact_number' => htmlspecialchars($input['contact_number']),
'created_at' => date('Y-m-d H:i:s')
]
];
} catch (PDOException $e) {
// In a real app, log this error. Don't expose it to the user.
$response['message'] = 'Database error: ' . $e->getMessage();
}
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
try {
$pdo = db();
$stmt = $pdo->query("SELECT id, first_name, last_name, date_of_birth, gender, contact_number, DATE_FORMAT(created_at, '%Y-%m-%d') as registration_date FROM patients ORDER BY created_at DESC LIMIT 20");
$patients = $stmt->fetchAll();
$response = ['status' => 'success', 'patients' => $patients];
} catch (PDOException $e) {
$response['message'] = 'Database error: ' . $e->getMessage();
}
}
echo json_encode($response);