<?php
require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';

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

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

$conn = db_connect();

try {
    $procedure_id = isset($_POST['procedure_id']) ? intval($_POST['procedure_id']) : 0;
    $instructions = isset($_POST['instructions']) ? trim($_POST['instructions']) : '';
    $followup_date = isset($_POST['followup_date']) ? $_POST['followup_date'] : null;
    
    if ($procedure_id <= 0) {
        throw new Exception('Invalid procedure ID');
    }
    
    // Verify procedure exists and get details
    $check_sql = "SELECT ep.*, p.patient_id, p.patient_number,
                  CONCAT(u.first_name, ' ', u.last_name) as patient_name,
                  pv.visit_id
                  FROM ent_procedures ep
                  INNER JOIN patients p ON ep.patient_id = p.patient_id
                  INNER JOIN users u ON p.user_id = u.user_id
                  LEFT JOIN patient_visits pv ON ep.visit_id = pv.visit_id
                  WHERE ep.procedure_id = ?";
    $stmt = $conn->prepare($check_sql);
    $stmt->bind_param('i', $procedure_id);
    $stmt->execute();
    $procedure = $stmt->get_result()->fetch_assoc();
    
    if (!$procedure) {
        throw new Exception('Procedure not found');
    }
    
    $conn->begin_transaction();
    
    // Update procedure status
    $update_proc_sql = "UPDATE ent_procedures 
                        SET status = 'COMPLETED',
                            post_op_status = 'DISCHARGED',
                            discharge_datetime = NOW(),
                            discharge_instructions = ?,
                            followup_date = ?
                        WHERE procedure_id = ?";
    $stmt = $conn->prepare($update_proc_sql);
    $stmt->bind_param('ssi', $instructions, $followup_date, $procedure_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update procedure status');
    }
    
    // Update patient visit status
    if ($procedure['visit_id']) {
        $update_visit_sql = "UPDATE patient_visits 
                            SET visit_status = 'DISCHARGED',
                                discharge_datetime = NOW()
                            WHERE visit_id = ?";
        $stmt = $conn->prepare($update_visit_sql);
        $stmt->bind_param('i', $procedure['visit_id']);
        $stmt->execute();
    }
    
    // Create discharge summary nursing note
    $note_sql = "INSERT INTO consultations (
                    patient_id, visit_id, doctor_id, consultation_type,
                    chief_complaint, clinical_notes, status,
                    consultation_date, start_time, end_time, created_at
                 ) VALUES (?, ?, ?, 'NURSING_NOTE', ?, ?, 'COMPLETED',
                          CURDATE(), CURTIME(), CURTIME(), NOW())";
    
    $stmt = $conn->prepare($note_sql);
    $user_id = $_SESSION['user_id'];
    $title = "Patient Discharge Summary";
    
    $note_content = "DISCHARGE SUMMARY\n\n";
    $note_content .= "Patient: " . $procedure['patient_name'] . " (" . $procedure['patient_number'] . ")\n";
    $note_content .= "Procedure: " . $procedure['procedure_name'] . "\n";
    $note_content .= "Discharge Date/Time: " . date('Y-m-d H:i:s') . "\n";
    $note_content .= "Discharged By: " . $_SESSION['user_name'] . " (Head Nurse)\n\n";
    
    $note_content .= "DISCHARGE CONDITION:\n";
    $note_content .= "Patient stable and ready for discharge\n";
    $note_content .= "All discharge criteria met\n";
    $note_content .= "Vital signs within normal limits\n\n";
    
    if (!empty($instructions)) {
        $note_content .= "DISCHARGE INSTRUCTIONS:\n" . $instructions . "\n\n";
    }
    
    if (!empty($followup_date)) {
        $note_content .= "FOLLOW-UP APPOINTMENT:\n";
        $note_content .= "Scheduled for: " . date('F d, Y', strtotime($followup_date)) . "\n\n";
    }
    
    $note_content .= "Patient/Family educated on:\n";
    $note_content .= "- Wound care and signs of infection\n";
    $note_content .= "- Medication schedule and instructions\n";
    $note_content .= "- Activity restrictions\n";
    $note_content .= "- When to seek medical attention\n";
    $note_content .= "- Follow-up appointment details\n\n";
    
    $note_content .= "Patient verbalized understanding of discharge instructions.\n";
    $note_content .= "Patient discharged in stable condition.";
    
    $stmt->bind_param('iiiss', 
        $procedure['patient_id'],
        $procedure['visit_id'],
        $user_id,
        $title,
        $note_content
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to create discharge summary');
    }
    
    $note_id = $stmt->insert_id;
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                     new_values, ip_address, user_agent)
                     VALUES (?, 'DISCHARGE_PATIENT', 'PROCEDURES', ?, 'DISCHARGE', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $log_data = json_encode([
        'procedure_id' => $procedure_id,
        'procedure_number' => $procedure['procedure_number'],
        'patient_id' => $procedure['patient_id'],
        'patient_name' => $procedure['patient_name'],
        'discharge_datetime' => date('Y-m-d H:i:s'),
        'followup_date' => $followup_date,
        'discharged_by' => $_SESSION['user_name']
    ]);
    $ip = $_SERVER['REMOTE_ADDR'];
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $stmt->bind_param('iisss', $user_id, $procedure_id, $log_data, $ip, $user_agent);
    $stmt->execute();
    
    // In production, generate discharge documents and send notifications
    /*
    // Generate discharge summary PDF
    // Send discharge instructions to patient email/SMS
    // Notify billing department for final bill
    // Schedule follow-up appointment
    */
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Patient successfully discharged',
        'discharge_note_id' => $note_id
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>