<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once 'db_connect.php'; 

try {
    // استلام المتغيرات من التطبيق
    $governorate = $_GET['governorate'] ?? '';
    $specialty = $_GET['specialty'] ?? '';
    $name = $_GET['name'] ?? '';
    // إضافة فلتر جديد للأونلاين (إذا أرسل التطبيق online=1)
    $online_only = $_GET['online'] ?? ''; 

    $sql = "SELECT 
                d.id, 
                d.user_id,
                u.full_name, 
                u.phone, 
                u.email,
                u.city,
                u.address,
                d.specialty_id,
                d.sub_specialty_id,
                s.name_ar as specialty_name_ar, 
                s.name_en as specialty_name_en, 
                ss.name_ar as sub_specialty_name_ar,
                ss.name_en as sub_specialty_name_en,
                d.experience_years,
                d.profile_image,
                d.bio,
                d.is_online_service, -- جلب حالة خدمة الأونلاين
                d.is_available_now    -- جلب الحالة اللحظية
            FROM doctors d 
            JOIN users u ON d.user_id = u.id
            LEFT JOIN medical_specialties s ON d.specialty_id = s.id
            LEFT JOIN medical_sub_specialties ss ON d.sub_specialty_id = ss.id
            WHERE 1=1";

    $params = [];

    // إضافة شروط الفلترة في SQL
    if ($governorate != '') {
        $sql .= " AND u.city LIKE :gov";
        $params[':gov'] = "%$governorate%";
    }
    if ($specialty != '') {
        $sql .= " AND (s.name_ar LIKE :spec OR s.name_en LIKE :spec)";
        $params[':spec'] = "%$specialty%";
    }
    if ($name != '') {
        $sql .= " AND u.full_name LIKE :name";
        $params[':name'] = "%$name%";
    }
    
    // فلترة الأطباء الذين يقدمون خدمة الأونلاين فقط (اختياري)
    if ($online_only == '1') {
        $sql .= " AND d.is_online_service = 1";
    }

    $sql .= " ORDER BY d.is_available_now DESC, d.id DESC"; // ترتيب الأطباء المتاحين الآن في المقدمة
        
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    $doctors = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // تحويل القيم إلى أرقام لضمان توافقها مع فلاتر
    foreach ($doctors as &$doc) {
        $doc['is_online_service'] = (int)$doc['is_online_service'];
        $doc['is_available_now'] = (int)$doc['is_available_now'];
    }
    
    echo json_encode([
        "status" => "success",
        "data" => $doctors
    ]);
} catch (PDOException $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>