<?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;
    $assessment_time = isset($_POST['assessment_time']) ? $_POST['assessment_time'] : date('H:i');
    $pain_level = isset($_POST['pain_level']) ? intval($_POST['pain_level']) : 0;
    $consciousness_level = isset($_POST['consciousness_level']) ? $_POST['consciousness_level'] : '';
    $nausea_status = isset($_POST['nausea_status']) ? $_POST['nausea_status'] : 'NONE';
    $wound_assessment = isset($_POST['wound_assessment']) ? trim($_POST['wound_assessment']) : '';
    $observations = isset($_POST['observations']) ? trim($_POST['observations']) : '';
    $interventions = isset($_POST['interventions']) ? trim($_POST['interventions']) : '';
    
    if ($procedure_id <= 0 || empty($observations)) {
        throw new Exception('Missing required fields');
    }
    
    // Verify procedure exists
    $check_sql = "SELECT ep.*, p.patient_id 
                  FROM ent_procedures ep
                  INNER JOIN patients p ON ep.patient_id = p.patient_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();
    
    // Create detailed post-op 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(), ?, ?, NOW())";
    
    $stmt = $conn->prepare($note_sql);
    $user_id = $_SESSION['user_id'];
    $title = "Post-Procedure Assessment - " . date('H:i');
    
    $note_content = "POST-PROCEDURE NURSING ASSESSMENT\n";
    $note_content .= "Procedure: " . $procedure['procedure_name'] . "\n";
    $note_content .= "Assessment Time: " . $assessment_time . "\n\n";
    $note_content .= "PAIN ASSESSMENT:\n";
    $note_content .= "Pain Level: " . $pain_level . "/10\n\n";
    $note_content .= "CONSCIOUSNESS:\n";
    $note_content .= "Level: " . $consciousness_level . "\n\n";
    $note_content .= "NAUSEA/VOMITING:\n";
    $note_content .= "Status: " . $nausea_status . "\n\n";
    
    if (!empty($wound_assessment)) {
        $note_content .= "WOUND/SITE ASSESSMENT:\n";
        $note_content .= $wound_assessment . "\n\n";
    }
    
    $note_content .= "NURSING OBSERVATIONS:\n";
    $note_content .= $observations . "\n\n";
    
    if (!empty($interventions)) {
        $note_content .= "INTERVENTIONS PROVIDED:\n";
        $note_content .= $interventions . "\n";
    }
    
    $stmt->bind_param('iiissss', 
        $procedure['patient_id'],
        $procedure['visit_id'],
        $user_id,
        $title,
        $note_content,
        $assessment_time,
        $assessment_time
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to save post-op note');
    }
    
    $note_id = $stmt->insert_id;
    
    // Update procedure with post-op notes
    $update_sql = "UPDATE ent_procedures 
                   SET post_procedure_notes = CONCAT(COALESCE(post_procedure_notes, ''), '\n\n', ?),
                       post_op_status = CASE 
                           WHEN post_op_status IS NULL THEN 'MONITORING'
                           ELSE post_op_status 
                       END
                   WHERE procedure_id = ?";
    $stmt = $conn->prepare($update_sql);
    $summary = date('H:i') . " - Pain: $pain_level/10, Consciousness: $consciousness_level";
    $stmt->bind_param('si', $summary, $procedure_id);
    $stmt->execute();
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, 
                     new_values, ip_address, user_agent)
                     VALUES (?, 'POSTOP_ASSESSMENT', 'PROCEDURES', ?, 'PROCEDURE', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $log_data = json_encode([
        'procedure_id' => $procedure_id,
        'procedure_number' => $procedure['procedure_number'],
        'assessment_time' => $assessment_time,
        'pain_level' => $pain_level,
        'consciousness_level' => $consciousness_level
    ]);
    $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();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Post-operative note recorded successfully',
        'note_id' => $note_id
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>