<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Course;
use App\Models\Module;

class ModuleController extends Controller
{
    public function create()
    {
        $courses = Course::with(['subject', 'level'])->get();
        return view('admin.modules.create', compact('courses'));
    }

	public function store(Request $request)
	{
		$request->validate([
			'course_id' => 'required|exists:courses,id',
			'name'      => 'required|string|max:255',
		]);

		$course = Course::findOrFail($request->course_id);

		$course->modules()->create([
			'name'  => $request->name,
			'order' => $course->modules()->count() + 1,
		]);

		return redirect()
			->route('admin.courses.show', $course->slug)
			->with('success', 'Module added.');
	}
	
	public function reorder(Request $request)
{
    $ids = json_decode($request->order, true);

    foreach ($ids as $index => $id) {
        Module::where('id', $id)->update(['order' => $index + 1]);
    }

    return back()->with('success', 'Module order updated.');
}
}