<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\ClassSessionVideo;
use App\Models\Enrollment;

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

    /**
     * Display a listing of class videos for enrolled courses.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $student = Auth::user();
        
        // Get enrolled course IDs
        $courseIds = Enrollment::where('student_id', $student->id)->pluck('course_id');
        
        // If no enrollments, return empty collection
        if ($courseIds->isEmpty()) {
            $videos = new \Illuminate\Pagination\LengthAwarePaginator([], 0, 20);
        } else {
            $query = ClassSessionVideo::whereIn('course_id', $courseIds)
                ->where('is_published', true)
                ->with(['course', 'courseOffering']);
            
            // Filter by course
            if ($request->has('course_id') && $request->course_id) {
                $query->where('course_id', $request->course_id);
            }
            
            $videos = $query->orderBy('session_date', 'desc')->paginate(20);
        }
        
        // Get courses for filter
        $courses = \App\Models\Course::whereIn('id', $courseIds)
            ->where('is_active', true)
            ->orderBy('name', 'asc')
            ->get();
        
        return view('student.videos.index', compact('videos', 'courses'));
    }

    /**
     * Extract Mega.nz file ID and key from URL.
     *
     * @param  string  $url
     * @return string|null
     */
    private function getMegaEmbedUrl($url)
    {
        if (!$url) {
            return null;
        }
        
        // Extract file ID and key from Mega URL
        // Format: https://mega.nz/file/gBFDlJZR#dAaaSszhqQd1N1Orldl8SiAkxh_W3uUNW-ADiY94wak
        // Embed format: https://mega.nz/embed/gBFDlJZR#dAaaSszhqQd1N1Orldl8SiAkxh_W3uUNW-ADiY94wak
        if (preg_match('/mega\.nz\/file\/([^#\s]+)(?:#(.+))?/', $url, $matches)) {
            $fileId = $matches[1];
            $key = isset($matches[2]) ? '#' . $matches[2] : '';
            return 'https://mega.nz/embed/' . $fileId . $key;
        }
        
        return null;
    }
    
    /**
     * Display the specified class video.
     *
     * @param  int  $id
     * @return \Illuminate\View\View
     */
    public function show($id)
    {
        $student = Auth::user();
        
        // Get enrolled course IDs
        $courseIds = Enrollment::where('student_id', $student->id)->pluck('course_id');
        
        // If no enrollments, return 404
        if ($courseIds->isEmpty()) {
            abort(404, 'You are not enrolled in any courses.');
        }
        
        $video = ClassSessionVideo::where('id', $id)
            ->whereIn('course_id', $courseIds)
            ->where('is_published', true)
            ->with(['course', 'courseOffering'])
            ->firstOrFail();
        
        // Get all videos from the same course for the sidebar
        $courseVideos = ClassSessionVideo::where('course_id', $video->course_id)
            ->where('is_published', true)
            ->whereIn('course_id', $courseIds)
            ->with(['course'])
            ->orderBy('session_date', 'asc')
            ->get();
        
        // Generate Mega embed URL if available
        $megaEmbedUrl = $this->getMegaEmbedUrl($video->mega_storage_link);
        
        // Generate embed URLs for all videos in the course
        $videosWithEmbeds = $courseVideos->map(function($v) {
            $v->embed_url = $this->getMegaEmbedUrl($v->mega_storage_link);
            return $v;
        });
        
        return view('student.videos.show', compact('video', 'megaEmbedUrl', 'videosWithEmbeds'));
    }
}

