<?php

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

use App\Filament\Resources\TeacherResource;
use App\Models\Teacher;
use App\Models\User;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class CreateTeacher extends CreateRecord
{
    protected static string $resource = TeacherResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        // 生成教师ID
        $data['teacher_id'] = $this->generateTeacherId();

        return $data;
    }

    protected function handleRecordCreation(array $data): Teacher
    {
        DB::beginTransaction();

        try {
            // 创建用户记录
            $userData = [
                'user_id' => $data['teacher_id'],
                'username' => $data['user']['username'],  // 手机号作为登录名（必填）
                'password_hash' => $data['user']['password_hash'],
                'full_name' => $data['name'],
                'role' => 'teacher',
                'is_active' => 1,
            ];

            // 邮箱是可选的
            if (!empty($data['user']['email'])) {
                $userData['email'] = $data['user']['email'];
            }

            $user = User::create($userData);

            // 创建教师记录
            $teacherData = [
                'teacher_id' => $data['teacher_id'],
                'user_id' => $data['teacher_id'],
                'name' => $data['name'],
                'subject' => $data['subject'],
            ];

            $teacher = Teacher::create($teacherData);

            DB::commit();

            return $teacher;

        } catch (\Exception $e) {
            DB::rollBack();
            throw $e;
        }
    }

    protected function getRedirectUrl(): string
    {
        return $this->getResource()::getUrl('index');
    }

    protected function getCreatedNotificationTitle(): ?string
    {
        return '教师创建成功';
    }

    protected function getCreatedNotification(): ?\Filament\Notifications\Notification
    {
        return \Filament\Notifications\Notification::make()
            ->success()
            ->title('教师创建成功')
            ->body('教师信息已成功保存。');
    }

    protected function generateTeacherId(): string
    {
        $timestamp = time();
        $sequence = DB::table('teachers')
            ->where('teacher_id', 'like', "tch_{$timestamp}%")
            ->count() + 1;

        return "tch_{$timestamp}_{$sequence}";
    }

    public function getTitle(): string
    {
        return '添加教师';
    }

    public function getBreadcrumbs(): array
    {
        return [
            '#' => '师生管理',
            static::getResource()::getUrl('index') => '教师管理',
            static::getResource()::getUrl('create') => '添加教师',
        ];
    }
}