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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get all active doctors
$doctors_sql = "SELECT 
    d.doctor_id,
    u.full_name,
    d.specialization,
    d.sub_specialization,
    d.consultation_fee,
    d.appointment_duration,
    d.max_daily_appointments,
    d.is_consultant
FROM doctors d
JOIN users u ON d.user_id = u.user_id
WHERE d.is_active = 1
ORDER BY d.is_consultant DESC, u.full_name";
$doctors = $conn->query($doctors_sql);

// Get appointment types
$appointment_types = ['CONSULTATION', 'FOLLOW_UP', 'PROCEDURE', 'EMERGENCY', 'TELEMEDICINE'];
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'AI Smart Scheduler')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    
    <style>
        .ai-scheduler-header {
            background: linear-gradient(135deg, #06b6d4 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        /* Patient Search Improvements */
        .patient-search-container {
            position: relative;
        }
        
        .patient-results-dropdown {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            max-height: 400px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
            margin-top: 4px;
        }
        
        .patient-result-item {
            padding: 1rem;
            border-bottom: 1px solid #f3f4f6;
            cursor: pointer;
            transition: background 0.2s;
        }
        
        .patient-result-item:hover {
            background: #f9fafb;
        }
        
        .patient-result-item:last-child {
            border-bottom: none;
        }
        
        .patient-result-item.selected {
            background: #eff6ff;
            border-left: 4px solid #3b82f6;
        }
        
        .selected-patient-badge {
            background: #dcfce7;
            border: 2px solid #10b981;
            border-radius: 8px;
            padding: 1rem;
            display: none;
        }
        
        .selected-patient-badge.show {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .smart-suggestion {
            background: white;
            border: 2px solid #e0e7ff;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .smart-suggestion:hover {
            border-color: #6366f1;
            box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2);
            transform: translateY(-2px);
        }
        
        .smart-suggestion.selected {
            border-color: #10b981;
            background: #f0fdf4;
        }
        
        .ai-badge {
            position: absolute;
            top: -10px;
            right: 10px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        
        .optimization-score {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            background: #fef3c7;
            color: #92400e;
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-weight: 600;
        }
        
        .time-slot {
            background: white;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .time-slot:hover:not(.unavailable) {
            border-color: #3b82f6;
            background: #eff6ff;
        }
        
        .time-slot.selected {
            border-color: #10b981;
            background: #d1fae5;
        }
        
        .time-slot.unavailable {
            background: #f1f5f9;
            cursor: not-allowed;
            opacity: 0.5;
        }
        
        .time-slot.ai-recommended {
            border-color: #6366f1;
            background: #eef2ff;
            position: relative;
        }
        
        .time-slot.ai-recommended::after {
            content: "⭐";
            position: absolute;
            top: -8px;
            right: -8px;
            font-size: 1rem;
        }
        
        .ai-insights-panel {
            background: #f8fafc;
            border-radius: 12px;
            padding: 1.5rem;
        }
        
        .insight-item {
            display: flex;
            align-items: start;
            gap: 1rem;
            padding: 1rem;
            background: white;
            border-radius: 8px;
            margin-bottom: 0.5rem;
        }
        
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            z-index: 999;
        }
        
        .no-results {
            padding: 2rem;
            text-align: center;
            color: #6b7280;
        }
        
        .search-hint {
            font-size: 0.875rem;
            color: #6b7280;
            margin-top: 0.5rem;
        }
        
        .quick-actions {
            display: flex;
            gap: 0.5rem;
            flex-wrap: wrap;
        }
        
        .quick-action-btn {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            border: 2px solid #e5e7eb;
            background: white;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .quick-action-btn:hover {
            border-color: #3b82f6;
            background: #eff6ff;
        }
    </style>
</head>

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

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Header -->
                    <div class="ai-scheduler-header">
                        <div class="row align-items-center">
                            <div class="col-auto">
                                <div style="font-size: 3rem;">🤖📅</div>
                            </div>
                            <div class="col">
                                <h2 class="mb-1">AI-Powered Smart Scheduler</h2>
                                <p class="mb-0 opacity-90">
                                    Intelligent appointment optimization • Wait time prediction • Automated conflicts resolution
                                </p>
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-light" onclick="showSchedulingStats()">
                                    <i class="ri-bar-chart-line me-1"></i> View Stats
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left: Appointment Form -->
                        <div class="col-lg-7">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0">
                                        <i class="ri-calendar-event-line me-2"></i>Schedule New Appointment
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form id="appointmentForm">
                                        <!-- Patient Selection -->
                                        <div class="mb-4">
                                            <label class="form-label fw-bold">
                                                Patient <span class="text-danger">*</span>
                                            </label>
                                            
                                            <!-- Selected Patient Badge -->
                                            <div class="selected-patient-badge mb-2" id="selectedPatientBadge">
                                                <div>
                                                    <div class="d-flex align-items-center gap-2">
                                                        <i class="ri-user-line fs-5 text-success"></i>
                                                        <div>
                                                            <div class="fw-bold" id="selectedPatientName"></div>
                                                            <small class="text-muted" id="selectedPatientInfo"></small>
                                                        </div>
                                                    </div>
                                                </div>
                                                <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearPatientSelection()">
                                                    <i class="ri-close-line"></i>
                                                </button>
                                            </div>
                                            
                                            <!-- Search Input -->
                                            <div class="patient-search-container">
                                                <div class="input-group">
                                                    <span class="input-group-text">
                                                        <i class="ri-search-line"></i>
                                                    </span>
                                                    <input type="text" 
                                                           class="form-control form-control-lg" 
                                                           id="patientSearch" 
                                                           placeholder="Search by name, phone, or patient number..."
                                                           autocomplete="off">
                                                    <button class="btn btn-outline-primary" 
                                                            type="button" 
                                                            onclick="openPatientModal()">
                                                        <i class="ri-add-line me-1"></i> New Patient
                                                    </button>
                                                </div>
                                                
                                                <div class="search-hint">
                                                    <i class="ri-information-line"></i> 
                                                    Start typing at least 2 characters to search
                                                </div>
                                                
                                                <!-- Search Results Dropdown -->
                                                <div class="patient-results-dropdown" id="patientResults" style="display: none;">
                                                    <!-- Results will be populated here -->
                                                </div>
                                            </div>
                                            
                                            <input type="hidden" id="selectedPatientId" name="patient_id">
                                        </div>

                                        <!-- Appointment Type -->
                                        <div class="mb-4">
                                            <label class="form-label fw-bold">
                                                Appointment Type <span class="text-danger">*</span>
                                            </label>
                                            <select class="form-select form-select-lg" 
                                                    id="appointmentType" 
                                                    name="appointment_type"
                                                    onchange="analyzeRequirements()">
                                                <option value="">Select appointment type...</option>
                                                <?php foreach($appointment_types as $type): ?>
                                                <option value="<?php echo $type; ?>">
                                                    <?php echo ucwords(str_replace('_', ' ', strtolower($type))); ?>
                                                </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>

                                        <!-- Chief Complaint -->
                                        <div class="mb-4">
                                            <label class="form-label fw-bold">
                                                Chief Complaint <span class="text-danger">*</span>
                                            </label>
                                            <textarea class="form-control" 
                                                      id="chiefComplaint" 
                                                      name="chief_complaint"
                                                      rows="4" 
                                                      placeholder="Describe the symptoms or reason for visit..."
                                                      oninput="analyzeRequirements()"></textarea>
                                            <small class="text-muted">
                                                <i class="ri-ai-generate me-1"></i>
                                                AI will analyze symptoms and suggest the best doctor
                                            </small>
                                        </div>

                                        <!-- AI Smart Suggestions -->
                                        <div id="aiSuggestions" style="display: none;">
                                            <div class="alert alert-info mb-3">
                                                <i class="ri-lightbulb-line me-2"></i>
                                                <strong>AI is analyzing your request...</strong>
                                            </div>
                                            <h6 class="mb-3 fw-bold">
                                                <i class="ri-robot-line me-2"></i>Recommended Doctors
                                            </h6>
                                            <div id="suggestionsContent"></div>
                                        </div>

                                        <!-- Manual Doctor Selection -->
                                        <div class="mb-4">
                                            <label class="form-label fw-bold">Or Select Doctor Manually</label>
                                            <select class="form-select" 
                                                    id="doctorSelect" 
                                                    name="doctor_id"
                                                    onchange="loadDoctorAvailability()">
                                                <option value="">Choose a doctor...</option>
                                                <?php while($doctor = $doctors->fetch_assoc()): ?>
                                                <option value="<?php echo $doctor['doctor_id']; ?>"
                                                        data-specialization="<?php echo $doctor['specialization']; ?>"
                                                        data-fee="<?php echo $doctor['consultation_fee']; ?>">
                                                    <?php echo htmlspecialchars($doctor['full_name']); ?> 
                                                    - <?php echo $doctor['specialization']; ?>
                                                    <?php if($doctor['is_consultant']): ?>(Consultant)<?php endif; ?>
                                                </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>

                                        <!-- Date Selection -->
                                        <div class="mb-4" id="dateSelectionSection" style="display: none;">
                                            <label class="form-label fw-bold">
                                                Preferred Date <span class="text-danger">*</span>
                                            </label>
                                            <input type="text" 
                                                   class="form-control" 
                                                   id="appointmentDate" 
                                                   name="appointment_date"
                                                   placeholder="Select date">
                                        </div>

                                        <!-- Time Slots -->
                                        <div id="timeSlotsSection" style="display: none;">
                                            <label class="form-label fw-bold">
                                                Available Time Slots <span class="text-danger">*</span>
                                            </label>
                                            <div id="timeSlots" class="row g-2"></div>
                                        </div>

                                        <!-- Special Requirements -->
                                        <div class="mb-4 mt-4">
                                            <label class="form-label fw-bold">Special Requirements (Optional)</label>
                                            <textarea class="form-control" 
                                                      name="special_requirements" 
                                                      rows="2"
                                                      placeholder="Any special needs or accommodations..."></textarea>
                                        </div>

                                        <!-- Submit Button -->
                                        <div class="d-grid gap-2">
                                            <button type="submit" 
                                                    class="btn btn-primary btn-lg" 
                                                    id="submitBtn" 
                                                    disabled>
                                                <i class="ri-calendar-check-line me-2"></i>
                                                Confirm Appointment
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>

                        <!-- Right: AI Insights & Calendar -->
                        <div class="col-lg-5">
                            <!-- AI Optimization Insights -->
                            <div class="card mb-3">
                                <div class="card-header bg-primary text-white">
                                    <h6 class="mb-0">
                                        <i class="ri-brain-line me-2"></i>AI Scheduling Insights
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div id="aiInsights">
                                        <div class="text-center text-muted py-4">
                                            <i class="ri-robot-line" style="font-size: 3rem; opacity: 0.3;"></i>
                                            <p class="mt-3">Select patient and provide symptoms to see AI recommendations</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Doctor Availability Calendar -->
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="mb-0">
                                        <i class="ri-calendar-2-line me-2"></i>Doctor Availability
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div id="availabilityCalendar">
                                        <p class="text-muted text-center">
                                            <i class="ri-calendar-line" style="font-size: 2rem; opacity: 0.3;"></i><br>
                                            Select a doctor to view availability
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <!-- Real-time Capacity Monitor -->
                            <div class="card mt-3">
                                <div class="card-header">
                                    <h6 class="mb-0">
                                        <i class="ri-pulse-line me-2"></i>Today's Capacity
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div id="capacityMonitor">
                                        <div class="d-flex justify-content-between align-items-center mb-2">
                                            <span>Scheduled</span>
                                            <strong id="todayScheduled">--</strong>
                                        </div>
                                        <div class="progress mb-3" style="height: 20px;">
                                            <div class="progress-bar bg-success" 
                                                 id="capacityBar" 
                                                 style="width: 0%"></div>
                                        </div>
                                        <div class="d-flex justify-content-between text-sm">
                                            <span class="text-muted">Available Slots</span>
                                            <span id="availableSlots">--</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </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="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>

    <script>
        let selectedDoctor = null;
        let selectedDate = null;
        let selectedTimeSlot = null;
        let selectedPatient = null;
        let searchTimeout = null;
        let currentRequest = null;

        // Enhanced Patient Search with Debouncing
        $('#patientSearch').on('input', function() {
            const query = $(this).val().trim();
            
            // Clear previous timeout
            if (searchTimeout) {
                clearTimeout(searchTimeout);
            }
            
            // Hide results if query is too short
            if (query.length < 2) {
                $('#patientResults').hide().empty();
                return;
            }
            
            // Show loading state
            $('#patientResults').show().html(`
                <div class="loading-overlay">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">Searching...</span>
                    </div>
                </div>
            `);
            
            // Debounce the search (wait 300ms after user stops typing)
            searchTimeout = setTimeout(() => {
                searchPatients(query);
            }, 300);
        });
        
        // Close dropdown when clicking outside
        $(document).on('click', function(e) {
            if (!$(e.target).closest('.patient-search-container').length) {
                $('#patientResults').hide();
            }
        });
        
        // Improved Patient Search Function
        function searchPatients(query) {
            // Cancel previous request if it exists
            if (currentRequest) {
                currentRequest.abort();
            }

            currentRequest = $.ajax({
                url: 'ajax/search_patients.php',
                type: 'POST',
                data: { query: query },
                dataType: 'json',
                success: function(response) {
                    console.log('Search Response:', response);

                    const patients = response.results || [];

                    if (patients.length === 0) {
                        $('#patientResults').html(`
                            <div class="no-results text-center py-3">
                                <i class="ri-user-search-line" style="font-size: 2rem; opacity: 0.3;"></i>
                                <p class="mt-2 mb-1">No patients found</p>
                                <small class="text-muted">Try a different search term</small>
                            </div>
                        `);
                        return;
                    }

                    let html = '';
                    patients.forEach((patient, index) => {
                        const safeName = escapeHtml(patient.full_name || '');
                        const safeNumber = escapeHtml(patient.patient_number || '');
                        const safePhone = escapeHtml(patient.phone || '');
                        const safeAge = escapeHtml(patient.age || '');
                        const registrationType = escapeHtml(patient.registration_type || '');

                        html += `
                            <div class="patient-result-item" 
                                 data-index="${index}" 
                                 onclick="selectPatient(
                                     ${patient.id}, 
                                     '${safeName}', 
                                     '${safeNumber}', 
                                     '${safePhone}', 
                                     '${safeAge}'
                                 )">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="flex-grow-1">
                                        <div class="fw-bold text-dark mb-1">
                                            <i class="ri-user-line me-1 text-primary"></i>
                                            ${safeName}
                                        </div>
                                        <div class="d-flex flex-wrap gap-3 text-muted small">
                                            <span>
                                                <i class="ri-hashtag me-1"></i>
                                                ${safeNumber}
                                            </span>
                                            ${patient.phone ? `
                                            <span>
                                                <i class="ri-phone-line me-1"></i>
                                                ${safePhone}
                                            </span>` : ''}
                                            ${patient.age ? `
                                            <span>
                                                <i class="ri-calendar-line me-1"></i>
                                                ${safeAge}
                                            </span>` : ''}
                                            ${registrationType ? `
                                            <span>
                                                <i class="ri-file-list-line me-1"></i>
                                                ${registrationType}
                                            </span>` : ''}
                                        </div>
                                    </div>
                                    <i class="ri-arrow-right-s-line text-muted"></i>
                                </div>
                            </div>
                        `;
                    });

                    $('#patientResults').html(html);
                },
                error: function(xhr, status, error) {
                    if (status !== 'abort') {
                        console.error('Search Error:', error);
                        $('#patientResults').html(`
                            <div class="no-results text-center py-3">
                                <i class="ri-alert-line text-danger" style="font-size: 2rem;"></i>
                                <p class="mt-2 mb-1 text-danger">Search failed</p>
                                <small class="text-muted">Please try again</small>
                            </div>
                        `);
                    }
                },
                complete: function() {
                    currentRequest = null;
                }
            });
        }
        
        // Helper function to escape HTML
        function escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            return String(text).replace(/[&<>"']/g, m => map[m]);
        }
        
        // Select Patient Function
        function selectPatient(id, name, number, phone, age) {
            selectedPatient = {
                id: id,
                name: name,
                number: number,
                phone: phone,
                age: age
            };
            
            $('#selectedPatientId').val(id);
            $('#patientSearch').val('');
            $('#patientResults').hide().empty();
            
            // Show selected patient badge
            $('#selectedPatientName').text(name);
            $('#selectedPatientInfo').text(`${number} ${phone ? '• ' + phone : ''} ${age ? '• ' + age : ''}`);
            $('#selectedPatientBadge').addClass('show');
            
            // Enable next steps
            analyzeRequirements();
            
            // Show success message
            Swal.fire({
                icon: 'success',
                title: 'Patient Selected',
                text: name,
                timer: 1500,
                showConfirmButton: false,
                toast: true,
                position: 'top-end'
            });
        }
        
        // Clear Patient Selection
        function clearPatientSelection() {
            selectedPatient = null;
            $('#selectedPatientId').val('');
            $('#selectedPatientBadge').removeClass('show');
            $('#patientSearch').val('').focus();
            $('#submitBtn').prop('disabled', true);
        }
        
        // Open Patient Registration Modal
        function openPatientModal() {
            Swal.fire({
                title: 'Register New Patient',
                html: `
                    <p class="text-muted">Would you like to register a new patient?</p>
                    <p class="small">You will be redirected to the patient registration page.</p>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Register',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.open('register_patient.php', '_blank');
                }
            });
        }

        // Analyze requirements and get AI suggestions using ajax/ai_assistant.php
        async function analyzeRequirements() {
            const type = $('#appointmentType').val();
            const complaint = $('#chiefComplaint').val().trim();

            if (!selectedPatient || !type || !complaint || complaint.length < 10) {
                return;
            }

            $('#aiInsights').html(`
                <div class="text-center p-3">
                    <div class="spinner-border text-primary"></div>
                    <p class="mt-2 mb-0">AI is analyzing...</p>
                </div>
            `);
            
            $('#aiSuggestions').show().find('.alert').show();

            try {
                const response = await $.ajax({
                    url: 'ajax/ai_assistant.php',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        action: 'analyze_scheduling',
                        data: {
                            complaint: complaint,
                            appointment_type: type,
                            patient_id: selectedPatient.id
                        }
                    }),
                    dataType: 'json'
                });

                if (response.success && response.analysis) {
                    displayAIInsights(response.analysis);
                    suggestDoctors(response.analysis);
                } else {
                    throw new Error(response.message || 'AI analysis failed');
                }
            } catch (error) {
                console.error("AI Analysis Error:", error);
                $('#aiInsights').html(`
                    <div class="alert alert-warning">
                        <i class="ri-alert-line me-2"></i>
                        AI analysis temporarily unavailable. Please select a doctor manually.
                    </div>
                `);
                $('#aiSuggestions').hide();
            }
        }

        // Display AI insights
        function displayAIInsights(analysis) {
            const urgencyColor = {
                'ROUTINE': 'info',
                'URGENT': 'warning',
                'EMERGENCY': 'danger'
            };

            const html = `
                <div class="ai-insights-panel">
                    <div class="insight-item">
                        <div style="font-size: 1.5rem;">🎯</div>
                        <div class="flex-grow-1">
                            <strong>Recommended Specialist</strong>
                            <p class="mb-0 text-muted">${analysis.recommended_specialization}</p>
                        </div>
                    </div>
                    <div class="insight-item">
                        <div style="font-size: 1.5rem;">⚡</div>
                        <div class="flex-grow-1">
                            <strong>Urgency Level</strong>
                            <p class="mb-0">
                                <span class="badge bg-${urgencyColor[analysis.urgency_level]}">${analysis.urgency_level}</span>
                            </p>
                        </div>
                    </div>
                    <div class="insight-item">
                        <div style="font-size: 1.5rem;">⏱️</div>
                        <div class="flex-grow-1">
                            <strong>Estimated Duration</strong>
                            <p class="mb-0 text-muted">${analysis.estimated_duration} minutes</p>
                        </div>
                    </div>
                    <div class="insight-item">
                        <div style="font-size: 1.5rem;">🕐</div>
                        <div class="flex-grow-1">
                            <strong>Best Time</strong>
                            <p class="mb-0 text-muted">${analysis.best_time_of_day}</p>
                        </div>
                    </div>
                    <div class="alert alert-info mt-3 mb-0">
                        <i class="ri-information-line me-2"></i>
                        ${analysis.reasoning}
                    </div>
                </div>
            `;

            $('#aiInsights').html(html);
        }

        // Suggest doctors based on AI analysis
        function suggestDoctors(analysis) {
            $.ajax({
                url: 'ajax/suggest_doctors.php',
                type: 'POST',
                data: {
                    specialization: analysis.recommended_specialization,
                    urgency: analysis.urgency_level,
                    time_preference: analysis.best_time_of_day,
                    duration: analysis.estimated_duration
                },
                dataType: 'json',
                success: function(doctors) {
                    $('#aiSuggestions .alert').hide();
                    
                    if (doctors.length === 0) {
                        $('#suggestionsContent').html(`
                            <div class="alert alert-warning">
                                <i class="ri-alert-line me-2"></i>
                                No doctors found matching the AI recommendations. Please select manually.
                            </div>
                        `);
                        return;
                    }

                    let html = '';
                    doctors.forEach((doctor, index) => {
                        const scorePercent = (doctor.match_score * 100).toFixed(0);
                        html += `
                            <div class="smart-suggestion ${index === 0 ? 'selected' : ''}" 
                                 onclick="selectRecommendedDoctor(${doctor.doctor_id})">
                                ${index === 0 ? '<span class="ai-badge">Best Match</span>' : ''}
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <h6 class="mb-1">${doctor.name}</h6>
                                        <p class="mb-1 text-muted">${doctor.specialization}</p>
                                        <div class="d-flex align-items-center gap-2">
                                            <span class="badge ${doctor.availability_status === 'available' ? 'bg-success' : doctor.availability_status === 'busy' ? 'bg-warning' : 'bg-danger'}">
                                                ${doctor.availability_status}
                                            </span>
                                            <small class="text-muted">Next: ${doctor.next_available_slot}</small>
                                        </div>
                                    </div>
                                    <div class="optimization-score">
                                        <i class="ri-star-fill"></i>
                                        ${scorePercent}%
                                    </div>
                                </div>
                                <div class="row text-center mt-3">
                                    <div class="col-4">
                                        <small class="text-muted">Fee</small>
                                        <div><strong>KES ${parseFloat(doctor.consultation_fee).toLocaleString()}</strong></div>
                                    </div>
                                    <div class="col-4">
                                        <small class="text-muted">Wait Time</small>
                                        <div><strong>${doctor.avg_wait_time} min</strong></div>
                                    </div>
                                    <div class="col-4">
                                        <small class="text-muted">Available</small>
                                        <div><strong>${doctor.available_slots_today} slots</strong></div>
                                    </div>
                                </div>
                            </div>
                        `;
                    });

                    $('#suggestionsContent').html(html);
                    
                    // Auto-select the first (best) doctor
                    if (doctors.length > 0) {
                        selectRecommendedDoctor(doctors[0].doctor_id);
                    }
                },
                error: function() {
                    $('#aiSuggestions .alert').hide();
                    $('#suggestionsContent').html(`
                        <div class="alert alert-danger">
                            <i class="ri-error-warning-line me-2"></i>
                            Failed to load doctor suggestions. Please select manually.
                        </div>
                    `);
                }
            });
        }

        // Select recommended doctor
        function selectRecommendedDoctor(doctorId) {
            $('.smart-suggestion').removeClass('selected');
            event.currentTarget.classList.add('selected');
            
            $('#doctorSelect').val(doctorId);
            selectedDoctor = doctorId;
            loadDoctorAvailability();
        }

        // Load doctor availability
        function loadDoctorAvailability() {
            const doctorId = $('#doctorSelect').val();
            if (!doctorId) return;

            selectedDoctor = doctorId;
            $('#dateSelectionSection').show();

            // Initialize date picker
            if (!document.getElementById('appointmentDate')._flatpickr) {
                flatpickr("#appointmentDate", {
                    minDate: "today",
                    maxDate: new Date().fp_incr(30),
                    disable: [
                        function(date) {
                            return (date.getDay() === 0); // Disable Sundays
                        }
                    ],
                    onChange: function(selectedDates, dateStr) {
                        selectedDate = dateStr;
                        loadTimeSlots();
                    }
                });
            }

            loadAvailabilityCalendar(doctorId);
            loadCapacityMetrics(doctorId);
        }

        // Load availability calendar
        function loadAvailabilityCalendar(doctorId) {
            $.ajax({
                url: 'ajax/get_doctor_availability_calendar.php',
                type: 'POST',
                data: { doctor_id: doctorId, days: 14 },
                dataType: 'json',
                success: function(response) {
                    console.log('Calendar Response:', response);
                    
                    if (!response.success) {
                        $('#availabilityCalendar').html(`
                            <div class="alert alert-warning">
                                <i class="ri-calendar-close-line me-2"></i>
                                ${response.error || 'Failed to load availability'}
                            </div>
                        `);
                        return;
                    }
                    
                    const availability = response.days || [];
                    
                    if (availability.length === 0) {
                        $('#availabilityCalendar').html(`
                            <div class="alert alert-info">
                                <i class="ri-information-line me-2"></i>
                                No availability data found for this doctor.
                            </div>
                        `);
                        return;
                    }
                    
                    let html = '<div class="row g-2">';
                    availability.forEach(day => {
                        // Skip non-working days
                        if (!day.is_working_day) {
                            return;
                        }
                        
                        // Determine badge color based on availability
                        let badgeColor = 'secondary';
                        if (day.available_slots > 5) {
                            badgeColor = 'success';
                        } else if (day.available_slots > 0) {
                            badgeColor = 'warning';
                        } else {
                            badgeColor = 'danger';
                        }
                        
                        const isDisabled = day.available_slots === 0;
                        
                        html += `
                            <div class="col-6 col-md-4">
                                <div class="calendar-day ${isDisabled ? 'unavailable' : ''}"
                                     style="border: 2px solid #e5e7eb; border-radius: 8px; padding: 0.75rem; cursor: ${isDisabled ? 'not-allowed' : 'pointer'}; transition: all 0.2s; opacity: ${isDisabled ? '0.5' : '1'};"
                                     onclick="${isDisabled ? '' : `selectCalendarDate('${day.date}')`}">
                                    <div class="fw-bold">${day.day_name}</div>
                                    <div class="small text-muted">${day.date_formatted}</div>
                                    <div class="mt-2">
                                        <span class="badge bg-${badgeColor}">
                                            ${day.available_slots} slot${day.available_slots !== 1 ? 's' : ''}
                                        </span>
                                    </div>
                                    <div class="small text-muted mt-1">
                                        ${day.booked_slots}/${day.total_capacity} booked
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                    html += '</div>';
                    
                    $('#availabilityCalendar').html(html);
                },
                error: function(xhr, status, error) {
                    console.error('Calendar Error:', error);
                    $('#availabilityCalendar').html(`
                        <div class="alert alert-danger">
                            <i class="ri-error-warning-line me-2"></i>
                            Failed to load availability calendar. Please try again.
                        </div>
                    `);
                }
            });
        }

        // Select date from calendar
        function selectCalendarDate(date) {
            $('#appointmentDate').val(date);
            selectedDate = date;
            loadTimeSlots();
        }

        // Load time slots
        function loadTimeSlots() {
            if (!selectedDoctor || !selectedDate) return;

            $('#timeSlotsSection').show();
            $('#timeSlots').html(`
                <div class="col-12 text-center py-3">
                    <div class="spinner-border text-primary"></div>
                    <p class="mt-2 mb-0">Loading available slots...</p>
                </div>
            `);

            $.ajax({
                url: 'ajax/get_available_slots.php',
                type: 'POST',
                data: {
                    doctor_id: selectedDoctor,
                    date: selectedDate
                },
                dataType: 'json',
                success: function(slots) {
                    if (slots.length === 0) {
                        $('#timeSlots').html(`
                            <div class="col-12">
                                <div class="alert alert-info text-center">
                                    <i class="ri-calendar-close-line fs-2 mb-2"></i>
                                    <p class="mb-0">No available slots for this date. Please choose another date.</p>
                                </div>
                            </div>
                        `);
                        return;
                    }

                    let html = '';
                    slots.forEach(slot => {
                        const isRecommended = slot.is_ai_recommended;
                        const classes = `time-slot ${slot.is_available ? '' : 'unavailable'} ${isRecommended ? 'ai-recommended' : ''}`;
                        
                        html += `
                            <div class="col-6 col-md-3">
                                <div class="${classes}" 
                                     data-slot-id="${slot.slot_id}"
                                     data-time="${slot.start_time}"
                                     onclick="selectTimeSlot(this, ${slot.is_available})">
                                    <div class="fw-bold">${slot.start_time}</div>
                                    ${slot.estimated_wait_time ? 
                                        `<small class="badge bg-info mt-1">${slot.estimated_wait_time}min wait</small>` : 
                                        ''}
                                </div>
                            </div>
                        `;
                    });

                    $('#timeSlots').html(html);
                },
                error: function() {
                    $('#timeSlots').html(`
                        <div class="col-12">
                            <div class="alert alert-danger">
                                <i class="ri-error-warning-line me-2"></i>
                                Failed to load time slots. Please try again.
                            </div>
                        </div>
                    `);
                }
            });
        }

        // Select time slot
        function selectTimeSlot(element, isAvailable) {
            if (!isAvailable) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Slot Unavailable',
                    text: 'This time slot is not available. Please choose another.',
                    timer: 2000,
                    showConfirmButton: false
                });
                return;
            }

            $('.time-slot').removeClass('selected');
            element.classList.add('selected');
            
            selectedTimeSlot = {
                slot_id: element.dataset.slotId,
                time: element.dataset.time
            };

            // Enable submit button if all required fields are filled
            if (selectedPatient && selectedDoctor && selectedDate && selectedTimeSlot) {
                $('#submitBtn').prop('disabled', false);
            }
        }

        // Load capacity metrics
        function loadCapacityMetrics(doctorId) {
            $.ajax({
                url: 'ajax/get_capacity_metrics.php',
                type: 'POST',
                data: { doctor_id: doctorId },
                dataType: 'json',
                success: function(response) {
                    console.log('Capacity Response:', response);
                    
                    if (!response.success) {
                        console.error('Capacity metrics error:', response.error);
                        return;
                    }
                    
                    // Update scheduled count
                    $('#todayScheduled').text(response.scheduled_today || 0);
                    
                    // Update available slots
                    $('#availableSlots').text(response.available_slots || 0);
                    
                    // Update capacity bar
                    const capacityPercent = response.capacity_percent || 0;
                    $('#capacityBar').css('width', capacityPercent + '%');
                    
                    // Change bar color based on capacity
                    $('#capacityBar').removeClass('bg-success bg-warning bg-danger');
                    if (capacityPercent >= 90) {
                        $('#capacityBar').addClass('bg-danger');
                    } else if (capacityPercent >= 70) {
                        $('#capacityBar').addClass('bg-warning');
                    } else {
                        $('#capacityBar').addClass('bg-success');
                    }
                    
                    // Optional: Add tooltip or additional info
                    $('#capacityMonitor').attr('title', 
                        `${response.checked_in_today || 0} checked in, ${response.completed_today || 0} completed`
                    );
                },
                error: function(xhr, status, error) {
                    console.error('Capacity metrics error:', error);
                    // Keep default values
                }
            });
        }

        // Submit appointment form
        $('#appointmentForm').on('submit', function (e) {
            e.preventDefault();

            // Validate required fields
            if (!selectedPatient || !selectedDoctor || !selectedDate || !selectedTimeSlot) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Incomplete Form',
                    text: 'Please complete all required fields before submitting.'
                });
                return;
            }

            // Prepare form data
            const formData = new FormData(this);
            formData.append('slot_id', selectedTimeSlot.slot_id);
            formData.append('appointment_time', selectedTimeSlot.time);

            // Show confirmation popup
            Swal.fire({
                title: 'Confirm Appointment',
                html: `
                    <div class="text-start">
                        <table class="table table-sm">
                            <tr><th>Patient:</th><td>${selectedPatient.name}</td></tr>
                            <tr><th>Patient No:</th><td>${selectedPatient.number}</td></tr>
                            <tr><th>Date:</th><td>${selectedDate}</td></tr>
                            <tr><th>Time:</th><td>${selectedTimeSlot.time}</td></tr>
                        </table>
                    </div>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: '<i class="ri-check-line me-1"></i> Yes, Book Appointment',
                cancelButtonText: '<i class="ri-close-line me-1"></i> Cancel',
                showLoaderOnConfirm: true,
                allowOutsideClick: () => !Swal.isLoading(),
                preConfirm: () => {
                    return new Promise((resolve, reject) => {
                        $.ajax({
                            url: 'ajax/book_appointment.php',
                            type: 'POST',
                            data: formData,
                            processData: false,
                            contentType: false,
                            dataType: 'json',
                            success: function (response) {
                                console.log('Booking Response:', response);
                                if (response.success) {
                                    resolve(response);
                                } else {
                                    reject(response.message || 'Booking failed');
                                }
                            },
                            error: function (xhr, status, error) {
                                console.error('AJAX Error Details:', {
                                    status: status,
                                    error: error,
                                    responseText: xhr.responseText
                                });
                                reject('Server error occurred. Please check the console for details.');
                            }
                        });
                    });
                }
            }).then((result) => {
                if (result.isConfirmed && result.value) {
                    const data = result.value;

                    Swal.fire({
                        icon: 'success',
                        title: 'Appointment Booked Successfully!',
                        html: `
                            <div class="text-start">
                                <p><strong>Appointment Number:</strong> <span class="text-primary">${data.appointment_number}</span></p>
                                <p><strong>Patient:</strong> ${selectedPatient.name}</p>
                                <p><strong>Date & Time:</strong> ${selectedDate} at ${selectedTimeSlot.time}</p>
                                <hr>
                                <p class="text-muted small">
                                    <i class="ri-information-line me-1"></i>
                                    Confirmation has been sent via SMS/Email
                                </p>
                            </div>
                        `,
                        showCancelButton: true,
                        confirmButtonText: '<i class="ri-eye-line me-1"></i> View Appointment',
                        cancelButtonText: '<i class="ri-add-line me-1"></i> Book Another'
                    }).then((action) => {
                        if (action.isConfirmed) {
                            window.location.href = 'view_appointment.php?id=' + data.appointment_id;
                        } else {
                            location.reload();
                        }
                    });
                }
            }).catch((error) => {
                Swal.fire({
                    icon: 'error',
                    title: 'Booking Failed',
                    text: typeof error === 'string' ? error : 'Failed to book appointment. Please try again.'
                });
            });
        });

        // Show scheduling statistics
        function showSchedulingStats() {
            $.ajax({
                url: 'ajax/get_scheduling_stats.php',
                type: 'GET',
                dataType: 'json',
                success: function(response) {
                    console.log('Stats Response:', response);
                    
                    if (!response.success) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error Loading Statistics',
                            text: response.error || 'Failed to load statistics'
                        });
                        return;
                    }
                    
                    // Build the statistics HTML
                    let html = `
                        <div class="text-start">
                            <h6 class="border-bottom pb-2 mb-3">
                                <i class="ri-calendar-line me-2"></i>Today's Statistics
                                <small class="text-muted float-end">${response.date}</small>
                            </h6>
                            
                            <!-- Main Stats Grid -->
                            <div class="row g-2 mb-3">
                                <div class="col-6">
                                    <div class="text-center p-3 bg-light rounded">
                                        <h3 class="mb-0 text-primary">${response.total_today || 0}</h3>
                                        <small>Total</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-3 bg-light rounded">
                                        <h3 class="mb-0 text-success">${response.checked_in || 0}</h3>
                                        <small>Checked In</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-3 bg-light rounded">
                                        <h3 class="mb-0 text-info">${response.completed || 0}</h3>
                                        <small>Completed</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="text-center p-3 bg-light rounded">
                                        <h3 class="mb-0 text-warning">${response.no_shows || 0}</h3>
                                        <small>No Shows</small>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Status Breakdown -->
                            <div class="alert alert-info small mb-3">
                                <div class="d-flex justify-content-between">
                                    <span>Scheduled: ${response.scheduled || 0}</span>
                                    <span>In Progress: ${response.in_progress || 0}</span>
                                </div>
                                <div class="d-flex justify-content-between mt-1">
                                    <span>Cancelled: ${response.cancelled || 0}</span>
                                    <span>Confirmed: ${response.confirmed || 0}</span>
                                </div>
                            </div>
                            
                            <!-- Performance Rates -->
                            <h6 class="border-bottom pb-2 mb-3 mt-4">
                                <i class="ri-line-chart-line me-2"></i>Performance Metrics
                            </h6>
                            <div class="row g-2 mb-3">
                                <div class="col-4">
                                    <div class="text-center">
                                        <div class="small text-muted">Completion</div>
                                        <div class="fw-bold text-success">${response.completion_rate || 0}%</div>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="text-center">
                                        <div class="small text-muted">No Show</div>
                                        <div class="fw-bold text-warning">${response.no_show_rate || 0}%</div>
                                    </div>
                                </div>
                                <div class="col-4">
                                    <div class="text-center">
                                        <div class="small text-muted">Cancellation</div>
                                        <div class="fw-bold text-danger">${response.cancellation_rate || 0}%</div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- AI Performance -->
                            <h6 class="border-bottom pb-2 mb-3 mt-4">
                                <i class="ri-robot-line me-2"></i>AI Performance
                            </h6>
                            <ul class="list-unstyled">
                                <li class="mb-2">
                                    <i class="ri-checkbox-circle-line text-success me-2"></i>
                                    AI Suggestions Accepted: <strong>${response.ai_acceptance_rate || 0}%</strong>
                                </li>
                                <li class="mb-2">
                                    <i class="ri-time-line text-primary me-2"></i>
                                    Avg Wait Time Reduction: <strong>${response.wait_time_improvement || 0} min</strong>
                                </li>
                                <li class="mb-2">
                                    <i class="ri-line-chart-line text-info me-2"></i>
                                    Scheduling Efficiency: <strong>${response.efficiency_score || 0}%</strong>
                                </li>
                            </ul>
                    `;
                    
                    // Add top doctors if available
                    if (response.top_doctors && response.top_doctors.length > 0) {
                        html += `
                            <h6 class="border-bottom pb-2 mb-3 mt-4">
                                <i class="ri-user-star-line me-2"></i>Top Doctors Today
                            </h6>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Doctor</th>
                                            <th class="text-center">Appointments</th>
                                            <th class="text-center">Utilization</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                        `;
                        
                        response.top_doctors.forEach(doctor => {
                            html += `
                                <tr>
                                    <td>
                                        <div class="fw-bold">${doctor.name}</div>
                                        <small class="text-muted">${doctor.specialization}</small>
                                    </td>
                                    <td class="text-center">${doctor.appointments_today}/${doctor.capacity}</td>
                                    <td class="text-center">
                                        <span class="badge bg-${doctor.utilization_percent >= 90 ? 'danger' : doctor.utilization_percent >= 70 ? 'warning' : 'success'}">
                                            ${doctor.utilization_percent}%
                                        </span>
                                    </td>
                                </tr>
                            `;
                        });
                        
                        html += `
                                    </tbody>
                                </table>
                            </div>
                        `;
                    }
                    
                    html += '</div>';
                    
                    // Show in SweetAlert
                    Swal.fire({
                        title: '<i class="ri-bar-chart-line me-2"></i>Scheduling Analytics',
                        html: html,
                        width: '700px',
                        confirmButtonText: '<i class="ri-close-line me-1"></i> Close',
                        customClass: {
                            container: 'stats-modal'
                        }
                    });
                },
                error: function(xhr, status, error) {
                    console.error('Stats Error:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load statistics. Please try again.'
                    });
                }
            });
        }

        // Initialize on page load
        $(document).ready(function() {
            console.log('AI Smart Scheduler initialized');
            
            // Focus on patient search
            $('#patientSearch').focus();
        });
    </script>
</body>
</html>