<?php
/**
 * API: جلب قائمة الفاحصين المتاحين
 * GET /api/supervisor/endpoints/get_available_inspectors.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// إعدادات الاتصال بقاعدة البيانات
$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals";
$password = "bassam.bassam";

$centerId = isset($_GET['center_id']) ? (int)$_GET['center_id'] : null;
$region = isset($_GET['region']) ? $_GET['region'] : null;

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // أولاً: التحقق من وجود جدول inspectors
    $tableCheck = $pdo->query("SHOW TABLES LIKE 'inspectors'")->rowCount();
    
    if ($tableCheck == 0) {
        // إذا لم يوجد جدول inspectors، نستخدم بيانات تجريبية
        $inspectors = [
            ['id' => 1, 'full_name' => 'أحمد محمد', 'specialization' => 'فحص شامل', 'region' => 'القاهرة', 'status' => 'available', 'rating' => 4.8, 'current_load' => 2, 'max_load' => 5, 'experience_years' => 8, 'phone' => '01012345678', 'email' => 'ahmed@autotester.com'],
            ['id' => 2, 'full_name' => 'خالد عبدالله', 'specialization' => 'كمبيوتر', 'region' => 'الإسكندرية', 'status' => 'available', 'rating' => 4.5, 'current_load' => 1, 'max_load' => 5, 'experience_years' => 5, 'phone' => '01123456789', 'email' => 'khaled@autotester.com'],
            ['id' => 3, 'full_name' => 'محمد علي', 'specialization' => 'محركات', 'region' => 'الجيزة', 'status' => 'busy', 'rating' => 4.2, 'current_load' => 4, 'max_load' => 5, 'experience_years' => 6, 'phone' => '01234567890', 'email' => 'mohamed@autotester.com'],
            ['id' => 4, 'full_name' => 'عمر حسن', 'specialization' => 'فرامل', 'region' => 'القاهرة', 'status' => 'available', 'rating' => 4.7, 'current_load' => 3, 'max_load' => 5, 'experience_years' => 7, 'phone' => '01512345678', 'email' => 'omar@autotester.com'],
            ['id' => 5, 'full_name' => 'سعيد محمود', 'specialization' => 'كهرباء', 'region' => 'بورسعيد', 'status' => 'available', 'rating' => 4.3, 'current_load' => 2, 'max_load' => 5, 'experience_years' => 4, 'phone' => '01098765432', 'email' => 'saeed@autotester.com']
        ];
        
        // تطبيق الفلاتر
        if ($centerId) {
            $inspectors = array_filter($inspectors, function($i) use ($centerId) {
                return $i['center_id'] ?? null == $centerId;
            });
        }
        
        if ($region) {
            $inspectors = array_filter($inspectors, function($i) use ($region) {
                return $i['region'] == $region;
            });
        }
        
        $inspectors = array_values($inspectors);
        
        echo json_encode([
            'success' => true,
            'data' => $inspectors,
            'total' => count($inspectors),
            'source' => 'mock'
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    
    // جلب الفاحصين من قاعدة البيانات
    $query = "SELECT 
                id,
                full_name,
                phone,
                email,
                specialization,
                center_id,
                region,
                experience_years,
                rating,
                status,
                current_load,
                max_load
              FROM inspectors 
              WHERE status = 'available' 
              AND current_load < max_load";
    
    $params = [];
    
    if ($centerId) {
        $query .= " AND center_id = :center_id";
        $params[':center_id'] = $centerId;
    }
    
    if ($region) {
        $query .= " AND region = :region";
        $params[':region'] = $region;
    }
    
    $query .= " ORDER BY rating DESC, current_load ASC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute($params);
    $inspectors = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'data' => $inspectors,
        'total' => count($inspectors)
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ], JSON_UNESCAPED_UNICODE);
}
?>