<?php
/**
 * AJAX Endpoint: Get Available Doctors and Audiologists
 * Fetches active medical staff with search and filter capabilities
 * Used for doctor selection during patient registration
 */

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

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

// Get filter parameters
$staff_type = $_GET['staff_type'] ?? 'ALL';
$search_term = $_GET['search'] ?? '';
$service_type = $_GET['service_type'] ?? '';

// Build WHERE clause
$where_clauses = [];
$params = [];
$types = '';

// Filter by staff type
if ($staff_type !== 'ALL') {
    $where_clauses[] = "staff_type = ?";
    $params[] = $staff_type;
    $types .= 's';
}

// Search filter
if (!empty($search_term)) {
    $where_clauses[] = "(staff_name LIKE ? OR specialization LIKE ? OR sub_specialization LIKE ? OR role LIKE ?)";
    $search_pattern = '%' . $search_term . '%';
    $params[] = $search_pattern;
    $params[] = $search_pattern;
    $params[] = $search_pattern;
    $params[] = $search_pattern;
    $types .= 'ssss';
}

// Auto-filter by service type if provided
if (!empty($service_type)) {
    if ($service_type === 'HEARING_TEST') {
        // Only show audiologists for hearing tests
        $where_clauses[] = "staff_type = 'AUDIOLOGIST'";
    }
    // Other service types can show all doctors
}

$where_sql = !empty($where_clauses) ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

// Query the view
$sql = "SELECT
            staff_id,
            staff_type,
            staff_code,
            staff_name,
            role,
            specialization,
            sub_specialization,
            consultation_fee,
            is_consultant,
            experience_years,
            is_available,
            user_id,
            profile_picture,
            primary_department
        FROM vw_available_medical_staff
        $where_sql
        ORDER BY
            is_available DESC,
            is_consultant DESC,
            staff_name ASC";

try {
    if (!empty($params)) {
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $result = $stmt->get_result();
    } else {
        $result = $conn->query($sql);
    }

    $staff = [];
    while ($row = $result->fetch_assoc()) {
        // Format the response
        $staff[] = [
            'staff_id' => $row['staff_id'],
            'staff_type' => $row['staff_type'],
            'user_id' => $row['user_id'],
            'staff_code' => $row['staff_code'],
            'staff_name' => $row['staff_name'],
            'role' => $row['role'],
            'specialization' => $row['specialization'] ?? 'General',
            'sub_specialization' => $row['sub_specialization'],
            'consultation_fee' => number_format($row['consultation_fee'], 2),
            'is_consultant' => (bool)$row['is_consultant'],
            'experience_years' => $row['experience_years'],
            'is_available' => (bool)$row['is_available'],
            'profile_picture' => $row['profile_picture'],
            'primary_department' => $row['primary_department'],
            'availability_status' => $row['is_available'] ? 'Available Today' : 'Limited Availability'
        ];
    }

    echo json_encode([
        'success' => true,
        'data' => $staff,
        'count' => count($staff)
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching staff: ' . $e->getMessage()
    ]);
}

$conn->close();
?>
