<?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 Illuminate\Http\Request;

class TopicController extends Controller
{
    public function __construct()
    {
        //
    }

    // =========================================================================
    // TOPICS
    // =========================================================================

    public function index(Request $request, Course $course)
    {
        $query = $course->topics()->withCount('subtopics');

        if ($search = $request->get('search')) {
            $query->where('title', 'like', "%{$search}%");
        }

        $topics = $query->orderBy('sort_order')->paginate(20)->withQueryString();

        if ($request->ajax()) {
            return response()->json([
                'html' => view('self-paced.dashboard.topics.partials.table', compact('topics', 'course'))->render(),
            ]);
        }

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

    public function create(Course $course)
    {
        return view('self-paced.dashboard.topics.create', compact('course'));
    }

    public function store(Request $request, Course $course)
    {
        $validated = $request->validate([
            'title'              => 'required|string|max:191',
            'description'        => 'nullable|string',
            'sort_order'         => 'nullable|integer|min:0',
            'is_published'       => 'nullable|boolean',
            'min_time_minutes'   => 'nullable|integer|min:0',
            'max_time_minutes'   => 'nullable|integer|min:0',
        ]);

        $validated['course_id']   = $course->id;
        $validated['sort_order']  = $validated['sort_order'] ?? ($course->topics()->max('sort_order') + 1);
        $validated['is_published'] = $request->boolean('is_published', true);

        // Convert minutes to seconds for storage
        if (isset($validated['min_time_minutes']) && $validated['min_time_minutes'] > 0) {
            $validated['min_time_seconds'] = $validated['min_time_minutes'] * 60;
        }
        if (isset($validated['max_time_minutes']) && $validated['max_time_minutes'] > 0) {
            $validated['max_time_seconds'] = $validated['max_time_minutes'] * 60;
        }
        unset($validated['min_time_minutes'], $validated['max_time_minutes']);

        $topic = CourseTopic::create($validated);

        return redirect()
            ->route('self-paced.dashboard.courses.topics.index', $course)
            ->with('success', "Topic \"{$topic->title}\" created successfully.");
    }

    public function show(Course $course, CourseTopic $topic)
    {
        $topic->load(['subtopics.media', 'downloads']);

        return view('self-paced.dashboard.topics.show', compact('course', 'topic'));
    }

    public function edit(Course $course, CourseTopic $topic)
    {
        return view('self-paced.dashboard.topics.edit', compact('course', 'topic'));
    }

    public function update(Request $request, Course $course, CourseTopic $topic)
    {
        $validated = $request->validate([
            'title'              => 'required|string|max:191',
            'description'        => 'nullable|string',
            'sort_order'         => 'nullable|integer|min:0',
            'is_published'       => 'nullable|boolean',
            'min_time_minutes'   => 'nullable|integer|min:0',
            'max_time_minutes'   => 'nullable|integer|min:0',
        ]);

        $validated['is_published'] = $request->boolean('is_published', true);

        // Convert minutes to seconds for storage
        if (isset($validated['min_time_minutes']) && $validated['min_time_minutes'] > 0) {
            $validated['min_time_seconds'] = $validated['min_time_minutes'] * 60;
        }
        if (isset($validated['max_time_minutes']) && $validated['max_time_minutes'] > 0) {
            $validated['max_time_seconds'] = $validated['max_time_minutes'] * 60;
        }
        unset($validated['min_time_minutes'], $validated['max_time_minutes']);

        $topic->update($validated);

        return redirect()
            ->route('self-paced.dashboard.courses.topics.index', $course)
            ->with('success', "Topic \"{$topic->title}\" updated successfully.");
    }

    public function destroy(Course $course, CourseTopic $topic)
    {
        $title = $topic->title;
        $topic->delete(); // cascades to subtopics and media via DB

        if (request()->ajax()) {
            return response()->json(['success' => true, 'message' => "Topic \"{$title}\" deleted."]);
        }

        return redirect()
            ->route('self-paced.dashboard.courses.topics.index', $course)
            ->with('success', "Topic \"{$title}\" and all its sub-topics deleted.");
    }

    /**
     * PATCH /self-paced/dashboard/courses/{course}/topics/reorder
     * Accepts: { order: [{ id: 1, sort_order: 0 }, ...] }
     */
    public function reorder(Request $request, Course $course)
    {
        $request->validate(['order' => 'required|array', 'order.*.id' => 'required|integer', 'order.*.sort_order' => 'required|integer']);

        foreach ($request->order as $item) {
            CourseTopic::where('id', $item['id'])->where('course_id', $course->id)
                ->update(['sort_order' => $item['sort_order']]);
        }

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

    // =========================================================================
    // SUB-TOPICS
    // =========================================================================

    public function createSubtopic(Course $course, CourseTopic $topic)
    {
        return view('self-paced.dashboard.subtopics.create', compact('course', 'topic'));
    }

    public function storeSubtopic(Request $request, Course $course, CourseTopic $topic)
    {
        $validated = $request->validate([
            'title'        => 'required|string|max:191',
            'content'      => 'nullable|string',
            'sort_order'   => 'nullable|integer|min:0',
            'is_published' => 'nullable|boolean',
        ]);

        $validated['topic_id']    = $topic->id;
        $validated['sort_order']  = $validated['sort_order'] ?? ($topic->subtopics()->max('sort_order') + 1);
        $validated['is_published'] = $request->boolean('is_published', true);

        $subtopic = CourseSubTopic::create($validated);

        return redirect()
            ->route('self-paced.dashboard.courses.topics.show', [$course, $topic])
            ->with('success', "Sub-topic \"{$subtopic->title}\" created successfully.");
    }

    public function showSubtopic(Course $course, CourseTopic $topic, CourseSubTopic $subtopic)
    {
        $subtopic->load('media');

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

    public function editSubtopic(Course $course, CourseTopic $topic, CourseSubTopic $subtopic)
    {
        return view('self-paced.dashboard.subtopics.edit', compact('course', 'topic', 'subtopic'));
    }

    public function updateSubtopic(Request $request, Course $course, CourseTopic $topic, CourseSubTopic $subtopic)
    {
        $validated = $request->validate([
            'title'        => 'required|string|max:191',
            'content'      => 'nullable|string',
            'sort_order'   => 'nullable|integer|min:0',
            'is_published' => 'nullable|boolean',
        ]);

        $validated['is_published'] = $request->boolean('is_published', true);
        $subtopic->update($validated);

        return redirect()
            ->route('self-paced.dashboard.courses.topics.show', [$course, $topic])
            ->with('success', "Sub-topic \"{$subtopic->title}\" updated successfully.");
    }

    public function destroySubtopic(Course $course, CourseTopic $topic, CourseSubTopic $subtopic)
    {
        $title = $subtopic->title;
        $subtopic->delete(); // cascades to media via DB

        if (request()->ajax()) {
            return response()->json(['success' => true, 'message' => "Sub-topic \"{$title}\" deleted."]);
        }

        return redirect()
            ->route('self-paced.dashboard.courses.topics.show', [$course, $topic])
            ->with('success', "Sub-topic \"{$title}\" deleted.");
    }

    /**
     * PATCH /self-paced/dashboard/courses/{course}/topics/{topic}/subtopics/reorder
     */
    public function reorderSubtopics(Request $request, Course $course, CourseTopic $topic)
    {
        $request->validate(['order' => 'required|array', 'order.*.id' => 'required|integer', 'order.*.sort_order' => 'required|integer']);

        foreach ($request->order as $item) {
            CourseSubTopic::where('id', $item['id'])->where('topic_id', $topic->id)
                ->update(['sort_order' => $item['sort_order']]);
        }

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