<?php

namespace App\Http\Controllers\Api\V1\Student;

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\ClassSessionVideo;
use App\Models\Enrollment;

class VideoController extends BaseController
{
    /**
     * Get list of videos for enrolled courses.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        try {
            $user = Auth::user();
            
            // Get enrolled course IDs
            $courseIds = Enrollment::where('student_id', $user->id)->pluck('course_id');
            
            // Log for debugging
            if ($courseIds->isEmpty()) {
                Log::info('Student has no enrolled courses', ['student_id' => $user->id]);
                return $this->paginated([], new \Illuminate\Pagination\LengthAwarePaginator([], 0, 20));
            }
            
            $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($request->get('per_page', 20));
            
            $data = $videos->map(function($video) {
                return [
                    'id' => $video->id,
                    'title' => $video->title,
                    'description' => $video->description,
                    'mega_storage_link' => $video->mega_storage_link,
                    'mega_embed_url' => $this->getMegaEmbedUrl($video->mega_storage_link),
                    'download_key' => $video->download_key,
                    'thumbnail_url' => $video->thumbnail_url,
                    'session_date' => $video->session_date ? $video->session_date->format('Y-m-d') : null,
                    'video_duration' => $video->video_duration ? date('H:i:s', strtotime($video->video_duration)) : null,
                    'is_published' => $video->is_published,
                    'views_count' => $video->views_count ?? 0,
                    'course' => [
                        'id' => $video->course->id ?? null,
                        'name' => $video->course->name ?? 'N/A',
                        'code' => $video->course->code ?? null,
                    ],
                    'course_offering' => $video->courseOffering ? [
                        'id' => $video->courseOffering->id,
                        'name' => $video->courseOffering->name,
                    ] : null,
                    'created_at' => $video->created_at ? $video->created_at->toISOString() : null,
                    'updated_at' => $video->updated_at ? $video->updated_at->toISOString() : null,
                ];
            });
            
            return $this->paginated($data, $videos);
        } catch (\Exception $e) {
            Log::error('Student Videos API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching videos.', null, 500);
        }
    }
    
    /**
     * Get video details.
     *
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        try {
            $user = Auth::user();
            
            // Get enrolled course IDs
            $courseIds = Enrollment::where('student_id', $user->id)->pluck('course_id');
            
            // If no enrollments, return error
            if ($courseIds->isEmpty()) {
                return $this->error('You are not enrolled in any courses.', null, 403);
            }
            
            $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 navigation
            $courseVideos = ClassSessionVideo::where('course_id', $video->course_id)
                ->where('is_published', true)
                ->whereIn('course_id', $courseIds)
                ->with(['course'])
                ->orderBy('session_date', 'asc')
                ->get()
                ->map(function($v) {
                    return [
                        'id' => $v->id,
                        'title' => $v->title,
                        'session_date' => $v->session_date ? $v->session_date->format('Y-m-d') : null,
                    ];
                });
            
            return $this->success([
                'id' => $video->id,
                'title' => $video->title,
                'description' => $video->description,
                'mega_storage_link' => $video->mega_storage_link,
                'mega_embed_url' => $this->getMegaEmbedUrl($video->mega_storage_link),
                'download_key' => $video->download_key,
                'thumbnail_url' => $video->thumbnail_url,
                'session_date' => $video->session_date ? $video->session_date->format('Y-m-d') : null,
                'video_duration' => $video->video_duration ? date('H:i:s', strtotime($video->video_duration)) : null,
                'is_published' => $video->is_published,
                'views_count' => $video->views_count ?? 0,
                'course' => [
                    'id' => $video->course->id ?? null,
                    'name' => $video->course->name ?? 'N/A',
                    'code' => $video->course->code ?? null,
                ],
                'course_offering' => $video->courseOffering ? [
                    'id' => $video->courseOffering->id,
                    'name' => $video->courseOffering->name,
                ] : null,
                'course_videos' => $courseVideos,
                'created_at' => $video->created_at ? $video->created_at->toISOString() : null,
                'updated_at' => $video->updated_at ? $video->updated_at->toISOString() : null,
            ]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return $this->error('Video not found.', null, 404);
        } catch (\Exception $e) {
            Log::error('Student Video API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching video details.', null, 500);
        }
    }
    
    /**
     * Extract Mega.nz file ID and key from URL and generate embed URL.
     *
     * @param  string|null  $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;
    }
}

