<?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;
    $complication_type = isset($_POST['complication_type']) ? $_POST['complication_type'] : '';
    $severity = isset($_POST['severity']) ? $_POST['severity'] : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $actions_taken = isset($_POST['actions_taken']) ? trim($_POST['actions_taken']) : '';
    
    if ($procedure_id <= 0 || empty($complication_type) || empty($severity) || empty($description)) {
        throw new Exception('Missing required fields');
    }
    
    // Validate severity
    $valid_severities = ['MILD', 'MODERATE', 'SEVERE', 'CRITICAL'];
    if (!in_array($severity, $valid_severities)) {
        throw new Exception('Invalid severity level');
    }
    
    // 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,
                  d.doctor_id, doc_u.email as doctor_email,
                  CONCAT(doc_u.first_name, ' ', doc_u.last_name) as doctor_name
                  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 doctors d ON ep.doctor_id = d.doctor_id
                  LEFT JOIN users doc_u ON d.user_id = doc_u.user_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 critical nursing note for the complication
    $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 = "*** CRITICAL *** Post-Procedure Complication Reported";
    
    $note_content = "*** POST-PROCEDURE COMPLICATION ***\n\n";
    $note_content .= "REPORTED: " . date('Y-m-d H:i:s') . "\n";
    $note_content .= "PATIENT: " . $procedure['patient_name'] . " (" . $procedure['patient_number'] . ")\n";
    $note_content .= "PROCEDURE: " . $procedure['procedure_name'] . "\n";
    $note_content .= "PROCEDURE #: " . $procedure['procedure_number'] . "\n\n";
    $note_content .= "COMPLICATION TYPE: " . $complication_type . "\n";
    $note_content .= "SEVERITY: " . $severity . "\n\n";
    $note_content .= "DESCRIPTION:\n" . $description . "\n\n";
    
    if (!empty($actions_taken)) {
        $note_content .= "IMMEDIATE ACTIONS TAKEN:\n" . $actions_taken . "\n\n";
    }
    
    $note_content .= "PHYSICIAN NOTIFIED: " . $procedure['doctor_name'] . "\n";
    $note_content .= "REPORTED BY: " . $_SESSION['user_name'] . " (Head Nurse)\n";
    
    $stmt->bind_param('iiiss', 
        $procedure['patient_id'],
        $procedure['visit_id'],
        $user_id,
        $title,
        $note_content
    );
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to record complication report');
    }
    
    $note_id = $stmt->insert_id;
    
    // Update procedure status if severe/critical
    if (in_array($severity, ['SEVERE', 'CRITICAL'])) {
        $update_sql = "UPDATE ent_procedures 
                       SET status = 'COMPLICATED',
                           post_op_status = 'CRITICAL',
                           post_procedure_notes = CONCAT(
                               COALESCE(post_procedure_notes, ''), 
                               '\n\n*** COMPLICATION REPORTED: ', ?, ' - ', ?, ' ***'
                           )
                       WHERE procedure_id = ?";
        $stmt = $conn->prepare($update_sql);
        $stmt->bind_param('ssi', $complication_type, $severity, $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 (?, 'REPORT_COMPLICATION', 'PROCEDURES', ?, 'COMPLICATION', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $log_data = json_encode([
        'procedure_id' => $procedure_id,
        'procedure_number' => $procedure['procedure_number'],
        'patient_name' => $procedure['patient_name'],
        'complication_type' => $complication_type,
        'severity' => $severity,
        'reported_at' => date('Y-m-d H:i:s'),
        'physician_notified' => $procedure['doctor_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, send immediate notifications:
    // 1. Email/SMS to responsible physician
    // 2. Alert to Head Nurse dashboard
    // 3. Notification to hospital administration if CRITICAL
    
    /*
    if ($severity === 'CRITICAL') {
        // Send emergency notification
        $notification_sql = "INSERT INTO notifications (user_id, title, message, priority, type)
                           VALUES (?, 'CRITICAL Complication', ?, 'URGENT', 'COMPLICATION')";
        // Notify doctor, head nurse, administration
    }
    */
    
    $conn->commit();
    
    // Return success with severity-based message
    $message = 'Complication report submitted successfully. ';
    if ($severity === 'CRITICAL') {
        $message .= 'Emergency response protocol initiated. Physician has been notified immediately.';
    } elseif ($severity === 'SEVERE') {
        $message .= 'Physician has been notified and will respond promptly.';
    } else {
        $message .= 'Physician has been notified.';
    }
    
    echo json_encode([
        'success' => true,
        'message' => $message,
        'note_id' => $note_id,
        'severity' => $severity
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>