<?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\Schedule;

/**
 * 课表控制器
 */
class ScheduleController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Schedule::with(['course', 'teacher', 'classroom']);

        if ($request->filled('teacher_id')) {
            $query->where('teacher_id', $request->input('teacher_id'));
        }
        if ($request->filled('classroom_id')) {
            $query->where('classroom_id', $request->input('classroom_id'));
        }
        if ($request->filled('day_of_week')) {
            $query->where('day_of_week', $request->input('day_of_week'));
        }

        $schedules = $query->paginate($request->input('per_page', 50));

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

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'course_id' => 'required|exists:courses,id',
            'teacher_id' => 'required|exists:users,id',
            'classroom_id' => 'required|exists:classrooms,id',
            'day_of_week' => 'required|integer|min:1|max:7',
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i|after:start_time',
            'effective_date' => 'required|date',
            'expiry_date' => 'nullable|date|after:effective_date',
        ]);

        // 冲突检测
        $conflicts = $this->detectConflicts($validated);
        if (!empty($conflicts)) {
            return response()->json([
                'code' => 1,
                'message' => '存在排课冲突',
                'data' => $conflicts,
            ], 422);
        }

        $schedule = Schedule::create($validated);

        return response()->json(['code' => 0, 'data' => $schedule->load(['course', 'teacher', 'classroom'])], 201);
    }

    public function update(Request $request, Schedule $schedule): JsonResponse
    {
        $validated = $request->validate([
            'course_id' => 'sometimes|exists:courses,id',
            'teacher_id' => 'sometimes|exists:users,id',
            'classroom_id' => 'sometimes|exists:classrooms,id',
            'day_of_week' => 'sometimes|integer|min:1|max:7',
            'start_time' => 'sometimes|date_format:H:i',
            'end_time' => 'sometimes|date_format:H:i|after:start_time',
            'effective_date' => 'sometimes|date',
            'expiry_date' => 'nullable|date|after:effective_date',
        ]);

        $schedule->update($validated);

        return response()->json(['code' => 0, 'data' => $schedule->fresh(['course', 'teacher', 'classroom'])]);
    }

    public function destroy(Schedule $schedule): JsonResponse
    {
        $schedule->update(['status' => 'cancelled']);

        return response()->json(['code' => 0, 'message' => '排课已取消']);
    }

    public function autoSchedule(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'course_ids' => 'required|array',
            'course_ids.*' => 'exists:courses,id',
            'start_date' => 'required|date',
        ]);

        // 自动排课算法（约束满足）
        // 实际项目中实现完整的排课算法

        return response()->json(['code' => 0, 'message' => '自动排课完成']);
    }

    public function checkConflicts(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'teacher_id' => 'nullable|exists:users,id',
            'classroom_id' => 'nullable|exists:classrooms,id',
            'day_of_week' => 'required|integer|min:1|max:7',
            'start_time' => 'required|date_format:H:i',
            'end_time' => 'required|date_format:H:i',
        ]);

        $conflicts = $this->detectConflicts($validated);

        return response()->json(['code' => 0, 'data' => ['has_conflict' => !empty($conflicts), 'conflicts' => $conflicts]]);
    }

    private function detectConflicts(array $data): array
    {
        $conflicts = [];

        // 教师时间冲突
        if (!empty($data['teacher_id'])) {
            $teacherConflict = Schedule::where('teacher_id', $data['teacher_id'])
                ->where('day_of_week', $data['day_of_week'])
                ->where('status', 'active')
                ->where('start_time', '<', $data['end_time'])
                ->where('end_time', '>', $data['start_time'])
                ->exists();

            if ($teacherConflict) {
                $conflicts[] = ['type' => 'teacher', 'message' => '教师时间冲突'];
            }
        }

        // 教室时间冲突
        if (!empty($data['classroom_id'])) {
            $classroomConflict = Schedule::where('classroom_id', $data['classroom_id'])
                ->where('day_of_week', $data['day_of_week'])
                ->where('status', 'active')
                ->where('start_time', '<', $data['end_time'])
                ->where('end_time', '>', $data['start_time'])
                ->exists();

            if ($classroomConflict) {
                $conflicts[] = ['type' => 'classroom', 'message' => '教室时间冲突'];
            }
        }

        return $conflicts;
    }
}
