<?php
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);
ob_start();

require_once '../db.php';
header('Content-Type: application/json');

try {
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_discharge_notes') {
        
        $staff_id = (int)($_SESSION['staff_id'] ?? 1);
        $episode_id = (int)$_POST['edit_episode_id'];
        $new_notes = trim($_POST['edit_discharge_notes']);

        $conn->begin_transaction();

        $qOld = $conn->query("SELECT discharge_notes FROM ipd_admission_episodes WHERE id = $episode_id");
        $old_notes = $qOld->fetch_assoc()['discharge_notes'] ?? '';

        $stmtEp = $conn->prepare("UPDATE ipd_admission_episodes SET discharge_notes = ? WHERE id = ?");
        $stmtEp->bind_param("si", $new_notes, $episode_id);
        if (!$stmtEp->execute()) {
            throw new Exception("Failed to update discharge notes.");
        }

        // System Audit Log for the alteration
        $ip_addr = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        $old_val = json_encode(['episode_id' => $episode_id, 'notes' => $old_notes]);
        $new_val = json_encode(['episode_id' => $episode_id, 'notes' => $new_notes]);
        
        $stmtAud = $conn->prepare("INSERT INTO system_audit_logs (staff_id, action_type, table_name, record_id, old_values, new_values, ip_address) VALUES (?, 'UPDATE', 'ipd_admission_episodes', ?, ?, ?, ?)");
        $strEp = (string)$episode_id;
        $stmtAud->bind_param("issss", $staff_id, $strEp, $old_val, $new_val, $ip_addr);
        $stmtAud->execute();

        $conn->commit();
        ob_end_clean();
        echo json_encode(['status' => 'success', 'message' => 'Discharge notes updated successfully. Audit log created.']);
        exit;
    } else {
        throw new Exception("Invalid Action Request.");
    }
} catch (Exception $e) {
    if(isset($conn)) $conn->rollback();
    ob_end_clean();
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    exit;
}
?>