<?php
session_start();
require_once __DIR__ . '/db.php';

header('Content-Type: application/json');

// Ensure it's a POST request
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method.']);
    exit();
}

$patient_no = isset($_POST['patient_no']) ? trim($_POST['patient_no']) : '';
$field = isset($_POST['field']) ? trim($_POST['field']) : '';
$value = isset($_POST['value']) ? trim($_POST['value']) : '';

// Validate inputs
if (empty($patient_no) || empty($field)) {
    echo json_encode(['status' => 'error', 'message' => 'Missing required data.']);
    exit();
}

// Security: Whitelist the ONLY columns allowed to be updated by this script
$allowed_fields = ['blood_group', 'allergies', 'medical_conditions'];

if (!in_array($field, $allowed_fields)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid field update attempt.']);
    exit();
}

// Default empty values back to standard string to prevent NULL UI errors
if (empty($value)) {
    if ($field === 'blood_group') {
        $value = 'NA';
    } else {
        $value = 'None Reported';
    }
}

// Execute the update
$sql = "UPDATE patient SET {$field} = ? WHERE patient_no = ?";
$stmt = $conn->prepare($sql);

if ($stmt) {
    $stmt->bind_param("ss", $value, $patient_no);
    
    if ($stmt->execute()) {
        echo json_encode(['status' => 'success', 'message' => 'Record updated.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Database error: ' . $stmt->error]);
    }
    $stmt->close();
} else {
    echo json_encode(['status' => 'error', 'message' => 'Failed to prepare statement.']);
}

$conn->close();
?>