<?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;
    $checklist = isset($_POST['checklist']) ? $_POST['checklist'] : [];
    $notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';
    
    if ($procedure_id <= 0) {
        throw new Exception('Invalid procedure ID');
    }
    
    // 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();
    
    // Update procedure with checklist
    $checklist_json = json_encode($checklist);
    $update_sql = "UPDATE ent_procedures 
                   SET pre_procedure_checklist = ?,
                       status = CASE 
                           WHEN status = 'SCHEDULED' THEN 'PRE_OP' 
                           ELSE status 
                       END
                   WHERE procedure_id = ?";
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param('si', $checklist_json, $procedure_id);
    
    if (!$stmt->execute()) {
        throw new Exception('Failed to save checklist');
    }
    
    // Create nursing note for pre-op preparation
    if (!empty($notes) || !empty($checklist)) {
        $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 = "Pre-Procedure Checklist Completed";
        $note_content = "Pre-operative checklist completed for procedure #" . $procedure['procedure_number'] . "\n\n";
        $note_content .= "Checklist items completed: " . count($checklist) . "\n";
        if (!empty($notes)) {
            $note_content .= "\nNotes: " . $notes;
        }
        
        $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 (?, 'PREOP_CHECKLIST', 'PROCEDURES', ?, 'PROCEDURE', ?, ?, ?)";
    $stmt = $conn->prepare($activity_sql);
    $log_data = json_encode([
        'procedure_id' => $procedure_id,
        'procedure_number' => $procedure['procedure_number'],
        'checklist_items' => count($checklist),
        'notes' => $notes
    ]);
    $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' => 'Pre-operative checklist saved successfully'
    ]);
    
} catch (Exception $e) {
    if ($conn->connect_errno === 0) {
        $conn->rollback();
    }
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>