<?php

namespace App\Http\Controllers\SelfPaced\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\SelfPaced\Course;
use App\Models\SelfPaced\CourseTopic;
use App\Models\SelfPaced\CourseSubTopic;
use App\Models\SelfPaced\CourseMedia;
use App\Models\SelfPaced\CourseDownload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MediaController extends Controller
{
    /** Max upload size: 500 MB in bytes */
    protected int $maxBytes = 524288000;

    public function __construct()
    {
        //
    }

    // =========================================================================
    // COURSE MEDIA (attached to a SubTopic)
    // =========================================================================

    public function index(Course $course, CourseTopic $topic, CourseSubTopic $subtopic)
    {
        $media = $subtopic->media()->orderBy('sort_order')->get();

        return view('self-paced.dashboard.media.index', compact('course', 'topic', 'subtopic', 'media'));
    }

    public function store(Request $request, Course $course, CourseTopic $topic, CourseSubTopic $subtopic)
    {
        $request->validate([
            'title'      => 'nullable|string|max:191',
            'type'       => 'required|in:video,image,pdf,presentation,excel',
            'media_file' => [
                'required',
                'file',
                "max:{$this->maxMbForValidation()}",
            ],
            'sort_order' => 'nullable|integer|min:0',
        ]);

        $file = $request->file('media_file');

        // Requirement 3.6: reject files > 500 MB
        if ($file->getSize() > $this->maxBytes) {
            return back()->withErrors(['media_file' => 'File exceeds the maximum allowed size of 500 MB.']);
        }

        $path = $file->store('self-paced/media', 'local');

        CourseMedia::create([
            'subtopic_id' => $subtopic->id,
            'title'       => $request->input('title') ?? $file->getClientOriginalName(),
            'type'        => $request->input('type'),
            'file_path'   => $path,
            'file_name'   => $file->getClientOriginalName(),
            'file_size'   => $file->getSize(),
            'mime_type'   => $file->getMimeType(),
            'sort_order'  => $request->input('sort_order', $subtopic->media()->max('sort_order') + 1),
        ]);

        return redirect()
            ->route('self-paced.dashboard.courses.topics.subtopics.show', [$course, $topic, $subtopic])
            ->with('success', 'Media file uploaded successfully.');
    }

    public function destroy(Course $course, CourseTopic $topic, CourseSubTopic $subtopic, CourseMedia $media)
    {
        if ($media->file_path && Storage::disk('local')->exists($media->file_path)) {
            Storage::disk('local')->delete($media->file_path);
        }

        $media->delete();

        if (request()->ajax()) {
            return response()->json(['success' => true, 'message' => 'Media deleted.']);
        }

        return redirect()
            ->route('self-paced.dashboard.courses.topics.subtopics.show', [$course, $topic, $subtopic])
            ->with('success', 'Media file deleted.');
    }

    /**
     * PATCH reorder media within a subtopic.
     */
    public function reorder(Request $request, Course $course, CourseTopic $topic, CourseSubTopic $subtopic)
    {
        $request->validate(['order' => 'required|array', 'order.*.id' => 'required|integer', 'order.*.sort_order' => 'required|integer']);

        foreach ($request->order as $item) {
            CourseMedia::where('id', $item['id'])->where('subtopic_id', $subtopic->id)
                ->update(['sort_order' => $item['sort_order']]);
        }

        return response()->json(['success' => true]);
    }

    // =========================================================================
    // COURSE DOWNLOADS (attached to a Course or Topic)
    // =========================================================================

    public function downloads(Course $course)
    {
        $courseDownloads = $course->downloads()->whereNull('topic_id')->get();
        $topics          = $course->topics()->with('downloads')->get();

        return view('self-paced.dashboard.media.downloads', compact('course', 'courseDownloads', 'topics'));
    }

    public function storeDownload(Request $request, Course $course)
    {
        $request->validate([
            'title'         => 'required|string|max:191',
            'topic_id'      => 'nullable|exists:self_paced_topics,id',
            'download_file' => [
                'required',
                'file',
                'mimes:pdf,xlsx,xls,doc,docx,zip,csv',
                "max:{$this->maxMbForValidation()}",
            ],
        ]);

        $file = $request->file('download_file');

        if ($file->getSize() > $this->maxBytes) {
            return back()->withErrors(['download_file' => 'File exceeds the maximum allowed size of 500 MB.']);
        }

        $path = $file->store('self-paced/downloads', 'local');

        CourseDownload::create([
            'course_id' => $course->id,
            'topic_id'  => $request->input('topic_id'),
            'title'     => $request->input('title'),
            'file_path' => $path,
            'file_name' => $file->getClientOriginalName(),
            'file_size' => $file->getSize(),
            'mime_type' => $file->getMimeType(),
        ]);

        return redirect()
            ->route('self-paced.dashboard.courses.downloads', $course)
            ->with('success', 'Download file uploaded successfully.');
    }

    public function destroyDownload(Course $course, CourseDownload $download)
    {
        if ($download->file_path && Storage::disk('local')->exists($download->file_path)) {
            Storage::disk('local')->delete($download->file_path);
        }

        $download->delete();

        if (request()->ajax()) {
            return response()->json(['success' => true, 'message' => 'Download deleted.']);
        }

        return redirect()
            ->route('self-paced.dashboard.courses.downloads', $course)
            ->with('success', 'Download file deleted.');
    }

    // =========================================================================
    // INLINE IMAGE UPLOAD (Quill editor — subtopic & exam question editors)
    // =========================================================================

    /**
     * Handle inline image uploads from the Quill rich-text editor.
     * Returns a JSON response with the image URL (Quill expects { location: '...' }).
     *
     * Requirements: self-paced media upload
     */
    public function uploadInlineImage(Request $request): \Illuminate\Http\JsonResponse
    {
        $request->validate(['file' => 'required|image|max:10240']); // 10 MB max

        try {
            $path = $request->file('file')->store('self-paced/inline-media', 'public');
            return response()->json(['location' => url(Storage::url($path))]);
        } catch (\Throwable $e) {
            return response()->json(['error' => 'Image upload failed. Please try again.'], 500);
        }
    }

    // =========================================================================
    // HELPERS
    // =========================================================================

    /** Convert 500 MB to KB for Laravel's max validation rule (which uses KB). */
    protected function maxMbForValidation(): int
    {
        return (int) ($this->maxBytes / 1024);
    }
}
