<?php

namespace App\Http\Controllers\Instructor;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\ClassSessionVideo;
use App\Models\Course;
use App\Models\CourseOffering;

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

    /**
     * Display a listing of class videos for instructor's courses.
     *
     * @return \Illuminate\View\View
     */
    public function index(Request $request)
    {
        $instructor = Auth::user();
        
        // Get instructor's course IDs
        $courseIds = Course::where('instructor_id', $instructor->id)
            ->where('is_active', true)
            ->pluck('id');
        
        $query = ClassSessionVideo::whereIn('course_id', $courseIds)
            ->with(['course', 'courseOffering']);
        
        // Filter by course
        if ($request->has('course_id') && $request->course_id) {
            $query->where('course_id', $request->course_id);
        }
        
        // Filter by published status
        if ($request->has('published') && $request->published !== '') {
            $query->where('is_published', $request->published == '1');
        }
        
        $videos = $query->orderBy('session_date', 'desc')->paginate(20);
        
        // Get courses for filter dropdown
        $courses = Course::where('instructor_id', $instructor->id)
            ->where('is_active', true)
            ->orderBy('name', 'asc')
            ->get();
        
        return view('instructor.videos.index', compact('videos', 'courses'));
    }

    /**
     * Show the form for creating a new class video.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        $instructor = Auth::user();
        
        $courses = Course::where('instructor_id', $instructor->id)
            ->where('is_active', true)
            ->with('courseOfferings')
            ->orderBy('name', 'asc')
            ->get();
        
        return view('instructor.videos.create', compact('courses'));
    }

    /**
     * Store a newly created class video.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        try {
            $instructor = Auth::user();
            
            // Verify the course belongs to this instructor
            $course = Course::where('id', $request->course_id)
                ->where('instructor_id', $instructor->id)
                ->firstOrFail();
            
            // Prepare validation rules
            $rules = [
                'course_id' => 'required|exists:courses,id',
                'title' => 'required|string|max:255',
                'description' => 'nullable|string',
                'session_date' => 'required|date',
                'download_key' => 'nullable|string',
                'video_duration' => 'nullable|date_format:H:i',
                'is_published' => 'boolean',
            ];
            
            // Only validate URLs if they're provided
            if ($request->filled('mega_storage_link')) {
                $rules['mega_storage_link'] = 'url';
            } else {
                $rules['mega_storage_link'] = 'nullable';
            }
            
            if ($request->filled('thumbnail_url')) {
                $rules['thumbnail_url'] = 'url';
            } else {
                $rules['thumbnail_url'] = 'nullable';
            }
            
            // Only validate course_offering_id if it's provided
            if ($request->filled('course_offering_id')) {
                $rules['course_offering_id'] = 'exists:course_offerings,id';
            }
            
            $validated = $request->validate($rules, [
                'course_id.required' => 'Please select a course.',
                'course_id.exists' => 'Selected course does not exist.',
                'title.required' => 'Video title is required.',
                'session_date.required' => 'Session date is required.',
                'session_date.date' => 'Please enter a valid date.',
                'mega_storage_link.url' => 'Mega storage link must be a valid URL.',
                'thumbnail_url.url' => 'Thumbnail URL must be a valid URL.',
                'video_duration.date_format' => 'Video duration must be in HH:MM format.',
                'course_offering_id.exists' => 'Selected course offering does not exist.',
            ]);
            
            // Verify course offering belongs to the course if provided
            if ($request->filled('course_offering_id')) {
                $offering = CourseOffering::where('id', $validated['course_offering_id'])
                    ->where('course_id', $validated['course_id'])
                    ->firstOrFail();
            }
            
            // Handle video_duration - convert H:i to H:i:s format for database
            $videoDuration = null;
            if (!empty($validated['video_duration'])) {
                // If format is H:i, convert to H:i:s
                if (preg_match('/^\d{2}:\d{2}$/', $validated['video_duration'])) {
                    $videoDuration = $validated['video_duration'] . ':00';
                } else {
                    $videoDuration = $validated['video_duration'];
                }
            }
            
            // Ensure instructor_id is set - this is required by the database
            if (empty($instructor->id)) {
                throw new \Exception('Instructor ID is missing. Please ensure you are logged in.');
            }
            
            // Create video using the SAME pattern as the working API implementation
            // This directly matches app/Http/Controllers/Api/V1/Instructor/VideoController.php:148-159
            $videoData = [
                'course_id' => $validated['course_id'],
                'instructor_id' => $instructor->id, // REQUIRED: Direct assignment - same as API
                'course_offering_id' => $request->filled('course_offering_id') ? $validated['course_offering_id'] : null,
                'title' => $validated['title'],
                'description' => !empty($validated['description']) ? $validated['description'] : null,
                'session_date' => $validated['session_date'],
                'mega_storage_link' => !empty($validated['mega_storage_link']) ? $validated['mega_storage_link'] : null,
                'download_key' => !empty($validated['download_key']) ? $validated['download_key'] : null,
                'video_duration' => $videoDuration,
                'thumbnail_url' => !empty($validated['thumbnail_url']) ? $validated['thumbnail_url'] : null,
                'is_published' => $request->has('is_published'),
                'views_count' => 0,
            ];
            
            // Log the data being inserted for debugging (remove in production if needed)
            Log::debug('Creating video with data:', ['instructor_id' => $videoData['instructor_id'], 'course_id' => $videoData['course_id']]);
            
            $video = ClassSessionVideo::create($videoData);
            
            return redirect()->route('instructor.videos.index')
                ->with('success', 'Class video created successfully!');
                
        } catch (\Illuminate\Validation\ValidationException $e) {
            return redirect()->back()
                ->withInput()
                ->withErrors($e->errors());
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return redirect()->back()
                ->withInput()
                ->withErrors(['error' => 'Course or course offering not found.']);
        } catch (\Exception $e) {
            \Log::error('Video creation error: ' . $e->getMessage(), [
                'instructor_id' => Auth::id(),
                'exception' => $e
            ]);
            
            return redirect()->back()
                ->withInput()
                ->withErrors(['error' => 'An error occurred while creating the video. Please try again.']);
        }
    }

    /**
     * Display the specified class video.
     *
     * @param  int  $video
     * @return \Illuminate\View\View
     */
    public function show($video)
    {
        $instructor = Auth::user();
        
        // Handle both route model binding and ID parameter
        $videoId = is_object($video) ? $video->id : $video;
        
        $video = ClassSessionVideo::where('id', $videoId)
            ->whereHas('course', function($q) use ($instructor) {
                $q->where('instructor_id', $instructor->id);
            })
            ->with(['course', 'courseOffering'])
            ->firstOrFail();
        
        return view('instructor.videos.show', compact('video'));
    }

    /**
     * Show the form for editing the specified class video.
     *
     * @param  int  $video
     * @return \Illuminate\View\View
     */
    public function edit($video)
    {
        $instructor = Auth::user();
        
        // Handle both route model binding and ID parameter
        $videoId = is_object($video) ? $video->id : $video;
        
        $video = ClassSessionVideo::where('id', $videoId)
            ->whereHas('course', function($q) use ($instructor) {
                $q->where('instructor_id', $instructor->id);
            })
            ->with(['course', 'courseOffering'])
            ->firstOrFail();
        
        $courses = Course::where('instructor_id', $instructor->id)
            ->where('is_active', true)
            ->with('courseOfferings')
            ->orderBy('name', 'asc')
            ->get();
        
        return view('instructor.videos.edit', compact('video', 'courses'));
    }

    /**
     * Update the specified class video.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $video
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request, $video)
    {
        $instructor = Auth::user();
        
        // Handle both route model binding and ID parameter
        $videoId = is_object($video) ? $video->id : $video;
        
        $video = ClassSessionVideo::where('id', $videoId)
            ->whereHas('course', function($q) use ($instructor) {
                $q->where('instructor_id', $instructor->id);
            })
            ->firstOrFail();
        
        $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|date_format:H:i',
            'thumbnail_url' => 'nullable|url',
            'is_published' => 'boolean',
        ]);
        
        // Verify the course belongs to this instructor
        $course = Course::where('id', $validated['course_id'])
            ->where('instructor_id', $instructor->id)
            ->firstOrFail();
        
        // Verify course offering belongs to the course if provided
        if (!empty($validated['course_offering_id'])) {
            $offering = CourseOffering::where('id', $validated['course_offering_id'])
                ->where('course_id', $validated['course_id'])
                ->firstOrFail();
        } else {
            $validated['course_offering_id'] = null;
        }
        
        // Ensure instructor_id is preserved (should not be changed)
        $validated['instructor_id'] = $instructor->id;
        
        // Handle video_duration - convert H:i to H:i:s format for database
        if (!empty($validated['video_duration'])) {
            // If format is H:i, convert to H:i:s
            if (preg_match('/^\d{2}:\d{2}$/', $validated['video_duration'])) {
                $validated['video_duration'] = $validated['video_duration'] . ':00';
            }
        } else {
            $validated['video_duration'] = null;
        }
        
        $validated['is_published'] = $request->has('is_published');
        
        $video->update($validated);
        
        return redirect()->route('instructor.videos.show', $video->id)
            ->with('success', 'Class video updated successfully!');
    }

    /**
     * Remove the specified class video.
     *
     * @param  int  $video
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy($video)
    {
        $instructor = Auth::user();
        
        // Handle both route model binding and ID parameter
        $videoId = is_object($video) ? $video->id : $video;
        
        $video = ClassSessionVideo::where('id', $videoId)
            ->whereHas('course', function($q) use ($instructor) {
                $q->where('instructor_id', $instructor->id);
            })
            ->firstOrFail();
        
        $video->delete();
        
        return redirect()->route('instructor.videos.index')
            ->with('success', 'Class video deleted successfully!');
    }
}

