<?php

declare(strict_types=1);

namespace Kylin\Education\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Kylin\Education\Models\Student;

/**
 * 学生管理控制器
 *
 * 提供学生信息的增删改查及状态管理 API。
 */
class StudentController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Student::with('user');

        if ($request->filled('status')) {
            $query->where('status', $request->input('status'));
        }
        if ($request->filled('keyword')) {
            $query->whereHas('user', function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->input('keyword')}%")
                    ->orWhere('phone', 'like', "%{$request->input('keyword')}%");
            });
        }

        $students = $query->paginate($request->input('per_page', 15));

        return response()->json(['code' => 0, 'data' => $students]);
    }

    public function store(Request $request): JsonResponse
    {
        $rules = [
            'name' => 'required|string|max:100',
            'phone' => 'required|string|max:20|unique:users',
            'email' => 'nullable|email|unique:users',
            'password' => 'required|string|min:8',
            'birthday' => 'required|date',
            'gender' => 'required|in:male,female',
            'source' => 'nullable|string|max:20',
            'tags' => 'nullable|array',
        ];

        // 未成年人监护人信息
        $birthday = \Carbon\Carbon::parse($request->input('birthday'));
        if ($birthday->age < config('kylin-education.student.minor_age_threshold', 14)) {
            $rules['guardian_name'] = 'required|string|max:100';
            $rules['guardian_phone'] = 'required|string|max:20';
            $rules['guardian_relation'] = 'required|string|max:20';
            $rules['guardian_consent'] = 'required|accepted';
        }

        $validated = $request->validate($rules);

        // 创建用户
        $user = \App\Models\User::create([
            'name' => $validated['name'],
            'phone' => $validated['phone'],
            'email' => $validated['email'] ?? null,
            'password' => bcrypt($validated['password']),
            'role' => 'student',
        ]);

        // 创建学员
        $student = Student::create([
            'user_id' => $user->id,
            'student_no' => 'STU' . str_pad((string) (Student::count() + 1), 6, '0', STR_PAD_LEFT),
            'birthday' => $validated['birthday'],
            'gender' => $validated['gender'],
            'guardian_name' => $validated['guardian_name'] ?? null,
            'guardian_phone' => $validated['guardian_phone'] ?? null,
            'guardian_relation' => $validated['guardian_relation'] ?? null,
            'guardian_consent' => $validated['guardian_consent'] ?? false,
            'source' => $validated['source'] ?? null,
            'tags' => $validated['tags'] ?? null,
        ]);

        return response()->json(['code' => 0, 'data' => $student->load('user')], 201);
    }

    public function show(Student $student): JsonResponse
    {
        $student->load(['user', 'enrollments.course']);

        return response()->json(['code' => 0, 'data' => $student]);
    }

    public function update(Request $request, Student $student): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:100',
            'phone' => 'sometimes|string|max:20|unique:users,phone,' . $student->user_id,
            'email' => 'nullable|email|unique:users,email,' . $student->user_id,
            'birthday' => 'sometimes|date',
            'gender' => 'sometimes|in:male,female',
            'status' => 'sometimes|in:active,suspended,withdrawn,graduated',
            'tags' => 'nullable|array',
        ]);

        if (isset($validated['name']) || isset($validated['phone']) || isset($validated['email'])) {
            $student->user->update(array_only($validated, ['name', 'phone', 'email']));
        }

        $student->update(array_only($validated, ['birthday', 'gender', 'status', 'tags']));

        return response()->json(['code' => 0, 'data' => $student->fresh('user')]);
    }

    public function destroy(Student $student): JsonResponse
    {
        $student->delete();

        return response()->json(['code' => 0, 'message' => '删除成功']);
    }

    public function enroll(Request $request, Student $student): JsonResponse
    {
        $validated = $request->validate([
            'course_id' => 'required|exists:courses,id',
        ]);

        $student->enrollments()->create([
            'course_id' => $validated['course_id'],
            'enrolled_at' => now(),
        ]);

        return response()->json(['code' => 0, 'message' => '报名成功']);
    }

    public function withdraw(Request $request, Student $student): JsonResponse
    {
        $validated = $request->validate([
            'course_id' => 'required|exists:courses,id',
        ]);

        $student->enrollments()
            ->where('course_id', $validated['course_id'])
            ->delete();

        return response()->json(['code' => 0, 'message' => '退课成功']);
    }

    public function import(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|mimes:xlsx,xls',
        ]);

        // 异步导入
        // 实际项目中使用 Job 异步处理

        return response()->json(['code' => 0, 'message' => '导入任务已创建']);
    }

    public function export(Request $request): JsonResponse
    {
        // 导出逻辑
        return response()->json(['code' => 0, 'message' => '导出任务已创建']);
    }
}
