<?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;
    
    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
                  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
                  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');
    }
    
    // Check if procedure is in appropriate status
    if (!in_array($procedure['status'], ['SCHEDULED', 'PRE_OP'])) {
        throw new Exception('Procedure is not in a valid status to be marked ready');
    }
    
    $conn->begin_transaction();
    
    // Update procedure status to ready
    $update_sql = "UPDATE ent_procedures 
                   SET status = 'READY',
                       pre_op_completed_at = NOW(),
                       pre_op_completed_by = ?
                   WHERE procedure_id = ?";
    $stmt = $conn->prepare($update_sql);
    $user_id = $_SESSION['user_id'];
    $stmt->bind_param('ii', $user_id, $procedure_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to update procedure status');
    }
    
    // Create 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);
    $title = "Patient Ready for Procedure";
    $note_content = "Patient " . $procedure['patient_name'] . " (" . $procedure['patient_number'] . ") " .
                   "has been prepared and is ready for: " . $procedure['procedure_name'] . "\n" .
                   "Procedure #: " . $procedure['procedure_number'] . "\n" .
                   "All pre-operative requirements completed.\n" .
                   "Patient can proceed to procedure room.";
    
    $stmt->bind_param('iiiss', 
        $procedure['patient_id'],
        $procedure['visit_id'],
        $user_id,
        $title,
        $note_content
    );
    $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 (?, 'MARK_PROCEDURE_READY', 'PROCEDURES', ?, 'PROCEDURE', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $log_data = json_encode([
        'procedure_id' => $procedure_id,
        'procedure_number' => $procedure['procedure_number'],
        'patient_name' => $procedure['patient_name'],
        'marked_ready_at' => date('Y-m-d H:i:s')
    ]);
    $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, you might want to notify the doctor/OR staff
    // Send notification here
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Patient marked as ready for procedure'
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>