<?php
session_start();
include '../layouts/dbconn.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check role permissions
$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ENT_DOCTOR', 'ENT_CONSULTANT', 'NURSE'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    echo json_encode(['success' => false, 'message' => 'Insufficient permissions']);
    exit();
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

$procedure_id = isset($input['procedure_id']) ? (int)$input['procedure_id'] : 0;
$note_type = isset($input['note_type']) ? $input['note_type'] : '';
$note_content = isset($input['note_content']) ? $input['note_content'] : '';

if (!$procedure_id || !$note_type || !$note_content) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit();
}

// Validate note type
$valid_note_types = ['procedure_notes', 'post_procedure_notes', 'complications', 'outcome'];
if (!in_array($note_type, $valid_note_types)) {
    echo json_encode(['success' => false, 'message' => 'Invalid note type']);
    exit();
}

// Update procedure notes
$update_sql = "UPDATE patient_procedures SET {$note_type} = ?, updated_at = NOW() WHERE procedure_id = ?";
$stmt = $conn->prepare($update_sql);
$stmt->bind_param('si', $note_content, $procedure_id);

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Notes saved successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to save notes']);
}

$conn->close();
?>