<?php
session_start();
header('Content-Type: application/json');

include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$response = [];

try {
    // Get AI analysis parameters
    $specialization = $_POST['specialization'] ?? '';
    $urgency = $_POST['urgency'] ?? 'ROUTINE';
    $time_preference = $_POST['time_preference'] ?? 'MORNING';
    $duration = (int)($_POST['duration'] ?? 30);
    
    $today = date('Y-m-d');
    $current_time = date('H:i:s');
    
    // Build query to find matching doctors with availability
    $sql = "SELECT 
                d.doctor_id,
                u.full_name as name,
                d.specialization,
                d.sub_specialization,
                d.consultation_fee,
                d.is_consultant,
                d.experience_years,
                d.max_daily_appointments,
                d.appointment_duration,
                
                -- Count today's appointments
                COUNT(DISTINCT a.appointment_id) as appointments_today,
                
                -- Calculate average wait time (in minutes)
                COALESCE(AVG(TIMESTAMPDIFF(MINUTE, a.scheduled_time, a.actual_start_time)), 15) as avg_wait_time,
                
                -- Calculate match score
                CASE 
                    WHEN d.specialization LIKE ? THEN 1.0
                    WHEN d.sub_specialization LIKE ? THEN 0.8
                    ELSE 0.5
                END as match_score
                
            FROM doctors d
            JOIN users u ON d.user_id = u.user_id
            LEFT JOIN appointments a ON d.doctor_id = a.doctor_id 
                AND DATE(a.scheduled_time) = ?
                AND a.status NOT IN ('CANCELLED', 'NO_SHOW')
            WHERE d.is_active = 1
            GROUP BY d.doctor_id, u.full_name, d.specialization, d.sub_specialization, 
                     d.consultation_fee, d.is_consultant, d.experience_years, 
                     d.max_daily_appointments, d.appointment_duration
            HAVING appointments_today < d.max_daily_appointments
            ORDER BY match_score DESC, d.is_consultant DESC, appointments_today ASC
            LIMIT 5";
    
    $spec_param = "%{$specialization}%";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sss", $spec_param, $spec_param, $today);
    $stmt->execute();
    $result = $stmt->get_result();
    
    while ($doctor = $result->fetch_assoc()) {
        // Calculate available slots for today
        $available_slots_today = $doctor['max_daily_appointments'] - $doctor['appointments_today'];
        
        // Determine availability status
        $capacity_percent = ($doctor['appointments_today'] / $doctor['max_daily_appointments']) * 100;
        if ($capacity_percent < 60) {
            $availability_status = 'available';
        } elseif ($capacity_percent < 85) {
            $availability_status = 'busy';
        } else {
            $availability_status = 'full';
        }
        
        // Find next available slot
        $next_slot_sql = "SELECT MIN(scheduled_time) as next_slot 
                         FROM appointments 
                         WHERE doctor_id = ? 
                         AND DATE(scheduled_time) >= CURDATE()
                         AND status = 'SCHEDULED'
                         AND scheduled_time > NOW()";
        
        $slot_stmt = $conn->prepare($next_slot_sql);
        $slot_stmt->bind_param("i", $doctor['doctor_id']);
        $slot_stmt->execute();
        $slot_result = $slot_stmt->get_result();
        $next_slot_data = $slot_result->fetch_assoc();
        
        $next_available_slot = 'Today';
        if ($next_slot_data && $next_slot_data['next_slot']) {
            $next_slot_date = new DateTime($next_slot_data['next_slot']);
            $now = new DateTime();
            $diff = $now->diff($next_slot_date);
            
            if ($diff->days == 0) {
                $next_available_slot = 'Today ' . $next_slot_date->format('H:i A');
            } elseif ($diff->days == 1) {
                $next_available_slot = 'Tomorrow ' . $next_slot_date->format('H:i A');
            } else {
                $next_available_slot = $next_slot_date->format('M d, Y');
            }
        }
        
        // Adjust match score based on urgency and consultant status
        $adjusted_score = $doctor['match_score'];
        if ($urgency === 'URGENT' && $availability_status === 'available') {
            $adjusted_score += 0.2;
        }
        if ($urgency === 'EMERGENCY' && $doctor['is_consultant']) {
            $adjusted_score += 0.3;
        }
        
        $response[] = [
            'doctor_id' => (int)$doctor['doctor_id'],
            'name' => $doctor['name'],
            'specialization' => $doctor['specialization'],
            'sub_specialization' => $doctor['sub_specialization'],
            'consultation_fee' => number_format($doctor['consultation_fee'], 2),
            'is_consultant' => (bool)$doctor['is_consultant'],
            'experience_years' => (int)$doctor['experience_years'],
            'match_score' => min($adjusted_score, 1.0),
            'availability_status' => $availability_status,
            'available_slots_today' => $available_slots_today,
            'appointments_today' => (int)$doctor['appointments_today'],
            'avg_wait_time' => round($doctor['avg_wait_time']),
            'next_available_slot' => $next_available_slot
        ];
    }
    
    $stmt->close();
    
} catch (Exception $e) {
    error_log("Doctor suggestion error: " . $e->getMessage());
    $response = [
        'error' => 'Failed to load doctor suggestions',
        'message' => $e->getMessage()
    ];
}

if (isset($conn)) {
    $conn->close();
}

echo json_encode($response);
exit();
?>