<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\LessonVideo;

class LessonVideoController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'lesson_id' => 'required|exists:lessons,id',
            'title'     => 'required|max:255',
            'video_url' => 'required|url',
        ]);

        $maxOrder = LessonVideo::where('lesson_id', $request->lesson_id)->max('order');
        $nextOrder = $maxOrder ? $maxOrder + 1 : 1;

        LessonVideo::create([
            'lesson_id' => $request->lesson_id,
            'title'     => $request->title,
            'video_url' => $request->video_url,
            'order'     => $nextOrder,
        ]);

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

    public function reorder(Request $request)
    {
        $request->validate([
            'order' => 'required|string',
        ]);

        $ids = json_decode($request->order, true);

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

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

    public function destroy(LessonVideo $video)
    {
        $video->delete();
        return back()->with('success', 'Video removed.');
    }
}