<?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'] === 'execute_final_discharge') {
        
        $staff_id = (int)($_SESSION['staff_id'] ?? 1);
        $episode_id = (int)$_POST['episode_id'];
        $visit_id = (int)$_POST['visit_id'];
        $bed_id = (int)$_POST['bed_id'];
        
        $discharge_notes = trim($_POST['discharge_notes']);

        $conn->begin_transaction();

        // STRICT VALIDATION: Must have a Principal Diagnosis mapped to a GDRG
        $qDiag = $conn->query("SELECT id, gdrg_mapped_code FROM clinical_diagnoses WHERE visit_id = $visit_id AND is_principal = 1");
        if($qDiag->num_rows === 0) {
            throw new Exception("Clinical Coding Error: Patient has no Principal Diagnosis. The attending doctor must enter a Principal Diagnosis before discharge can be executed.");
        }
        $diag = $qDiag->fetch_assoc();
        if(empty($diag['gdrg_mapped_code'])) {
            throw new Exception("Billing Map Error: The Principal Diagnosis is not mapped to a valid G-DRG code. Please contact the clinical coding team.");
        }

        // 1. Update Episode to Fully Discharged
        $stmtEp = $conn->prepare("UPDATE ipd_admission_episodes SET status = 'Discharged', discharge_date = NOW(), discharged_by = ?, discharge_notes = ? WHERE id = ?");
        $stmtEp->bind_param("isi", $staff_id, $discharge_notes, $episode_id);
        if (!$stmtEp->execute()) {
            throw new Exception("Failed to update admission episode.");
        }

        // 2. Free the Bed 
        $stmtBed = $conn->prepare("UPDATE ipd_beds SET occupancy_status = 'Vacant', bed_status = 'Housekeeping', status_changed_by = ?, last_status_change = NOW() WHERE id = ?");
        $stmtBed->bind_param("ii", $staff_id, $bed_id);
        if (!$stmtBed->execute()) {
            throw new Exception("Failed to release the bed.");
        }

        // 3. System Audit Log
        $ip_addr = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        $old_val = json_encode(['episode_id' => $episode_id, 'status' => 'Pending Discharge']);
        $new_val = json_encode(['episode_id' => $episode_id, 'status' => 'Discharged', 'gdrg_validated' => $diag['gdrg_mapped_code']]);
        
        $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' => 'Patient successfully discharged. Diagnosis validated & Bed vacated.']);
        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;
}
?>