<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ClassSessionVideo;
use App\Models\Course;
use App\Models\CourseOffering;
use Illuminate\Http\Request;

class ClassVideoController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'role:admin']);
    }

    /**
     * Display a listing of class videos.
     */
    public function index(Request $request)
    {
        $query = ClassSessionVideo::with(['course', 'instructor', 'courseOffering']);

        if ($request->has('search') && $request->search) {
            $search = $request->search;
            $query->where('title', 'like', "%{$search}%")
                  ->orWhereHas('course', function($q) use ($search) {
                      $q->where('name', 'like', "%{$search}%");
                  });
        }

        if ($request->has('course_id') && $request->course_id) {
            $query->where('course_id', $request->course_id);
        }

        $videos = $query->orderBy('session_date', 'desc')->paginate(20);
        $courses = Course::where('is_active', true)->orderBy('name')->get();

        return view('admin.class-videos.index', compact('videos', 'courses'));
    }

    /**
     * Show the form for creating a new class video.
     */
    public function create()
    {
        $courses = Course::where('is_active', true)->with('instructor')->orderBy('name')->get();
        $offerings = CourseOffering::where('status', '!=', 'cancelled')->orderBy('start_date', 'desc')->get();
        return view('admin.class-videos.create', compact('courses', 'offerings'));
    }

    /**
     * Store a newly created class video.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'course_id' => 'required|exists:courses,id',
            'course_offering_id' => 'nullable|exists:course_offerings,id',
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'session_date' => 'required|date',
            'mega_storage_link' => 'nullable|url',
            'download_key' => 'nullable|string',
            'video_duration' => 'nullable|string',
            'thumbnail_url' => 'nullable|url',
            'is_published' => 'nullable',
        ]);

        $course = Course::find($validated['course_id']);

        ClassSessionVideo::create([
            'course_id' => $validated['course_id'],
            'instructor_id' => $course->instructor_id,
            'course_offering_id' => $validated['course_offering_id'] ?? null,
            'title' => $validated['title'],
            'description' => $validated['description'] ?? null,
            'session_date' => $validated['session_date'],
            'mega_storage_link' => $validated['mega_storage_link'] ?? null,
            'download_key' => $validated['download_key'] ?? null,
            'video_duration' => $validated['video_duration'] ?? null,
            'thumbnail_url' => $validated['thumbnail_url'] ?? null,
            'is_published' => $request->has('is_published') && $request->is_published == '1',
        ]);

        return redirect()->route('admin.class-videos.index')
            ->with('success', 'Class video created successfully!');
    }

    /**
     * Display the specified class video.
     */
    public function show($id)
    {
        $video = ClassSessionVideo::with(['course', 'instructor', 'courseOffering'])->findOrFail($id);
        return view('admin.class-videos.show', compact('video'));
    }

    /**
     * Show the form for editing the specified class video.
     */
    public function edit($id)
    {
        $video = ClassSessionVideo::findOrFail($id);
        $courses = Course::where('is_active', true)->with('instructor')->orderBy('name')->get();
        $offerings = CourseOffering::where('status', '!=', 'cancelled')->orderBy('start_date', 'desc')->get();
        return view('admin.class-videos.edit', compact('video', 'courses', 'offerings'));
    }

    /**
     * Update the specified class video.
     */
    public function update(Request $request, $id)
    {
        $video = ClassSessionVideo::findOrFail($id);

        $validated = $request->validate([
            'course_id' => 'required|exists:courses,id',
            'course_offering_id' => 'nullable|exists:course_offerings,id',
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'session_date' => 'required|date',
            'mega_storage_link' => 'nullable|url',
            'download_key' => 'nullable|string',
            'video_duration' => 'nullable|string',
            'thumbnail_url' => 'nullable|url',
            'is_published' => 'nullable',
        ]);

        $updateData = $validated;
        $updateData['is_published'] = $request->has('is_published') && $request->is_published == '1';
        $video->update($updateData);

        return redirect()->route('admin.class-videos.index')
            ->with('success', 'Class video updated successfully!');
    }

    /**
     * Remove the specified class video.
     */
    public function destroy($id)
    {
        $video = ClassSessionVideo::findOrFail($id);
        $video->delete();

        return redirect()->route('admin.class-videos.index')
            ->with('success', 'Class video deleted successfully!');
    }
}

