<?php

namespace App\Filament\Resources\TeacherResource\Pages;
use Illuminate\Database\Eloquent\Builder;

use App\Filament\Resources\TeacherResource;
use App\Models\Teacher;
use Filament\Actions;
use Filament\Resources\Pages\ViewRecord;

class ViewTeacher extends ViewRecord
{
    protected static string $resource = TeacherResource::class;

    protected string $view = 'filament.resources.teacher.pages.view-teacher';

    public function getTitle(): string
    {
        return '教师详情 - ' . $this->record->name;
    }

    public function getBreadcrumbs(): array
    {
        return [
            static::getResource()::getUrl('index') => '教师管理',
            static::getResource()::getUrl('view', ['record' => $this->record]) => $this->record->name,
        ];
    }

    protected function getHeaderActions(): array
    {
        return [
            Actions\EditAction::make()
                ->label('编辑信息')
                ->icon('heroicon-o-pencil-square'),
            Actions\Action::make('viewStudents')
                ->label('查看学生')
                ->icon('heroicon-o-users')
                ->color('primary')
                ->url(fn (Teacher $record) => '/admin/students?tableFilters[teacher_id][value]=' . $record->teacher_id),
        ];
    }

    public function getViewData(): array
    {
        $teacher = $this->record;

        // 加载用户信息，使用正确的关联关系
        $user = \App\Models\User::where('id', $teacher->user_id)->first();
        $teacher->user = $user;

        // 加载学生数量
        $studentsCount = $teacher->students()->count();

        // 加载考试数量
        $examCount = \App\Models\Paper::where('teacher_id', $teacher->teacher_id)->count();

        return [
            'teacher' => $teacher,
            'studentsCount' => $studentsCount,
            'examCount' => $examCount,
        ];
    }
}