<?php

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\Course;
use App\Models\Lesson;
use App\Models\LessonVideo;
use App\Models\Chapter;

class LessonController extends Controller
{	
	public function reorder(Request $request)
	{
		$ids = json_decode($request->order, true);

		if (!is_array($ids)) {
			return back()->with('error', 'Invalid order data.');
		}

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

		return back()->with('success', 'Lesson order updated.');
	}
	
	public function show($courseId, $chapterId, Lesson $lesson)
	{
		// later we’ll validate that the lesson belongs to this chapter & course
		return view('admin.lessons.show', compact('lesson', 'chapterId', 'courseId'));
	}
	
	public function store(Request $request)
	{
		$request->validate([
			'chapter_id' => 'required|exists:chapters,id',
			'title'      => 'required|string|max:255',
		]);

		$order = Lesson::where('chapter_id', $request->chapter_id)->max('order') + 1;

		Lesson::create([
			'chapter_id'  => $request->chapter_id,
			'title'       => $request->title,
			'slug'        => Str::slug($request->title),
			'description' => $request->description ?? null,
			'order'       => $order,
		]);

		return back()->with('success', 'Lesson added.');
	}

	public function destroy(Course $course, Chapter $chapter, Lesson $lesson)
	{
		$lesson->delete();

		return redirect()->route('admin.chapters.show', [
			'course'  => $course->slug,
			'chapter' => $chapter->slug,
		])->with('success', 'Lesson deleted.');
	}

	
}