<?php
/**
 * API: جلب أداء الفاحصين للمشرف
 * GET /api/supervisor/get_inspector_performance.php?supervisor_id=1
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

$host = "localhost";
$dbname = "digitals_autotester_db";
$username = "digitals";
$password = "bassam.bassam";

$supervisor_id = isset($_GET['supervisor_id']) ? intval($_GET['supervisor_id']) : 0;

if (!$supervisor_id) {
    echo json_encode(['success' => false, 'message' => 'supervisor_id مطلوب']);
    exit();
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // جلب الفاحصين التابعين للمشرف
    $inspStmt = $pdo->prepare("
        SELECT i.id, u.full_name 
        FROM supervisor_inspectors si
        JOIN inspectors i ON si.inspector_id = i.id
        JOIN users u ON i.user_id = u.id
        WHERE si.supervisor_id = ?
    ");
    $inspStmt->execute([$supervisor_id]);
    $inspectors = $inspStmt->fetchAll(PDO::FETCH_ASSOC);
    
    $inspectorIds = array_column($inspectors, 'id');
    $performance = [];
    
    if (!empty($inspectorIds)) {
        $placeholders = implode(',', array_fill(0, count($inspectorIds), '?'));
        
        // جلب عدد الفحوصات لكل فاحص من جدول inspection_requests_new
        // (بافتراض وجود عمود inspector_id في الجدول)
        $stmt = $pdo->prepare("
            SELECT inspector_id, COUNT(*) as inspections
            FROM inspection_requests_new 
            WHERE inspector_id IN ($placeholders)
            GROUP BY inspector_id
        ");
        $stmt->execute($inspectorIds);
        $counts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        $countMap = [];
        foreach ($counts as $c) {
            $countMap[$c['inspector_id']] = $c['inspections'];
        }
        
        foreach ($inspectors as $insp) {
            $performance[] = [
                'id' => $insp['id'],
                'name' => $insp['full_name'],
                'inspections' => $countMap[$insp['id']] ?? 0
            ];
        }
    }
    
    echo json_encode([
        'success' => true,
        'data' => $performance
    ], JSON_UNESCAPED_UNICODE);
    
} catch(PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>