<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Student;
use App\Models\Teacher;
use Illuminate\Http\Request;

class KnowledgeMindmapController extends Controller
{
    public function getTeachers()
    {
        // For demonstration, return all teachers or a subset
        // In a real app, this might be filtered by the logged-in user's permissions
        $teachers = Teacher::query()
            ->select('id as teacher_id', 'name')
            ->limit(10)
            ->get();

        // If no teachers found, return some mock data for testing
        if ($teachers->isEmpty()) {
            return response()->json([
                ['teacher_id' => 1, 'name' => '张老师'],
                ['teacher_id' => 2, 'name' => '李老师'],
                ['teacher_id' => 3, 'name' => '王老师'],
            ]);
        }

        return response()->json($teachers);
    }

    public function getStudents($teacherId)
    {
        // Return students associated with the teacher
        // Mocking logic if no relationship exists in DB for this demo
        $students = Student::query()
            ->select('id as student_id', 'name')
            ->limit(20)
            ->get();

        if ($students->isEmpty()) {
             return response()->json([
                ['student_id' => 101, 'name' => '学生A'],
                ['student_id' => 102, 'name' => '学生B'],
                ['student_id' => 103, 'name' => '学生C'],
            ]);
        }
        
        return response()->json($students);
    }

    public function getMastery($studentId)
    {
        try {
            $service = app(\App\Services\LearningAnalyticsService::class);
            $response = $service->getStudentMasteryList($studentId);
            
            if (isset($response['error'])) {
                return response()->json([]);
            }

            // The service returns data in a 'data' key or directly as an array depending on the endpoint
            // Based on getStudentMastery implementation, it returns the full JSON response from the API
            // which likely contains a 'data' key.
            $data = $response['data'] ?? [];
            
            // Transform if necessary, but the view expects { kp_code: '...', mastery_level: ... }
            // The API response format should be verified, but assuming it matches what we need
            // or we map it here.
            
            // Let's ensure we return a list of { kp_code, mastery_level }
            return response()->json($data);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Failed to fetch mastery data for mindmap', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);
            return response()->json([]);
        }
    }
}
