<?php

session_start();
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check authentication - doctors only
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$role_id = $_SESSION['role_id'];

$user_id = $_SESSION['user_id'];
$visit_id = isset($_GET['visit_id']) ? intval($_GET['visit_id']) : 0;
$patient_id = isset($_GET['patient_id']) ? intval($_GET['patient_id']) : 0;
$visit_details = null;

// Define the visit SQL query globally
$visit_sql = "SELECT
    pv.*,
    p.patient_id,
    p.patient_number,
    p.user_id,
    p.registration_type,
    p.insurance_provider_id,
    p.insurance_number,
    p.policy_number,
    p.employer,
    p.occupation,
    p.marital_status,
    p.blood_group,
    p.allergies,
    p.chronic_conditions,
    p.current_medications,
    p.family_medical_history,
    p.ent_history,
    p.preferred_language,
    u.full_name,
    u.date_of_birth,
    u.gender,
    u.email,
    u.phone_primary,
    u.address,
    u.emergency_contact_name,
    u.emergency_contact_phone
FROM patient_visits pv
JOIN patients p ON pv.patient_id = p.patient_id
JOIN users u ON p.user_id = u.user_id
WHERE pv.visit_id = ?";


// If patient_id provided but no visit, create a new visit
if ($patient_id > 0 && !$visit_details) {
    // Fetch patient details
    $patient_sql = "SELECT 
        p.*,
        u.full_name,
        u.date_of_birth,
        u.gender,
        u.email,
        u.phone_primary,
        u.address,
        u.emergency_contact_name,
        u.emergency_contact_phone
    FROM patients p
    JOIN users u ON p.user_id = u.user_id
    WHERE p.patient_id = ?";
    
    $stmt = $conn->prepare($patient_sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $patient_data = $stmt->get_result()->fetch_assoc();
    
    if ($patient_data) {
        // Create a new visit
        $conn->begin_transaction();
        
        try {
            // Generate visit number
            $visit_number_sql = "SELECT CONCAT('VISIT-', DATE_FORMAT(NOW(), '%Y%m%d'), '-', 
                                 LPAD(COALESCE(MAX(CAST(SUBSTRING(visit_number, -3) AS UNSIGNED)), 0) + 1, 3, '0')) as new_number
                                 FROM patient_visits 
                                 WHERE visit_number LIKE CONCAT('VISIT-', DATE_FORMAT(NOW(), '%Y%m%d'), '%')";
            $result = $conn->query($visit_number_sql);
            $visit_number = $result->fetch_assoc()['new_number'];
            
            // Insert new visit
            $insert_visit_sql = "INSERT INTO patient_visits 
                (visit_number, patient_id, visit_type, visit_source, registration_type, 
                 registration_date, status, registered_by) 
                VALUES (?, ?, 'CONSULTATION', 'WALK_IN', ?, NOW(), 'REGISTERED', ?)";
            
            $reg_type = $patient_data['registration_type'] ?? 'CASH';
            $stmt = $conn->prepare($insert_visit_sql);
            $stmt->bind_param("sisi", $visit_number, $patient_id, $reg_type, $user_id);
            $stmt->execute();
            $visit_id = $conn->insert_id;
            
            $conn->commit();
            
            // Fetch the newly created visit
            $stmt = $conn->prepare($visit_sql);
            $stmt->bind_param("i", $visit_id);
            $stmt->execute();
            $visit_details = $stmt->get_result()->fetch_assoc();
            
        } catch (Exception $e) {
            $conn->rollback();
            die("Error creating visit: " . $e->getMessage());
        }
    }
}

// Fetch all doctors for selection
$all_doctors_sql = "SELECT d.doctor_id, u.full_name, d.specialization, d.consultation_fee, d.commission_rate
                    FROM doctors d
                    JOIN users u ON d.user_id = u.user_id
                    WHERE d.is_active = 1";
$all_doctors_stmt = $conn->prepare($all_doctors_sql);
$all_doctors_stmt->execute();
$all_doctors = $all_doctors_stmt->get_result()->fetch_all(MYSQLI_ASSOC);


// Get doctor details for commission calculation
$doctor_sql = "SELECT d.* FROM doctors d WHERE d.user_id = ?";
$doctor_stmt = $conn->prepare($doctor_sql);
$doctor_stmt->bind_param("i", $user_id);
$doctor_stmt->execute();
$doctor_info = $doctor_stmt->get_result()->fetch_assoc();

// If we have visit details, split the name for display
if ($visit_details) {
    $name_parts = explode(' ', $visit_details['full_name'], 2);
    $visit_details['first_name'] = $name_parts[0];
    $visit_details['last_name'] = isset($name_parts[1]) ? $name_parts[1] : '';
    
    // Calculate age
    $dob = new DateTime($visit_details['date_of_birth']);
    $now = new DateTime();
    $visit_details['age'] = $now->diff($dob)->y;
}
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'New Consultation - AI Assistant')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link href="assets/libs/flatpickr/flatpickr.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    <style>
        .ai-assistant-panel {
            position: sticky;
            top: 20px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            border: 2px solid #e0e7ff;
        }
        
        .ai-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem;
            border-radius: 10px 10px 0 0;
        }
        
        /* ===== AI SUGGESTION IMPROVEMENTS ===== */
.ai-suggestion {
    background: #f8fafc;
    border-left: 4px solid #3b82f6;
    border-radius: 8px;
    padding: 1rem;
    margin-bottom: 1rem;
    cursor: pointer;
    transition: all 0.3s ease;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.ai-suggestion:hover {
    background: #eff6ff;
    transform: translateX(5px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.ai-suggestion.critical {
    border-left-color: #ef4444;
    background: #fef2f2;
    cursor: default;
}

.ai-suggestion.critical:hover {
    transform: none;
}

.ai-suggestion.warning {
    border-left-color: #f59e0b;
    background: #fffbeb;
}

/* SweetAlert Wide Modal */
.swal-wide {
    font-family: inherit;
}

.swal-wide .swal2-html-container {
    line-height: 1.6;
}
        
        .confidence-meter {
            width: 100%;
            height: 6px;
            background: #e2e8f0;
            border-radius: 3px;
            overflow: hidden;
            margin-top: 0.5rem;
        }
        
        .confidence-fill {
            height: 100%;
            background: linear-gradient(90deg, #10b981 0%, #059669 100%);
            transition: width 0.3s ease;
        }
        
        .drug-alert {
            background: #fef2f2;
            border: 2px solid #fecaca;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
            display: none;
        }
        
        .drug-alert.active {
            display: block;
            animation: shake 0.5s;
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-10px); }
            75% { transform: translateX(10px); }
        }
        
        .ai-thinking {
            display: none;
            text-align: center;
            padding: 1rem;
            color: #6366f1;
        }
        
        .ai-thinking.active {
            display: block;
        }
        
        .quick-action-btn {
            width: 100%;
            text-align: left;
            margin-bottom: 0.5rem;
            padding: 0.75rem;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            background: white;
            transition: all 0.2s;
        }
        
        .quick-action-btn:hover {
            background: #f8fafc;
            border-color: #3b82f6;
        }
        
        .section-header {
            background: #f8fafc;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
            font-weight: 600;
        }
        
        .patient-selector-card {
            border: 2px dashed #cbd5e1;
            border-radius: 12px;
            padding: 2rem;
            text-align: center;
            background: #f8fafc;
            margin-bottom: 2rem;
        }
        
        .patient-selector-card.has-patient {
            border: 2px solid #10b981;
            background: #f0fdf4;
        }
        
        /* ICD-10 Select2 Styling */
.icd10-result {
    padding: 5px 0;
}

.icd10-result .fw-bold {
    color: #2d7a2d;
}

/* Medication Select2 Styling */
.medication-result {
    padding: 5px 0;
}

.medication-result .fw-bold {
    color: #2d7a2d;
}

/* Medication Item Styling */
.medication-item {
    background: #f8f9fa;
    padding: 1rem;
    border-radius: 8px;
    border: 1px solid #dee2e6;
    transition: all 0.3s ease;
}

.medication-item:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.medication-info {
    margin-top: 0.5rem;
}

/* Select2 Bootstrap 5 Theme Enhancements */
.select2-container--bootstrap-5 .select2-selection {
    min-height: 38px;
    border-color: #ced4da;
}

.select2-container--bootstrap-5 .select2-dropdown {
    border-color: #26a69a;
}

.select2-container--bootstrap-5.select2-container--focus .select2-selection,
.select2-container--bootstrap-5.select2-container--open .select2-selection {
    border-color: #26a69a;
    box-shadow: 0 0 0 0.25rem rgba(38, 166, 154, 0.25);
}

.select2-container--bootstrap-5 .select2-results__option--highlighted {
    background-color: #26a69a !important;
    color: white;
}

.select2-container--bootstrap-5 .select2-results__option--selected {
    background-color: #e8f5e9;
}

.select2-container--bootstrap-5 .select2-search__field {
    border: 1px solid #ced4da;
    border-radius: 4px;
}

.select2-container--bootstrap-5 .select2-search__field:focus {
    border-color: #26a69a;
    outline: 0;
    box-shadow: 0 0 0 0.25rem rgba(38, 166, 154, 0.25);
}

/* Badge Styling for Stock Status */
.badge.bg-danger {
    background-color: #dc3545 !important;
}

.badge.bg-warning {
    background-color: #ffc107 !important;
    color: #000;
}

.badge.bg-success {
    background-color: #198754 !important;
}

/* Loading State for Select2 */
.select2-results__option.loading-results {
    text-align: center;
    color: #6c757d;
}

/* Disabled Remove Button Styling */
.medication-item:first-child .btn-outline-danger[disabled] {
    opacity: 0.3;
    cursor: not-allowed;
}
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">
                                    <i class="ri-stethoscope-line me-2"></i>New Consultation
                                    <span class="badge bg-primary ms-2">AI-Assisted</span>
                                </h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_consultations.php">Consultations</a></li>
                                        <li class="breadcrumb-item active">New Consultation</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (!$visit_details): ?>
                    <!-- Patient Selection Card -->
                    <div class="card patient-selector-card" id="patientSelectorCard">
                        <div class="card-body">
                            <i class="ri-user-search-line display-4 text-muted mb-3"></i>
                            <h4>Select a Patient to Start Consultation</h4>
                            <p class="text-muted">Search for an existing patient or register a new one</p>
                            <div class="row justify-content-center mt-4">
                                <div class="col-md-8">
                                    <div class="input-group input-group-lg">
                                        <input type="text" class="form-control" id="patientSearch" 
                                               placeholder="Search by name, patient number, phone...">
                                        <button class="btn btn-primary" type="button" onclick="searchPatients()">
                                            <i class="ri-search-line me-1"></i>Search
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-3">
                                <a href="register_patient.php" class="btn btn-outline-success">
                                    <i class="ri-user-add-line me-1"></i>Register New Patient
                                </a>
                            </div>
                            
                            <!-- Search Results -->
                            <div id="searchResults" class="mt-4" style="display:none;">
                                <h5 class="text-start mb-3">Search Results</h5>
                                <div id="searchResultsList"></div>
                            </div>
                        </div>
                    </div>
                    <?php else: ?>

                    <!-- Patient Info Banner -->
                    <div class="card bg-primary text-white mb-3">
                        <div class="card-body">
                            <div class="row align-items-center">
                                <div class="col-md-3">
                                    <h5 class="mb-0"><?php echo htmlspecialchars($visit_details['full_name']); ?></h5>
                                    <small><?php echo $visit_details['patient_number']; ?></small>
                                </div>
                                <div class="col-md-2">
                                    <strong>Age:</strong> <?php echo $visit_details['age']; ?> years
                                </div>
                                <div class="col-md-2">
                                    <strong>Gender:</strong> <?php echo $visit_details['gender']; ?>
                                </div>
                                <div class="col-md-2">
                                    <strong>Visit #:</strong> <?php echo $visit_details['visit_number']; ?>
                                </div>
                                <div class="col-md-3 text-end">
                                    <?php if ($visit_details['allergies']): ?>
                                    <span class="badge bg-danger">
                                        <i class="ri-alert-line me-1"></i>ALLERGIES
                                    </span>
                                    <?php endif; ?>
                                    <?php if ($visit_details['chronic_conditions']): ?>
                                    <span class="badge bg-warning">
                                        <i class="ri-heart-pulse-line me-1"></i>CHRONIC
                                    </span>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Main Consultation Form -->
                        <div class="col-lg-8">
                            <form id="consultationForm">
                                <input type="hidden" name="visit_id" value="<?php echo $visit_id; ?>">
                                <input type="hidden" name="patient_id" value="<?php echo $visit_details['patient_id']; ?>">
                                <input type="hidden" name="doctor_id" value="<?php echo $doctor_info['doctor_id']; ?>">
                                <input type="hidden" name="patient_age" value="<?php echo $visit_details['age']; ?>">
                                <input type="hidden" name="patient_gender" value="<?php echo $visit_details['gender']; ?>">

                                <!-- Consultation Type -->
                                <div class="card mb-3">
                                    <div class="card-header">
                                        <h5 class="mb-0">Consultation Type</h5>
                                    </div>
                                    <div class="card-body">
                                        <select class="form-select" name="consultation_type" required>
                                            <option value="INITIAL" selected>Initial Consultation</option>
                                            <option value="FOLLOW_UP">Follow-up Visit</option>
                                            <option value="SECOND_OPINION">Second Opinion</option>
                                            <option value="EMERGENCY">Emergency Consultation</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <!-- Doctor Selection -->
                                <div class="card mb-3">
                                    <div class="card-header">
                                        <h5 class="mb-0">Consulting Doctor</h5>
                                    </div>
                                    <div class="card-body">
                                        <select class="form-select" name="doctor_id" id="doctorSelect" required onchange="updateDoctorCommission()">
                                            <option value="">Select Doctor</option>
                                            <?php foreach ($all_doctors as $doc): ?>
                                                <option value="<?php echo $doc['doctor_id']; ?>"
                                                    data-fee="<?php echo $doc['consultation_fee']; ?>"
                                                    data-commission="<?php echo $doc['commission_rate']; ?>"
                                                    <?php echo ($doc['doctor_id'] == $doctor_info['doctor_id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($doc['full_name'] . ' (' . $doc['specialization'] . ')'); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>


                                <!-- Chief Complaint -->
                                <div class="card mb-3">
                                    <div class="card-header">
                                        <h5 class="mb-0">Chief Complaint</h5>
                                    </div>
                                    <div class="card-body">
                                        <textarea class="form-control" name="chief_complaint" id="chiefComplaint" 
                                                  rows="3" placeholder="Enter patient's main complaint..."
                                                  oninput="triggerAIAnalysis()" required></textarea>
                                        <small class="text-muted">
                                            <i class="ri-lightbulb-line me-1"></i>AI will suggest diagnoses as you type
                                        </small>
                                    </div>
                                </div>

                                <!-- History -->
                                <div class="card mb-3">
                                    <div class="card-header">
                                        <h5 class="mb-0">Medical History</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="section-header">History of Present Illness</div>
                                        <textarea class="form-control mb-3" name="history_present_illness" 
                                                  rows="4" id="historyPresent" oninput="triggerAIAnalysis()"></textarea>

                                        <div class="section-header">Past Medical History</div>
                                        <textarea class="form-control mb-3" name="past_medical_history" 
                                                  rows="3"><?php echo htmlspecialchars($visit_details['chronic_conditions'] ?? ''); ?></textarea>

                                        <div class="section-header">Family History</div>
                                        <textarea class="form-control mb-3" name="family_history" 
                                                  rows="2"><?php echo htmlspecialchars($visit_details['family_medical_history'] ?? ''); ?></textarea>

                                        <div class="section-header">Social History</div>
                                        <textarea class="form-control mb-3" name="social_history" 
                                                  rows="2" placeholder="Smoking, alcohol, occupation, lifestyle factors..."></textarea>

                                        <div class="section-header">Current Medications</div>
                                        <div class="alert alert-info">
                                            <?php if ($visit_details['current_medications']): ?>
                                                <?php echo nl2br(htmlspecialchars($visit_details['current_medications'])); ?>
                                            <?php else: ?>
                                                No current medications recorded
                                            <?php endif; ?>
                                        </div>

                                        <div class="section-header">Allergies</div>
                                        <?php if ($visit_details['allergies']): ?>
                                        <div class="alert alert-danger">
                                            <i class="ri-alert-line me-2"></i>
                                            <strong>ALLERGIES:</strong> <?php echo htmlspecialchars($visit_details['allergies']); ?>
                                        </div>
                                        <?php else: ?>
                                        <p class="text-muted">No known allergies</p>
                                        <?php endif; ?>
                                    </div>
                                </div>

                                <!-- ENT Examination -->
                                <div class="card mb-3">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <h5 class="mb-0">ENT Examination</h5>
                                        <button type="button" class="btn btn-sm btn-outline-primary" 
                                                onclick="loadExamTemplate()">
                                            <i class="ri-file-list-line me-1"></i>Load Template
                                        </button>
                                    </div>
                                    <div class="card-body">
                                        <!-- Ear Examination -->
                                        <div class="mb-3">
                                            <label class="form-label fw-bold">Ear Examination</label>
                                            <div class="row">
                                                <div class="col-md-6 mb-2">
                                                    <label class="form-label small">External Ear</label>
                                                    <textarea class="form-control" name="ear_external" rows="2" 
                                                              placeholder="External ear examination findings..."></textarea>
                                                </div>
                                                <div class="col-md-6 mb-2">
                                                    <label class="form-label small">Otoscopy</label>
                                                    <textarea class="form-control" name="ear_otoscopy" rows="2" 
                                                              placeholder="Tympanic membrane, canal findings..."></textarea>
                                                </div>
                                                <div class="col-md-12 mb-2">
                                                    <label class="form-label small">Hearing Assessment</label>
                                                    <textarea class="form-control" name="ear_hearing" rows="2" 
                                                              placeholder="Hearing tests, tuning fork tests..."></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Nose Examination -->
                                        <div class="mb-3">
                                            <label class="form-label fw-bold">Nose Examination</label>
                                            <div class="row">
                                                <div class="col-md-6 mb-2">
                                                    <label class="form-label small">External Nose</label>
                                                    <textarea class="form-control" name="nose_external" rows="2" 
                                                              placeholder="External nose examination..."></textarea>
                                                </div>
                                                <div class="col-md-6 mb-2">
                                                    <label class="form-label small">Rhinoscopy</label>
                                                    <textarea class="form-control" name="nose_rhinoscopy" rows="2" 
                                                              placeholder="Nasal mucosa, septum, turbinates..."></textarea>
                                                </div>
                                                <div class="col-md-12 mb-2">
                                                    <label class="form-label small">Endoscopy Findings</label>
                                                    <textarea class="form-control" name="nose_endoscopy" rows="2" 
                                                              placeholder="Endoscopic examination findings..."></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Throat Examination -->
                                        <div class="mb-3">
                                            <label class="form-label fw-bold">Throat Examination</label>
                                            <div class="row">
                                                <div class="col-md-6 mb-2">
                                                    <label class="form-label small">Oral Cavity</label>
                                                    <textarea class="form-control" name="throat_oral_cavity" rows="2" 
                                                              placeholder="Teeth, tongue, palate, buccal mucosa..."></textarea>
                                                </div>
                                                <div class="col-md-6 mb-2">
                                                    <label class="form-label small">Pharynx</label>
                                                    <textarea class="form-control" name="throat_pharynx" rows="2" 
                                                              placeholder="Pharyngeal examination..."></textarea>
                                                </div>
                                                <div class="col-md-12 mb-2">
                                                    <label class="form-label small">Larynx</label>
                                                    <textarea class="form-control" name="throat_larynx" rows="2" 
                                                              placeholder="Laryngoscopy findings..."></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Neck Examination -->
                                        <div class="mb-3">
                                            <label class="form-label fw-bold">Neck Examination</label>
                                            <div class="row">
                                                <div class="col-md-6 mb-2">
                                                    <label class="form-label small">Lymph Nodes</label>
                                                    <textarea class="form-control" name="neck_lymph_nodes" rows="2" 
                                                              placeholder="Cervical lymphadenopathy..."></textarea>
                                                </div>
                                                <div class="col-md-6 mb-2">
                                                    <label class="form-label small">Thyroid</label>
                                                    <textarea class="form-control" name="neck_thyroid" rows="2" 
                                                              placeholder="Thyroid examination..."></textarea>
                                                </div>
                                                <div class="col-md-12 mb-2">
                                                    <label class="form-label small">Masses/Other</label>
                                                    <textarea class="form-control" name="neck_masses" rows="2" 
                                                              placeholder="Any masses or abnormalities..."></textarea>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Cranial Nerves -->
                                        <div class="mb-3">
                                            <label class="form-label fw-bold">Cranial Nerves Assessment</label>
                                            <textarea class="form-control" name="cranial_nerves_exam" rows="3" 
                                                      placeholder="Relevant cranial nerve examination findings..."></textarea>
                                        </div>

                                        <!-- General Examination -->
                                        <div class="mb-3">
                                            <label class="form-label fw-bold">General Examination</label>
                                            <textarea class="form-control" name="general_examination" rows="3" 
                                                      placeholder="General appearance, vitals, systemic examination..."></textarea>
                                        </div>
                                    </div>
                                </div>

                                <!-- Diagnosis -->
                                <div class="card mb-3">
                                    <div class="card-header">
                                        <h5 class="mb-0">Diagnosis</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label class="form-label">Primary Diagnosis <span class="text-danger">*</span></label>
                                            <select class="form-select" name="diagnosis_primary" 
                                                    id="primaryDiagnosis" required>
                                                <option value="">Search for ICD-10 code...</option>
                                            </select>
                                            <small class="text-muted">
                                                <i class="ri-information-line me-1"></i>Search by code or description
                                            </small>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Secondary Diagnosis</label>
                                            <select class="form-select" name="diagnosis_secondary" 
                                                    id="secondaryDiagnosis">
                                                <option value="">Search for ICD-10 code (optional)...</option>
                                            </select>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Differential Diagnosis</label>
                                            <textarea class="form-control" name="differential_diagnosis" rows="2" 
                                                      placeholder="List differential diagnoses..."></textarea>
                                        </div>
                                    </div>
                                </div>

                                <!-- Treatment Plan -->
                                <div class="card mb-3">
                                    <div class="card-header">
                                        <h5 class="mb-0">Treatment Plan</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label class="form-label">Treatment Plan</label>
                                            <textarea class="form-control" name="treatment_plan" rows="4" 
                                                      placeholder="Detailed treatment plan..."></textarea>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Medications to Prescribe</label>
                                            <div id="medicationsList">
                                                <div class="medication-item mb-3" data-index="0">
                                                    <div class="row">
                                                        <div class="col-md-12 mb-2">
                                                            <label class="form-label small">Search Medication</label>
                                                            <select class="form-select medication-select" 
                                                                    data-index="0"
                                                                    name="med_inventory_id[]">
                                                                <option value="">Type to search medication...</option>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-3 mb-2">
                                                            <label class="form-label small">Medicine Name</label>
                                                            <input type="text" class="form-control medication-name" 
                                                                   name="med_name[]"
                                                                   placeholder="Auto-filled"
                                                                   readonly>
                                                        </div>
                                                        <div class="col-md-2 mb-2">
                                                            <label class="form-label small">Dosage</label>
                                                            <input type="text" class="form-control medication-dosage" 
                                                                   name="med_dosage[]"
                                                                   placeholder="e.g., 500mg">
                                                        </div>
                                                        <div class="col-md-2 mb-2">
                                                            <label class="form-label small">Frequency</label>
                                                            <select class="form-select medication-frequency" name="med_frequency[]">
                                                                <option value="">Select</option>
                                                                <option value="OD">OD (Once daily)</option>
                                                                <option value="BD">BD (Twice daily)</option>
                                                                <option value="TDS">TDS (Three times)</option>
                                                                <option value="QID">QID (Four times)</option>
                                                                <option value="PRN">PRN (As needed)</option>
                                                                <option value="STAT">STAT (Immediately)</option>
                                                            </select>
                                                        </div>
                                                        <div class="col-md-2 mb-2">
                                                            <label class="form-label small">Duration</label>
                                                            <input type="text" class="form-control medication-duration" 
                                                                   name="med_duration[]"
                                                                   placeholder="e.g., 7 days">
                                                        </div>
                                                        <div class="col-md-2 mb-2">
                                                            <label class="form-label small">Quantity</label>
                                                            <input type="number" class="form-control medication-quantity" 
                                                                   name="med_quantity[]"
                                                                   placeholder="Qty"
                                                                   min="1">
                                                        </div>
                                                        <div class="col-md-1 mb-2">
                                                            <label class="form-label small">&nbsp;</label>
                                                            <button type="button" class="btn btn-outline-danger w-100" 
                                                                    onclick="removeMedication(this)" disabled>
                                                                <i class="ri-delete-bin-line"></i>
                                                            </button>
                                                        </div>
                                                        <div class="col-md-12">
                                                            <div class="medication-info" style="display:none;">
                                                                <div class="alert alert-info py-2 mb-0">
                                                                    <small>
                                                                        <strong>Stock Info:</strong> <span class="stock-info"></span> | 
                                                                        <strong>Price:</strong> KES <span class="price-info"></span> | 
                                                                        <strong>Form:</strong> <span class="form-info"></span>
                                                                    </small>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <button type="button" class="btn btn-sm btn-outline-primary" 
                                                    onclick="addMedicationRow()">
                                                <i class="ri-add-line me-1"></i>Add Another Medication
                                            </button>
                                        </div>

                                        <!-- Drug Interaction Alert -->
                                        <div class="drug-alert" id="drugAlert">
                                            <div class="d-flex align-items-start">
                                                <i class="ri-error-warning-line text-danger fs-4 me-3"></i>
                                                <div>
                                                    <h6 class="text-danger mb-2">Drug Interaction Alert!</h6>
                                                    <div id="drugAlertContent"></div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Procedures Recommended</label>
                                            <textarea class="form-control" name="procedures_recommended_text" rows="2" 
                                                      placeholder="List recommended procedures..."></textarea>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Investigations Ordered</label>
                                            <textarea class="form-control" name="investigations_ordered_text" rows="2" 
                                                      placeholder="List investigations to be ordered..."></textarea>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Referrals</label>
                                            <textarea class="form-control" name="referrals_text" rows="2" 
                                                      placeholder="Any specialist referrals needed..."></textarea>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Follow-up Instructions</label>
                                            <textarea class="form-control" name="follow_up_instructions" rows="3" 
                                                      placeholder="Instructions for patient follow-up..."></textarea>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Next Appointment Date</label>
                                            <input type="date" class="form-control" name="next_appointment" 
                                                   id="nextAppointment"
                                                   min="<?php echo date('Y-m-d', strtotime('+1 day')); ?>">
                                        </div>
                                    </div>
                                </div>

                                <!-- Consultation Fees -->
                                <div class="card mb-3">
                                    <div class="card-header">
                                        <h5 class="mb-0">Financial Information</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Consultation Fee (KES)</label>
                                                <input type="number" class="form-control" name="consultation_fee" 
                                                       id="consultationFee" 
                                                       value="<?php echo $doctor_info['consultation_fee'] ?? 0; ?>" 
                                                       step="0.01" min="0" onchange="calculateCommission()">
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Commission Rate (%)</label>
                                                <input type="number" class="form-control" 
                                                       value="<?php echo $doctor_info['commission_rate'] ?? 0; ?>" 
                                                       id="commissionRate" readonly>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <label class="form-label">Doctor Commission (KES)</label>
                                                <input type="number" class="form-control" name="doctor_commission" 
                                                       id="doctorCommission" readonly>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Doctor's Notes -->
                                <div class="card mb-3">
                                    <div class="card-header">
                                        <h5 class="mb-0">Doctor's Notes</h5>
                                    </div>
                                    <div class="card-body">
                                        <textarea class="form-control" name="doctor_notes" rows="4" 
                                                  placeholder="Private notes, observations, clinical reasoning..."></textarea>
                                    </div>
                                </div>

                                <!-- Submit Buttons -->
                                <div class="d-grid gap-2 mb-4">
                                    <button type="submit" class="btn btn-success btn-lg">
                                        <i class="ri-save-line me-2"></i>Complete Consultation
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" onclick="saveDraft()">
                                        <i class="ri-draft-line me-1"></i>Save as Draft
                                    </button>
                                </div>
                            </form>
                        </div>

                        <!-- AI Assistant Panel -->
                        <div class="col-lg-4">
                            <div class="ai-assistant-panel">
                                <div class="ai-header">
                                    <div class="d-flex align-items-center justify-content-between">
                                        <div>
                                            <h5 class="mb-0">🤖 AI Clinical Assistant</h5>
                                            <small class="opacity-75">Real-time decision support</small>
                                        </div>
                                        <span class="badge bg-light text-dark">Claude Sonnet 4</span>
                                    </div>
                                </div>
                                
                                <div class="p-3">
                                    <!-- AI Thinking Indicator -->
                                    <div class="ai-thinking" id="aiThinking">
                                        <div class="spinner-border spinner-border-sm me-2"></div>
                                        <span>AI is analyzing...</span>
                                    </div>

                                    <!-- Quick Actions -->
                                    <div class="mb-3" id="quickActions">
                                        <h6 class="mb-3">Quick Actions</h6>
                                        <button class="quick-action-btn" onclick="askAI('suggest_diagnosis')">
                                            <i class="ri-brain-line me-2 text-primary"></i>
                                            <strong>Suggest Diagnoses</strong>
                                            <br><small class="text-muted">Based on symptoms entered</small>
                                        </button>
                                        <button class="quick-action-btn" onclick="askAI('treatment_protocol')">
                                            <i class="ri-file-list-3-line me-2 text-success"></i>
                                            <strong>Treatment Protocol</strong>
                                            <br><small class="text-muted">Evidence-based guidelines</small>
                                        </button>
                                        <button class="quick-action-btn" onclick="askAI('differential')">
                                            <i class="ri-list-check me-2 text-info"></i>
                                            <strong>Differential Diagnosis</strong>
                                            <br><small class="text-muted">Alternative possibilities</small>
                                        </button>
                                        <button class="quick-action-btn" onclick="checkAllInteractions()">
                                            <i class="ri-medicine-bottle-line me-2 text-warning"></i>
                                            <strong>Check Drug Interactions</strong>
                                            <br><small class="text-muted">Safety verification</small>
                                        </button>
                                    </div>

                                    <!-- AI Suggestions -->
                                    <div id="aiSuggestions">
                                        <h6 class="mb-3">AI Suggestions</h6>
                                        <div class="text-center text-muted py-4">
                                            <i class="ri-lightbulb-line fs-2 mb-2"></i>
                                            <p>Start entering patient information to receive AI-powered suggestions</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php endif; ?>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/libs/flatpickr/flatpickr.min.js"></script>

    <script>
    let aiTimeout;
    let medicationIndex = 1;
    let medicationData = {}; // Store selected medication details
    const currentMedications = <?php echo json_encode($visit_details['current_medications'] ?? ''); ?>;
    const commissionRate = <?php echo $doctor_info['commission_rate'] ?? 0; ?>;
    const patientAllergies = <?php echo json_encode($visit_details['allergies'] ?? ''); ?>;

    // ==================== DOCUMENT READY ====================
    $(document).ready(function() {
        // Initialize flatpickr for date picker
        flatpickr("#nextAppointment", {
            minDate: "today",
            dateFormat: "Y-m-d"
        });

        // Calculate commission on page load
        calculateCommission();
        
        // Initialize doctor selection and commission
updateDoctorCommission();


        // Initialize Select2 for ICD-10 codes
        initializeICD10Select2();

        // Initialize Select2 for first medication row
        initializeMedicationSelect2(0);
    });

    // ==================== COMMISSION CALCULATION ====================
    function calculateCommission() {
        const fee = parseFloat($('#consultationFee').val()) || 0;
        const commission = (fee * commissionRate) / 100;
        $('#doctorCommission').val(commission.toFixed(2));
    }

    // ==================== ICD-10 SELECT2 INITIALIZATION ====================
    function initializeICD10Select2() {
        // Primary Diagnosis Select2
        $('#primaryDiagnosis').select2({
            theme: 'bootstrap-5',
            placeholder: 'Search for ICD-10 code...',
            allowClear: true,
            minimumInputLength: 2,
            ajax: {
                url: 'ajax/search_icd10_codes.php',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        q: params.term,
                        page: params.page || 1
                    };
                },
                processResults: function(data) {
                    return {
                        results: data.results,
                        pagination: data.pagination
                    };
                },
                cache: true
            },
            templateResult: formatICD10Result,
            templateSelection: formatICD10Selection
        });

        // Secondary Diagnosis Select2
        $('#secondaryDiagnosis').select2({
            theme: 'bootstrap-5',
            placeholder: 'Search for ICD-10 code (optional)...',
            allowClear: true,
            minimumInputLength: 2,
            ajax: {
                url: 'ajax/search_icd10_codes.php',
                dataType: 'json',
                delay: 250,
                data: function(params) {
                    return {
                        q: params.term,
                        page: params.page || 1
                    };
                },
                processResults: function(data) {
                    return {
                        results: data.results,
                        pagination: data.pagination
                    };
                },
                cache: true
            },
            templateResult: formatICD10Result,
            templateSelection: formatICD10Selection
        });
    }

    // Format ICD-10 results in dropdown
    function formatICD10Result(data) {
        if (data.loading) {
            return data.text;
        }

        let badges = '';
        if (data.commonly_used == 1) {
            badges += '<span class="badge bg-primary-subtle text-primary ms-2">Common</span>';
        }
        if (data.is_ent_related == 1) {
            badges += '<span class="badge bg-success-subtle text-success ms-2">ENT</span>';
        }

        let $result = $(`
            <div class="icd10-result">
                <div class="fw-bold">${data.code} - ${data.description}${badges}</div>
                ${data.category ? `<small class="text-muted">${data.category}</small>` : ''}
            </div>
        `);
        
        return $result;
    }

    // Format selected ICD-10 code
    function formatICD10Selection(data) {
        return data.code ? `${data.code} - ${data.description || data.text}` : data.text;
    }

    // ==================== MEDICATION SELECT2 INITIALIZATION ====================
function initializeMedicationSelect2(index) {
    $(`select.medication-select[data-index="${index}"]`).select2({
        theme: 'bootstrap-5',
        placeholder: 'Type to search medication...',
        allowClear: true,
        minimumInputLength: 2,
        dropdownParent: $('body'), // Add this line to attach dropdown to body
        ajax: {
            url: 'ajax/search_pharmacy_inventory.php',
            dataType: 'json',
            delay: 300,
            data: function(params) {
                return {
                    q: params.term,
                    page: params.page || 1
                };
            },
            processResults: function(data) {
                return {
                    results: data.results,
                    pagination: data.pagination
                };
            },
            cache: true
        },
        templateResult: formatMedicationResult,
        templateSelection: formatMedicationSelection
    }).on('select2:select', function(e) {
        handleMedicationSelection(e.params.data, index);
    }).on('select2:clear', function(e) {
        clearMedicationData(index);
    });
}

    // Format medication results in dropdown
    function formatMedicationResult(data) {
        if (data.loading) {
            return data.text;
        }

        let stockBadge = '';
        let stockClass = 'success';
        
        if (data.stock_status === 'OUT_OF_STOCK') {
            stockBadge = '<span class="badge bg-danger ms-2">Out of Stock</span>';
            stockClass = 'danger';
        } else if (data.stock_status === 'LOW_STOCK') {
            stockBadge = '<span class="badge bg-warning ms-2">Low Stock</span>';
            stockClass = 'warning';
        } else {
            stockBadge = '<span class="badge bg-success ms-2">In Stock</span>';
        }

        let $result = $(`
            <div class="medication-result">
                <div class="fw-bold">${data.item_name}${stockBadge}</div>
                <small class="text-muted">
                    ${data.generic_name ? data.generic_name + ' | ' : ''}
                    ${data.strength ? data.strength + ' | ' : ''}
                    ${data.dosage_form ? data.dosage_form : ''}
                </small>
                <br>
                <small class="text-${stockClass}">
                    Available: ${data.current_stock} ${data.unit_of_measure || 'units'}
                </small>
            </div>
        `);
        
        return $result;
    }

    // Format selected medication
    function formatMedicationSelection(data) {
        return data.item_name || data.text;
    }

    // Handle medication selection
    function handleMedicationSelection(data, index) {
        const $item = $(`.medication-item[data-index="${index}"]`);
        
        // Store medication data
        medicationData[index] = data;
        
        // Fill in the fields
        $item.find('.medication-name').val(data.item_name);
        
        // Auto-fill dosage if strength is available
        if (data.strength) {
            $item.find('.medication-dosage').val(data.strength);
        }
        
        // Show medication info
        $item.find('.stock-info').text(
            data.current_stock + ' ' + (data.unit_of_measure || 'units')
        );
        $item.find('.price-info').text(
            parseFloat(data.selling_price || 0).toFixed(2)
        );
        $item.find('.form-info').text(data.dosage_form || 'N/A');
        $item.find('.medication-info').slideDown();
        
        // Check for drug interactions when medication is selected
        checkDrugInteraction();
        
        // Warn if out of stock
        if (data.stock_status === 'OUT_OF_STOCK') {
            Swal.fire({
                icon: 'warning',
                title: 'Out of Stock',
                text: `${data.item_name} is currently out of stock. Please select an alternative or inform the patient.`,
                confirmButtonText: 'Understood'
            });
        } else if (data.stock_status === 'LOW_STOCK') {
            Swal.fire({
                icon: 'info',
                title: 'Low Stock Alert',
                text: `${data.item_name} has low stock (${data.current_stock} remaining). Consider informing pharmacy.`,
                confirmButtonText: 'OK',
                timer: 3000
            });
        }
    }

    // Clear medication data
    function clearMedicationData(index) {
        const $item = $(`.medication-item[data-index="${index}"]`);
        delete medicationData[index];
        
        $item.find('.medication-name').val('');
        $item.find('.medication-dosage').val('');
        $item.find('.medication-info').slideUp();
    }

    // Add new medication row
    function addMedicationRow() {
        const newIndex = medicationIndex++;
        
        const html = `
            <div class="medication-item mb-3" data-index="${newIndex}">
                <div class="row">
                    <div class="col-md-12 mb-2">
                        <label class="form-label small">Search Medication</label>
                        <select class="form-select medication-select" 
                                data-index="${newIndex}"
                                name="med_inventory_id[]">
                            <option value="">Type to search medication...</option>
                        </select>
                    </div>
                    <div class="col-md-3 mb-2">
                        <label class="form-label small">Medicine Name</label>
                        <input type="text" class="form-control medication-name" 
                               name="med_name[]"
                               placeholder="Auto-filled"
                               readonly>
                    </div>
                    <div class="col-md-2 mb-2">
                        <label class="form-label small">Dosage</label>
                        <input type="text" class="form-control medication-dosage" 
                               name="med_dosage[]"
                               placeholder="e.g., 500mg">
                    </div>
                    <div class="col-md-2 mb-2">
                        <label class="form-label small">Frequency</label>
                        <select class="form-select medication-frequency" name="med_frequency[]">
                            <option value="">Select</option>
                            <option value="OD">OD (Once daily)</option>
                            <option value="BD">BD (Twice daily)</option>
                            <option value="TDS">TDS (Three times)</option>
                            <option value="QID">QID (Four times)</option>
                            <option value="PRN">PRN (As needed)</option>
                            <option value="STAT">STAT (Immediately)</option>
                        </select>
                    </div>
                    <div class="col-md-2 mb-2">
                        <label class="form-label small">Duration</label>
                        <input type="text" class="form-control medication-duration" 
                               name="med_duration[]"
                               placeholder="e.g., 7 days">
                    </div>
                    <div class="col-md-2 mb-2">
                        <label class="form-label small">Quantity</label>
                        <input type="number" class="form-control medication-quantity" 
                               name="med_quantity[]"
                               placeholder="Qty"
                               min="1">
                    </div>
                    <div class="col-md-1 mb-2">
                        <label class="form-label small">&nbsp;</label>
                        <button type="button" class="btn btn-outline-danger w-100" 
                                onclick="removeMedication(this)">
                            <i class="ri-delete-bin-line"></i>
                        </button>
                    </div>
                    <div class="col-md-12">
                        <div class="medication-info" style="display:none;">
                            <div class="alert alert-info py-2 mb-0">
                                <small>
                                    <strong>Stock Info:</strong> <span class="stock-info"></span> | 
                                    <strong>Price:</strong> KES <span class="price-info"></span> | 
                                    <strong>Form:</strong> <span class="form-info"></span>
                                </small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        $('#medicationsList').append(html);
        initializeMedicationSelect2(newIndex);
    }

    // Remove medication row
    function removeMedication(btn) {
        const $item = $(btn).closest('.medication-item');
        const index = $item.data('index');
        
        // Remove from medicationData
        delete medicationData[index];
        
        // Destroy Select2 before removing
        $item.find('.medication-select').select2('destroy');
        
        // Remove the row
        $item.fadeOut(300, function() {
            $(this).remove();
            // Recheck drug interactions after removal
            checkDrugInteraction();
        });
    }

    // ==================== PATIENT SEARCH ====================
     // Patient Search Function
function searchPatients() {
            const query = $('#patientSearch').val().trim();
            if (!query) {
                Swal.fire('Info', 'Please enter a search term', 'info');
                return;
            }
            $.ajax({
                url: 'ajax/search_patients.php',
                type: 'POST',
                data: { query: query },
                success: function(response) {
                    if (response.success && response.results) {
                        let html = '';
                        response.results.forEach(patient => {
                            html += `
                                <div class="patient-result" onclick="selectPatient(${patient.id})">
                                    <div class="d-flex justify-content-between">
                                        <div>
                                            <h6>${patient.full_name}</h6>
                                            <small class="text-muted">ID: ${patient.patient_number} | Age: ${patient.age} | ${patient.gender}</small>
                                            <br><small>${patient.phone_primary || patient.email}</small>
                                        </div>
                                        <button class="btn btn-sm btn-primary">Select</button>
                                    </div>
                                </div>
                            `;
                        });
                        $('#searchResultsList').html(html);
                        $('#searchResults').show();
                    } else {
                        $('#searchResultsList').html('<p class="text-muted">No patients found.</p>');
                        $('#searchResults').show();
                    }
                },
                error: function() {
                    Swal.fire('Error', 'Failed to search patients', 'error');
                }
            });
        }

        // Display search results
        function displaySearchResults(patients) {
            let html = '';
            patients.forEach(patient => {
                const age = calculateAge(patient.date_of_birth);
                html += `
                    <div class="card mb-2">
                        <div class="card-body">
                            <div class="row align-items-center">
                                <div class="col-md-4">
                                    <h6 class="mb-0">${patient.full_name}</h6>
                                    <small class="text-muted">${patient.patient_number}</small>
                                </div>
                                <div class="col-md-3">
                                    <small><strong>Age:</strong> ${age} years</small><br>
                                    <small><strong>Gender:</strong> ${patient.gender}</small>
                                </div>
                                <div class="col-md-3">
                                    <small>${patient.phone_primary || 'No phone'}</small>
                                </div>
                                <div class="col-md-2 text-end">
                                    <button class="btn btn-sm btn-primary" 
                                            onclick="selectPatient(${patient.patient_id})">
                                        <i class="ri-stethoscope-line me-1"></i>Start
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });

            $('#searchResultsList').html(html);
            $('#searchResults').show();
        }

        // Calculate age from date of birth
        function calculateAge(dob) {
            const birthDate = new Date(dob);
            const today = new Date();
            let age = today.getFullYear() - birthDate.getFullYear();
            const m = today.getMonth() - birthDate.getMonth();
            if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
                age--;
            }
            return age;
        }
        
        // Update consultation fee and commission rate when doctor changes
function updateDoctorCommission() {
    const selectedOption = $('#doctorSelect option:selected');
    const fee = selectedOption.data('fee');
    const commissionRate = selectedOption.data('commission');

    $('#consultationFee').val(fee);
    $('#commissionRate').val(commissionRate);
    calculateCommission();
}


        // Select patient and start consultation
        function selectPatient(patientId) {
            window.location.href = `new_consultation.php?patient_id=${patientId}`;
        }

        // Enter key for search
        $('#patientSearch').on('keypress', function(e) {
            if (e.which === 13) {
                searchPatients();
            }
        });

    // ==================== AI ASSISTANT FUNCTIONS ====================
    // ==================== AI ASSISTANT FUNCTIONS ====================
// Trigger AI analysis with debouncing
function triggerAIAnalysis() {
    clearTimeout(aiTimeout);
    aiTimeout = setTimeout(() => {
        performAIAnalysis();
    }, 1500);
}

// Perform AI Analysis
async function performAIAnalysis() {
    const chiefComplaint = document.getElementById('chiefComplaint').value;
    const historyPresent = document.getElementById('historyPresent').value;
    const patientAge = $('input[name="patient_age"]').val();
    const patientGender = $('input[name="patient_gender"]').val();

    if (!chiefComplaint && !historyPresent) {
        return;
    }

    $('#aiThinking').addClass('active');
    $('#aiSuggestions').html(`
        <h6 class="mb-3">AI Suggestions</h6>
        <div class="text-center text-muted py-3">
            <div class="spinner-border spinner-border-sm me-2"></div>
            <span>Analyzing symptoms...</span>
        </div>
    `);

    try {
        const response = await fetch('ajax/ai_assistant.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'analyze_symptoms',
                data: {
                    chief_complaint: chiefComplaint,
                    history_present: historyPresent,
                    age: patientAge,
                    gender: patientGender
                }
            })
        });

        const result = await response.json();

        if (result.success && result.analysis) {
            displayAISuggestions(result.analysis);
        } else {
            $('#aiSuggestions').html(`
                <h6 class="mb-3">AI Suggestions</h6>
                <div class="alert alert-warning">
                    <i class="ri-information-line me-2"></i>
                    ${result.message || 'Unable to analyze symptoms. Please check AI configuration.'}
                </div>
            `);
        }
    } catch (error) {
        console.error("AI Analysis Error:", error);
        $('#aiSuggestions').html(`
            <h6 class="mb-3">AI Suggestions</h6>
            <div class="alert alert-danger">
                <i class="ri-error-warning-line me-2"></i>
                AI analysis failed. Please try again or contact support.
            </div>
        `);
    } finally {
        $('#aiThinking').removeClass('active');
    }
}

// Display AI Suggestions with improved formatting
function displayAISuggestions(analysis) {
    let html = '';

    // Check if analysis is valid
    if (!analysis || typeof analysis !== 'object') {
        html = `
            <div class="alert alert-warning">
                <i class="ri-information-line me-2"></i>
                AI returned unexpected data. Please try again.
            </div>
        `;
        $('#aiSuggestions').html('<h6 class="mb-3">AI Suggestions</h6>' + html);
        return;
    }

    // Possible Diagnoses
    if (analysis.possible_diagnoses && Array.isArray(analysis.possible_diagnoses) && analysis.possible_diagnoses.length > 0) {
        analysis.possible_diagnoses.forEach(diag => {
            const severity = diag.confidence >= 80 ? '' : 'warning';
            const confidenceColor = diag.confidence >= 80 ? 'success' : 
                                   diag.confidence >= 60 ? 'warning' : 'danger';
            
            html += `
                <div class="ai-suggestion ${severity}" onclick="acceptDiagnosis('${escapeHtml(diag.diagnosis)}')">
                    <div class="d-flex justify-content-between align-items-start mb-2">
                        <div class="flex-grow-1">
                            <strong class="d-block mb-1">${escapeHtml(diag.diagnosis)}</strong>
                            <p class="mb-0 small text-muted">${escapeHtml(diag.reasoning)}</p>
                        </div>
                        <span class="badge bg-${confidenceColor} ms-2">${diag.confidence}%</span>
                    </div>
                    <div class="confidence-meter">
                        <div class="confidence-fill" style="width: ${diag.confidence}%; 
                             background: ${diag.confidence >= 80 ? 'linear-gradient(90deg, #10b981, #059669)' : 
                                         diag.confidence >= 60 ? 'linear-gradient(90deg, #f59e0b, #d97706)' : 
                                         'linear-gradient(90deg, #ef4444, #dc2626)'}"></div>
                    </div>
                </div>
            `;
        });
    }

    // Red Flags
    if (analysis.red_flags && Array.isArray(analysis.red_flags) && analysis.red_flags.length > 0) {
        html += `
            <div class="ai-suggestion critical">
                <div class="d-flex align-items-start">
                    <i class="ri-alert-line text-danger fs-5 me-2"></i>
                    <div>
                        <h6 class="text-danger mb-2">Red Flags - Immediate Attention Required</h6>
                        <ul class="mb-0 ps-3">
        `;
        analysis.red_flags.forEach(flag => {
            html += `<li class="mb-1">${escapeHtml(flag)}</li>`;
        });
        html += `
                        </ul>
                    </div>
                </div>
            </div>
        `;
    }

    // Recommended Tests
    if (analysis.recommended_tests && Array.isArray(analysis.recommended_tests) && analysis.recommended_tests.length > 0) {
        html += `
            <div class="ai-suggestion">
                <h6 class="mb-2">
                    <i class="ri-test-tube-line me-2 text-info"></i>
                    Recommended Tests
                </h6>
                <div class="d-flex flex-wrap gap-2">
        `;
        analysis.recommended_tests.forEach(test => {
            html += `<span class="badge bg-info-subtle text-info">${escapeHtml(test)}</span>`;
        });
        html += `
                </div>
            </div>
        `;
    }

    // Treatment Suggestions
    if (analysis.treatment_suggestions && Array.isArray(analysis.treatment_suggestions) && analysis.treatment_suggestions.length > 0) {
        html += `
            <div class="ai-suggestion">
                <h6 class="mb-2">
                    <i class="ri-capsule-line me-2 text-success"></i>
                    Treatment Suggestions
                </h6>
                <ul class="mb-0 ps-3">
        `;
        analysis.treatment_suggestions.forEach(treatment => {
            html += `<li class="mb-1">${escapeHtml(treatment)}</li>`;
        });
        html += `
                </ul>
            </div>
        `;
    }

    // Follow-up Recommendation
    if (analysis.follow_up_needed === true) {
        html += `
            <div class="ai-suggestion">
                <div class="d-flex align-items-center">
                    <i class="ri-calendar-check-line me-2 text-primary fs-5"></i>
                    <strong>Follow-up appointment recommended</strong>
                </div>
            </div>
        `;
    }

    // If no suggestions were generated
    if (html === '') {
        html = `
            <div class="text-center text-muted py-4">
                <i class="ri-lightbulb-line fs-2 mb-2"></i>
                <p>AI needs more information to provide suggestions.</p>
                <small>Continue entering patient details...</small>
            </div>
        `;
    }

    $('#aiSuggestions').html('<h6 class="mb-3">AI Suggestions</h6>' + html);
}

// Accept AI diagnosis suggestion
function acceptDiagnosis(diagnosis) {
    Swal.fire({
        title: 'Use AI Suggestion?',
        html: `Add "<strong>${escapeHtml(diagnosis)}</strong>" as primary diagnosis?`,
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: '<i class="ri-check-line me-1"></i>Yes, use it',
        cancelButtonText: '<i class="ri-close-line me-1"></i>No, thanks',
        confirmButtonColor: '#26a69a',
        cancelButtonColor: '#6c757d'
    }).then((result) => {
        if (result.isConfirmed) {
            // Search for the diagnosis in ICD-10 codes
            $.ajax({
                url: 'ajax/search_icd10_codes.php',
                type: 'GET',
                data: { q: diagnosis, page: 1 },
                dataType: 'json',
                success: function(response) {
                    if (response.results && response.results.length > 0) {
                        // Use the first result
                        const firstResult = response.results[0];
                        const newOption = new Option(
                            `${firstResult.code} - ${firstResult.description}`,
                            firstResult.code,
                            true,
                            true
                        );
                        $('#primaryDiagnosis').append(newOption).trigger('change');
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Diagnosis Added!',
                            text: `${firstResult.code} - ${firstResult.description}`,
                            timer: 3000,
                            showConfirmButton: false
                        });
                    } else {
                        // If no exact match, show options
                        Swal.fire({
                            icon: 'info',
                            title: 'No Exact Match',
                            html: `Could not find exact ICD-10 code for "<strong>${escapeHtml(diagnosis)}</strong>".<br><br>Please search manually in the diagnosis field.`,
                            confirmButtonText: 'OK'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        icon: 'error',
                        title: 'Search Failed',
                        text: 'Unable to search ICD-10 codes. Please try manually.',
                        confirmButtonText: 'OK'
                    });
                }
            });
        }
    });
}

// Ask AI specific questions with improved prompts
async function askAI(query_type) {
    const chiefComplaint = document.getElementById('chiefComplaint').value;
    const historyPresent = document.getElementById('historyPresent').value;
    const diagnosis = $('#primaryDiagnosis option:selected').text();

    if (!chiefComplaint && !historyPresent && !diagnosis) {
        Swal.fire({
            icon: 'info',
            title: 'More Information Needed',
            text: 'Please enter patient symptoms or diagnosis first',
            confirmButtonText: 'OK'
        });
        return;
    }

    $('#aiThinking').addClass('active');

    // Show loading in SweetAlert
    Swal.fire({
        title: 'AI Assistant Thinking...',
        html: 'Please wait while I analyze the information',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    try {
        const response = await fetch('ajax/ai_assistant.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'ask_question',
                data: {
                    query_type: query_type,
                    chief_complaint: chiefComplaint,
                    history_present: historyPresent,
                    diagnosis: diagnosis
                }
            })
        });

        const result = await response.json();

        if (result.success && result.response) {
            const aiResponse = result.response;
            
            // Format the response with proper HTML
            const formattedResponse = aiResponse
                .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>') // Bold text
                .replace(/\n\n/g, '</p><p>') // Paragraphs
                .replace(/\n- /g, '<br>• ') // Bullet points
                .replace(/\n\d+\. /g, '<br>$&'); // Numbered lists

            Swal.fire({
                title: getAITitle(query_type),
                html: `
                    <div class="text-start" style="max-height: 500px; overflow-y: auto;">
                        <p>${formattedResponse}</p>
                    </div>
                `,
                width: '750px',
                confirmButtonText: '<i class="ri-check-line me-1"></i>Close',
                confirmButtonColor: '#26a69a',
                customClass: {
                    popup: 'swal-wide'
                },
                showCloseButton: true
            });
        } else {
            Swal.fire({
                icon: 'error',
                title: 'AI Assistant Error',
                text: result.message || 'Failed to get AI response. Please check configuration.',
                confirmButtonText: 'OK'
            });
        }
    } catch (error) {
        console.error("AI Query Error:", error);
        Swal.fire({
            icon: 'error',
            title: 'Connection Error',
            text: 'Failed to connect to AI Assistant. Please try again.',
            confirmButtonText: 'OK'
        });
    } finally {
        $('#aiThinking').removeClass('active');
    }
}

// Get appropriate title for AI query type
function getAITitle(queryType) {
    const titles = {
        'suggest_diagnosis': '🩺 AI Diagnosis Suggestions',
        'treatment_protocol': '💊 Treatment Protocol',
        'differential': '📋 Differential Diagnosis'
    };
    return titles[queryType] || 'AI Assistant Response';
}

// ==================== DRUG INTERACTION CHECKING ====================
// Check drug interactions using medicationData
function checkDrugInteraction() {
    const allMedications = Object.values(medicationData)
        .map(med => med.item_name)
        .filter(name => name);

    if (allMedications.length < 1) {
        $('#drugAlert').removeClass('active');
        return;
    }

    checkInteractionsAI(allMedications);
}

async function checkInteractionsAI(medications) {
    try {
        const response = await fetch('ajax/ai_assistant.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                action: 'check_interactions',
                data: {
                    medications: medications,
                    current_medications: currentMedications,
                    allergies: patientAllergies
                }
            })
        });

        const result = await response.json();

        if (result.success && result.interaction_data) {
            const interactionData = result.interaction_data;

            // Check if interaction_data is valid
            if (!interactionData || typeof interactionData !== 'object') {
                $('#drugAlert').removeClass('active');
                return;
            }

            if (interactionData.has_interaction === true && 
                Array.isArray(interactionData.interactions) && 
                interactionData.interactions.length > 0) {
                
                let alertHtml = '<ul class="mb-0">';
                
                interactionData.interactions.forEach(interaction => {
                    const severityClass = interaction.severity === 'MAJOR' ? 'danger' : 
                                        interaction.severity === 'MODERATE' ? 'warning' : 'info';
                    const severityIcon = interaction.severity === 'MAJOR' ? 'ri-error-warning-line' : 
                                       'ri-alert-line';
                    
                    const drugs = Array.isArray(interaction.drugs) ? 
                                interaction.drugs.join(' + ') : 
                                'Unknown drugs';
                    
                    alertHtml += `
                        <li class="mb-3">
                            <div class="d-flex align-items-start">
                                <i class="${severityIcon} text-${severityClass} me-2 mt-1"></i>
                                <div>
                                    <strong class="text-${severityClass}">${escapeHtml(drugs)}</strong>
                                    <br>
                                    <span class="badge bg-${severityClass} mt-1">${interaction.severity || 'UNKNOWN'}</span>
                                    <p class="mt-2 mb-1"><strong>Effect:</strong> ${escapeHtml(interaction.effect || 'Not specified')}</p>
                                    <p class="mb-0 text-primary">
                                        <i class="ri-lightbulb-line me-1"></i>
                                        <strong>Recommendation:</strong> ${escapeHtml(interaction.recommendation || 'Consult pharmacist')}
                                    </p>
                                </div>
                            </div>
                        </li>
                    `;
                });
                
                alertHtml += '</ul>';

                $('#drugAlertContent').html(alertHtml);
                $('#drugAlert').addClass('active');
                
                // Scroll to alert
                $('html, body').animate({
                    scrollTop: $('#drugAlert').offset().top - 100
                }, 500);
            } else {
                $('#drugAlert').removeClass('active');
            }
        } else {
            console.log('No interactions found or AI error:', result.message);
            $('#drugAlert').removeClass('active');
        }
    } catch (error) {
        console.error("Drug interaction check error:", error);
        $('#drugAlert').removeClass('active');
    }
}

// Check all drug interactions - called by button
function checkAllInteractions() {
    const medications = Object.values(medicationData)
        .map(med => med.item_name)
        .filter(name => name);

    if (medications.length < 1) {
        Swal.fire({
            icon: 'info',
            title: 'No Medications',
            text: 'Please add at least 1 medication to check interactions',
            confirmButtonText: 'OK'
        });
        return;
    }

    Swal.fire({
        title: 'Checking Interactions...',
        html: 'AI is analyzing medication combinations',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });

    checkInteractionsAI(medications).then(() => {
        Swal.close();
        
        if ($('#drugAlert').hasClass('active')) {
            Swal.fire({
                icon: 'warning',
                title: 'Interactions Detected!',
                text: 'Please review the drug interaction alert below',
                confirmButtonText: 'View Details'
            });
        } else {
            Swal.fire({
                icon: 'success',
                title: 'No Interactions',
                text: 'No significant drug interactions detected',
                timer: 3000,
                showConfirmButton: false
            });
        }
    });
}

    // ==================== EXAMINATION TEMPLATES ====================
    // Load examination template
    function loadExamTemplate() {
        Swal.fire({
            title: 'Select Exam Template',
            html: `
                <select class="form-select" id="examTemplate">
                    <option value="">Choose template...</option>
                    <option value="normal">Normal ENT Examination</option>
                    <option value="otitis">Otitis Media</option>
                    <option value="rhinitis">Rhinitis/Sinusitis</option>
                    <option value="pharyngitis">Pharyngitis/Tonsillitis</option>
                    <option value="vertigo">Vertigo/Balance Disorder</option>
                </select>
            `,
            showCancelButton: true,
            confirmButtonText: 'Load Template',
            preConfirm: () => {
                return document.getElementById('examTemplate').value;
            }
        }).then((result) => {
            if (result.isConfirmed && result.value) {
                applyExamTemplate(result.value);
            }
        });
    }

    // Apply examination template
    function applyExamTemplate(templateType) {
        const templates = {
            normal: {
                ear_external: "External ears: Normal shape and position. No discharge, swelling or tenderness.",
                ear_otoscopy: "Tympanic membranes: Intact, pearly gray bilaterally. Landmarks visible. Normal light reflex.",
                ear_hearing: "Hearing: Grossly normal. Weber test midline. Rinne test positive bilaterally.",
                nose_external: "External nose: Normal shape. No deformity or tenderness.",
                nose_rhinoscopy: "Nasal mucosa: Pink and moist. Septum: Midline. Turbinates: Normal size.",
                nose_endoscopy: "No polyps, masses or foreign bodies visualized.",
                throat_oral_cavity: "Oral cavity: Good dental hygiene. Tongue: Normal. Palate: Normal.",
                throat_pharynx: "Pharynx: No erythema or exudate. Tonsils: Normal size, no inflammation.",
                throat_larynx: "Larynx: Clear view. Vocal cords: Mobile, no lesions.",
                neck_lymph_nodes: "No palpable cervical lymphadenopathy.",
                neck_thyroid: "Thyroid: Normal size, no nodules or masses.",
                neck_masses: "No abnormal masses palpated.",
                cranial_nerves_exam: "CN II-XII intact and functioning normally.",
                general_examination: "Patient alert and oriented. No acute distress."
            },
            otitis: {
                ear_external: "External ear: Normal. Mild tenderness on tragal pressure.",
                ear_otoscopy: "Tympanic membrane: Erythematous, bulging. Landmarks obscured. Possible fluid level.",
                ear_hearing: "Hearing: Reduced on affected side. Weber lateralizes to affected ear.",
                nose_external: "Within normal limits",
                nose_rhinoscopy: "Within normal limits",
                nose_endoscopy: "No significant findings",
                throat_oral_cavity: "Within normal limits",
                throat_pharynx: "Within normal limits",
                throat_larynx: "Not examined",
                neck_lymph_nodes: "Tender periauricular and postauricular lymph nodes present.",
                neck_thyroid: "Normal",
                neck_masses: "None",
                cranial_nerves_exam: "No focal deficits",
                general_examination: "Febrile, otherwise stable"
            },
            rhinitis: {
                ear_external: "Within normal limits",
                ear_otoscopy: "Tympanic membranes: Intact, no effusion",
                ear_hearing: "Grossly normal",
                nose_external: "External nose: Tender over maxillary and frontal sinuses.",
                nose_rhinoscopy: "Nasal mucosa: Edematous, erythematous, congested. Turbinates: Hypertrophied. Discharge: Mucopurulent.",
                nose_endoscopy: "Purulent discharge from middle meatus. Polyps may be present.",
                throat_oral_cavity: "Normal",
                throat_pharynx: "Posterior pharyngeal wall: Postnasal drip evident.",
                throat_larynx: "Not examined",
                neck_lymph_nodes: "Tender anterior cervical lymph nodes may be present.",
                neck_thyroid: "Normal",
                neck_masses: "None",
                cranial_nerves_exam: "No focal deficits",
                general_examination: "Mild respiratory distress due to nasal congestion"
            },
            pharyngitis: {
                ear_external: "Within normal limits",
                ear_otoscopy: "Tympanic membranes: Normal",
                ear_hearing: "Normal",
                nose_external: "Normal",
                nose_rhinoscopy: "Nasal mucosa: Pink, no discharge",
                nose_endoscopy: "Normal findings",
                throat_oral_cavity: "Oral cavity: Normal dentition",
                throat_pharynx: "Pharynx: Erythematous with exudate. Tonsils: Enlarged, inflamed, possible exudate.",
                throat_larynx: "Larynx: Normal visualization",
                neck_lymph_nodes: "Tender bilateral cervical lymphadenopathy.",
                neck_thyroid: "Normal",
                neck_masses: "None",
                cranial_nerves_exam: "Normal",
                general_examination: "Febrile, appears uncomfortable"
            },
            vertigo: {
                ear_external: "External ears: Normal",
                ear_otoscopy: "Tympanic membranes: Intact, normal",
                ear_hearing: "Hearing assessment: May show unilateral sensorineural loss",
                nose_external: "Normal",
                nose_rhinoscopy: "Normal",
                nose_endoscopy: "Normal",
                throat_oral_cavity: "Normal",
                throat_pharynx: "Normal",
                throat_larynx: "Normal",
                neck_lymph_nodes: "No lymphadenopathy",
                neck_thyroid: "Normal",
                neck_masses: "None",
                cranial_nerves_exam: "CN VIII: Possible vestibular dysfunction. Nystagmus may be present. Other CNs intact.",
                general_examination: "Patient appears anxious. Positive Romberg test. Dix-Hallpike maneuver positive."
            }
        };

        if (templates[templateType]) {
            const template = templates[templateType];
            Object.keys(template).forEach(key => {
                $(`textarea[name="${key}"]`).val(template[key]);
                $(`input[name="${key}"]`).val(template[key]);
            });
            
            Swal.fire('Template Loaded', 'Examination template has been applied', 'success');
        }
    }

    // ==================== FORM SUBMISSION ====================
    // Save consultation
    $('#consultationForm').on('submit', function(e) {
        e.preventDefault();

        // Collect medications with inventory IDs
        const medications = [];
        $('.medication-item').each(function() {
            const index = $(this).data('index');
            const inventoryId = $(this).find('.medication-select').val();
            const name = $(this).find('.medication-name').val();
            
            if (name && medicationData[index]) {
                medications.push({
                    inventory_id: inventoryId,
                    name: name,
                    dosage: $(this).find('.medication-dosage').val(),
                    frequency: $(this).find('.medication-frequency').val(),
                    duration: $(this).find('.medication-duration').val(),
                    quantity: $(this).find('.medication-quantity').val(),
                    price: medicationData[index].selling_price,
                    unit_of_measure: medicationData[index].unit_of_measure
                });
            }
        });

        // Validate stock availability
        let outOfStock = [];
        medications.forEach(med => {
            const medData = Object.values(medicationData).find(m => m.inventory_id == med.inventory_id);
            if (medData && medData.stock_status === 'OUT_OF_STOCK') {
                outOfStock.push(med.name);
            }
        });

        if (outOfStock.length > 0) {
            Swal.fire({
                icon: 'error',
                title: 'Stock Unavailable',
                html: `The following medications are out of stock:<br><br><strong>${outOfStock.join(', ')}</strong><br><br>Please remove them or select alternatives.`,
                confirmButtonText: 'OK'
            });
            return;
        }

        // Build JSON for ENT examination fields
        const earExamination = {
            external: $('textarea[name="ear_external"]').val(),
            otoscopy: $('textarea[name="ear_otoscopy"]').val(),
            hearing: $('textarea[name="ear_hearing"]').val()
        };

        const noseExamination = {
            external: $('textarea[name="nose_external"]').val(),
            rhinoscopy: $('textarea[name="nose_rhinoscopy"]').val(),
            endoscopy: $('textarea[name="nose_endoscopy"]').val()
        };

        const throatExamination = {
            oral_cavity: $('textarea[name="throat_oral_cavity"]').val(),
            pharynx: $('textarea[name="throat_pharynx"]').val(),
            larynx: $('textarea[name="throat_larynx"]').val()
        };

        const neckExamination = {
            lymph_nodes: $('textarea[name="neck_lymph_nodes"]').val(),
            thyroid: $('textarea[name="neck_thyroid"]').val(),
            masses: $('textarea[name="neck_masses"]').val()
        };

        const cranialNerves = {
            examination: $('textarea[name="cranial_nerves_exam"]').val()
        };

        // Convert procedures and investigations text to JSON arrays
        const proceduresText = $('textarea[name="procedures_recommended_text"]').val();
        const proceduresArray = proceduresText.split('\n').filter(p => p.trim()).map(p => ({
            procedure: p.trim(),
            reason: ''
        }));

        const investigationsText = $('textarea[name="investigations_ordered_text"]').val();
        const investigationsArray = investigationsText.split('\n').filter(i => i.trim());

        const referralsText = $('textarea[name="referrals_text"]').val();
        const referralsArray = referralsText.split('\n').filter(r => r.trim()).map(r => ({
            specialist: r.trim(),
            reason: ''
        }));

        const formData = new FormData(this);
        formData.append('medications_prescribed', JSON.stringify(medications));
        formData.append('ear_examination', JSON.stringify(earExamination));
        formData.append('nose_examination', JSON.stringify(noseExamination));
        formData.append('throat_examination', JSON.stringify(throatExamination));
        formData.append('neck_examination', JSON.stringify(neckExamination));
        formData.append('cranial_nerves', JSON.stringify(cranialNerves));
        formData.append('procedures_recommended', JSON.stringify(proceduresArray));
        formData.append('investigations_ordered', JSON.stringify(investigationsArray));
        formData.append('referrals', JSON.stringify(referralsArray));
        formData.append('status', 'COMPLETED');

        Swal.fire({
            title: 'Complete Consultation?',
            text: 'This will save the consultation and update patient records',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, complete it',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Show loading
                Swal.fire({
                    title: 'Saving Consultation...',
                    html: 'Please wait while we save the consultation',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                $.ajax({
                    url: 'ajax/save_consultation.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Consultation Saved!',
                                text: response.message,
                                showCancelButton: true,
                                confirmButtonText: 'View Consultation',
                                cancelButtonText: 'New Patient'
                            }).then((result) => {
                                if (result.isConfirmed) {
                                    window.location.href = 'view_consultation.php?id=' + response.consultation_id;
                                } else {
                                    window.location.href = 'list_patients.php';
                                }
                            });
                        } else {
                            Swal.fire('Error', response.message, 'error');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Save error:', error);
                        Swal.fire('Error', 'Failed to save consultation. Please try again.', 'error');
                    }
                });
            }
        });
    });

    // Save as draft
    function saveDraft() {
        // Collect medications with inventory IDs
        const medications = [];
        $('.medication-item').each(function() {
            const index = $(this).data('index');
            const inventoryId = $(this).find('.medication-select').val();
            const name = $(this).find('.medication-name').val();
            
            if (name && medicationData[index]) {
                medications.push({
                    inventory_id: inventoryId,
                    name: name,
                    dosage: $(this).find('.medication-dosage').val(),
                    frequency: $(this).find('.medication-frequency').val(),
                    duration: $(this).find('.medication-duration').val(),
                    quantity: $(this).find('.medication-quantity').val(),
                    price: medicationData[index].selling_price,
                    unit_of_measure: medicationData[index].unit_of_measure
                });
            }
        });

        const earExamination = {
            external: $('textarea[name="ear_external"]').val(),
            otoscopy: $('textarea[name="ear_otoscopy"]').val(),
            hearing: $('textarea[name="ear_hearing"]').val()
        };

        const noseExamination = {
            external: $('textarea[name="nose_external"]').val(),
            rhinoscopy: $('textarea[name="nose_rhinoscopy"]').val(),
            endoscopy: $('textarea[name="nose_endoscopy"]').val()
        };

        const throatExamination = {
            oral_cavity: $('textarea[name="throat_oral_cavity"]').val(),
            pharynx: $('textarea[name="throat_pharynx"]').val(),
            larynx: $('textarea[name="throat_larynx"]').val()
        };

        const neckExamination = {
            lymph_nodes: $('textarea[name="neck_lymph_nodes"]').val(),
            thyroid: $('textarea[name="neck_thyroid"]').val(),
            masses: $('textarea[name="neck_masses"]').val()
        };

        const cranialNerves = {
            examination: $('textarea[name="cranial_nerves_exam"]').val()
        };

        const formData = new FormData(document.getElementById('consultationForm'));
        formData.append('medications_prescribed', JSON.stringify(medications));
        formData.append('ear_examination', JSON.stringify(earExamination));
        formData.append('nose_examination', JSON.stringify(noseExamination));
        formData.append('throat_examination', JSON.stringify(throatExamination));
        formData.append('neck_examination', JSON.stringify(neckExamination));
        formData.append('cranial_nerves', JSON.stringify(cranialNerves));
        formData.append('status', 'IN_PROGRESS');

        $.ajax({
            url: 'ajax/save_consultation.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Draft Saved',
                        text: 'You can continue this consultation later',
                        timer: 2000,
                        showConfirmButton: false
                    });
                } else {
                    Swal.fire('Error', response.message, 'error');
                }
            },
            error: function() {
                Swal.fire('Error', 'Failed to save draft', 'error');
            }
        });
    }

    // ==================== UTILITY FUNCTIONS ====================
    // Escape HTML to prevent XSS
    function escapeHtml(text) {
        const map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, m => map[m]);
    }

    // Auto-save draft every 5 minutes
    setInterval(function() {
        const chiefComplaint = document.getElementById('chiefComplaint')?.value;
        if (chiefComplaint) {
            saveDraft();
            console.log('Auto-saved draft at ' + new Date().toLocaleTimeString());
        }
    }, 300000); // 5 minutes
</script>
</body>
</html>