<?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\ExamQuestion;
use App\Services\SelfPacedService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ExamController extends Controller
{
    public function __construct(protected SelfPacedService $selfPacedService)
    {
        //
    }

    // =========================================================================
    // QUESTION BANK — index across all courses
    // =========================================================================

    public function index(Request $request)
    {
        $query = ExamQuestion::with('course');

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

        if ($courseId = $request->get('course_id')) {
            $query->where('course_id', $courseId);
        }

        if ($request->has('is_active')) {
            $query->where('is_active', (bool) $request->get('is_active'));
        }

        $questions = $query->orderBy('course_id')->orderBy('sort_order')->paginate(20)->withQueryString();
        $courses   = Course::orderBy('title')->get(['id', 'title']);

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

        return view('self-paced.dashboard.exams.index', compact('questions', 'courses'));
    }

    // =========================================================================
    // QUESTIONS PER COURSE
    // =========================================================================

    public function courseQuestions(Request $request, Course $course)
    {
        $query = $course->examQuestions();

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

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

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

        return view('self-paced.dashboard.exams.course-questions', compact('course', 'questions'));
    }

    public function create(Course $course)
    {
        $topics = CourseTopic::where('course_id', $course->id)->ordered()->get();
        return view('self-paced.dashboard.exams.create', compact('course', 'topics'));
    }

    public function store(Request $request, Course $course)
    {
        $validated = $request->validate([
            'question_text'       => 'required|string',
            'question_text_html'  => 'nullable|string',
            'option_a'            => 'required|string',
            'option_b'            => 'required|string',
            'option_c'            => 'required|string',
            'option_d'            => 'required|string',
            'correct_answer'      => 'nullable|in:A,B,C,D',
            'correct_answers_json'=> 'nullable|array',
            'correct_answers_json.*' => 'in:A,B,C,D',
            'allow_multiple_answers' => 'nullable|boolean',
            'explanation'         => 'nullable|string',
            'sort_order'          => 'nullable|integer|min:0',
            'is_active'           => 'nullable|boolean',
            'upload_required'     => 'nullable|boolean',
            'upload_label'        => 'nullable|string|max:500',
            'question_media'      => 'nullable|file|max:524288',
            'topic_id'            => 'nullable|exists:self_paced_topics,id',
        ]);

        $validated['course_id']              = $course->id;
        $validated['sort_order']             = $validated['sort_order'] ?? ($course->examQuestions()->max('sort_order') + 1);
        $validated['is_active']              = $request->boolean('is_active', true);
        $validated['upload_required']        = $request->boolean('upload_required', false);
        $validated['allow_multiple_answers'] = $request->boolean('allow_multiple_answers', false);

        // For multi-answer, sort and store the correct answers array
        if ($validated['allow_multiple_answers']) {
            $answers = $validated['correct_answers_json'] ?? [];
            sort($answers);
            $validated['correct_answers_json'] = $answers;
            $validated['correct_answer']        = null; // not used for multi
        } else {
            $validated['correct_answers_json'] = null;
        }

        if ($request->hasFile('question_media')) {
            $file = $request->file('question_media');
            $validated['question_media_path'] = $file->store('self-paced/question-media', 'local');
            $validated['question_media_name'] = $file->getClientOriginalName();
            $validated['question_media_size'] = $file->getSize();
            $validated['question_media_type'] = $this->detectMediaType($file->getMimeType(), $file->getClientOriginalExtension());
        }

        ExamQuestion::create($validated);

        return redirect()
            ->route('self-paced.dashboard.exams.course-questions', $course)
            ->with('success', 'Exam question added successfully.');
    }

    public function edit(Course $course, ExamQuestion $question)
    {
        $topics = CourseTopic::where('course_id', $course->id)->ordered()->get();
        return view('self-paced.dashboard.exams.edit', compact('course', 'question', 'topics'));
    }

    public function update(Request $request, Course $course, ExamQuestion $question)
    {
        $validated = $request->validate([
            'question_text'          => 'required|string',
            'question_text_html'     => 'nullable|string',
            'option_a'               => 'required|string',
            'option_b'               => 'required|string',
            'option_c'               => 'required|string',
            'option_d'               => 'required|string',
            'correct_answer'         => 'nullable|in:A,B,C,D',
            'correct_answers_json'   => 'nullable|array',
            'correct_answers_json.*' => 'in:A,B,C,D',
            'allow_multiple_answers' => 'nullable|boolean',
            'explanation'            => 'nullable|string',
            'sort_order'             => 'nullable|integer|min:0',
            'is_active'              => 'nullable|boolean',
            'upload_required'        => 'nullable|boolean',
            'upload_label'           => 'nullable|string|max:500',
            'question_media'         => 'nullable|file|max:524288',
            'remove_media'           => 'nullable|boolean',
            'topic_id'               => 'nullable|exists:self_paced_topics,id',
        ]);

        $validated['is_active']              = $request->boolean('is_active', true);
        $validated['upload_required']        = $request->boolean('upload_required', false);
        $validated['allow_multiple_answers'] = $request->boolean('allow_multiple_answers', false);

        if ($validated['allow_multiple_answers']) {
            $answers = $validated['correct_answers_json'] ?? [];
            sort($answers);
            $validated['correct_answers_json'] = $answers;
            $validated['correct_answer']        = null;
        } else {
            $validated['correct_answers_json'] = null;
        }

        if ($request->boolean('remove_media') && $question->question_media_path) {
            \Illuminate\Support\Facades\Storage::disk('local')->delete($question->question_media_path);
            $validated['question_media_path'] = null;
            $validated['question_media_name'] = null;
            $validated['question_media_size'] = 0;
            $validated['question_media_type'] = null;
        }

        if ($request->hasFile('question_media')) {
            if ($question->question_media_path) {
                \Illuminate\Support\Facades\Storage::disk('local')->delete($question->question_media_path);
            }
            $file = $request->file('question_media');
            $validated['question_media_path'] = $file->store('self-paced/question-media', 'local');
            $validated['question_media_name'] = $file->getClientOriginalName();
            $validated['question_media_size'] = $file->getSize();
            $validated['question_media_type'] = $this->detectMediaType($file->getMimeType(), $file->getClientOriginalExtension());
        }

        $question->update($validated);

        return redirect()
            ->route('self-paced.dashboard.exams.course-questions', $course)
            ->with('success', 'Exam question updated successfully.');
    }

    public function destroy(Course $course, ExamQuestion $question)
    {
        $question->delete();

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

        return redirect()
            ->route('self-paced.dashboard.exams.course-questions', $course)
            ->with('success', 'Exam question deleted.');
    }

    // =========================================================================
    // EXAM SETTINGS (time limit, questions per attempt, max attempts, passing score)
    // =========================================================================

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

    public function updateSettings(Request $request, Course $course)
    {
        $validated = $request->validate([
            'exam_time_limit'            => 'required|integer|min:1',
            'exam_questions_per_attempt' => 'required|integer|min:1',
            'exam_attempts_allowed'      => 'required|integer|min:1',
            'passing_score'              => 'required|integer|min:1|max:100',
        ]);

        $this->selfPacedService->updateCourse($course, $validated, Auth::id());

        return redirect()
            ->route('self-paced.dashboard.exams.settings', $course)
            ->with('success', 'Exam settings updated successfully.');
    }

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

    protected function detectMediaType(string $mimeType, string $ext): string
    {
        $ext = strtolower($ext);
        if (str_starts_with($mimeType, 'video/') || in_array($ext, ['mp4', 'webm', 'ogg', 'mov', 'avi'])) return 'video';
        if (str_starts_with($mimeType, 'image/') || in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'])) return 'image';
        if ($mimeType === 'application/pdf' || $ext === 'pdf') return 'pdf';
        if (in_array($ext, ['ppt', 'pptx', 'odp'])) return 'presentation';
        if (in_array($ext, ['xls', 'xlsx', 'csv', 'ods'])) return 'excel';
        return 'pdf'; // fallback
    }

    // =========================================================================
    // BULK CSV IMPORT
    // =========================================================================

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

    public function import(Request $request, Course $course)
    {
        $request->validate([
            'csv_file' => 'required|file|mimes:csv,txt|max:2048',
        ]);

        $file    = $request->file('csv_file');
        $handle  = fopen($file->getRealPath(), 'r');
        $header  = fgetcsv($handle); // skip header row
        $count   = 0;
        $errors  = [];

        while (($row = fgetcsv($handle)) !== false) {
            if (count($row) < 6) {
                continue;
            }

            [$questionText, $optionA, $optionB, $optionC, $optionD, $correctAnswer, $explanation] = array_pad($row, 7, null);

            $correctAnswer = strtoupper(trim($correctAnswer ?? ''));

            if (!in_array($correctAnswer, ['A', 'B', 'C', 'D'])) {
                $errors[] = "Row skipped — invalid correct_answer: \"{$correctAnswer}\"";
                continue;
            }

            ExamQuestion::create([
                'course_id'      => $course->id,
                'question_text'  => trim($questionText),
                'option_a'       => trim($optionA),
                'option_b'       => trim($optionB),
                'option_c'       => trim($optionC),
                'option_d'       => trim($optionD),
                'correct_answer' => $correctAnswer,
                'explanation'    => $explanation ? trim($explanation) : null,
                'sort_order'     => $course->examQuestions()->max('sort_order') + 1,
                'is_active'      => true,
            ]);

            $count++;
        }

        fclose($handle);

        $message = "{$count} question(s) imported successfully.";
        if (!empty($errors)) {
            $message .= ' ' . count($errors) . ' row(s) skipped.';
        }

        return redirect()
            ->route('self-paced.dashboard.exams.course-questions', $course)
            ->with('success', $message);
    }
}
