<?php
/**
 * API: جلب جميع الفاحصين مع بيانات المستخدم المرتبطة
 * GET /api/admin/endpoints/get_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";

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // جلب جميع الفاحصين مع ربط جدول users
    $query = "SELECT i.*, u.email as user_email, u.status as user_status 
              FROM inspectors i
              LEFT JOIN users u ON i.user_id = u.id
              ORDER BY i.id DESC";
    
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $inspectors = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // تنسيق البيانات
    $formattedInspectors = [];
    foreach ($inspectors as $insp) {
        $formatted = [];
        $formatted['id'] = $insp['id'] ?? null;
        $formatted['full_name'] = $insp['full_name'] ?? $insp['name'] ?? $insp['inspector_name'] ?? '-';
        $formatted['phone'] = $insp['phone'] ?? '-';
        $formatted['email'] = $insp['email'] ?? $insp['user_email'] ?? '-';
        $formatted['specialization'] = $insp['specialization'] ?? '-';
        $formatted['region'] = $insp['region'] ?? '-';
        $formatted['experience_years'] = $insp['experience_years'] ?? 0;
        $formatted['max_load'] = $insp['max_load'] ?? 5;
        $formatted['current_load'] = $insp['current_load'] ?? 0;
        $formatted['status'] = $insp['status'] ?? 'available';
        $formatted['rating'] = $insp['rating'] ?? 0;
        $formatted['center_id'] = $insp['center_id'] ?? null;
        $formatted['user_id'] = $insp['user_id'] ?? null;
        $formatted['created_at'] = $insp['created_at'] ?? null;
        $formattedInspectors[] = $formatted;
    }
    
    echo json_encode([
        'success' => true,
        'data' => $formattedInspectors,
        'total' => count($formattedInspectors)
    ], 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);
}
?>