<?php

namespace App\Http\Controllers\Admin\Quiz;

use App\Exceptions\CustomWebException;
use App\Http\Controllers\Controller;
use App\Models\Level;
use App\Models\QuestionLevel;
use App\Models\Quiz;
use App\Services\ModalIndexQuey;
use Illuminate\Http\Request;

class QuestionLevelController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Quiz $quiz)
    {
        adminUserHasPermission(permission: 'read');

        $modalKeys = [
            'create' => 'question_level_create_modal',
            'edit' => 'question_level_edit_modal',
        ];

        $buttons = [
            [
                'label' => __('Back'),
                'icon' => 'ph ph-arrow-clockwise',
                'type' => 'link',
                'link' => route('admin.quizzes.index'),
            ],
            [
                'label' => __('Create New level'),
                'icon' => 'ph ph-plus-bold',
                'type' => 'modal',
                'id' => $modalKeys['create'],
                'href' => route('admin.quizzes.question-levels.store', $quiz),
            ],
        ];

        $questionLevels = ModalIndexQuey::get(model: $quiz->questionLevels(), with: ['level:id,title,slug']);

        $columns = [
            [
                'label' => __('label'),
                'key' => 'level.title',
                'header_class' => 'lg:w-[350px]',
            ],
            [
                'label' => __('Action'),
                'render' => function ($level) use ($quiz) {
                    $action_buttons = [
                        [
                            'label' => __('Questions'),
                            'icon' => 'ph ph-list',
                            'type' => 'link',
                            'href' => route('admin.quizzes.questions.index', ['quiz' => $quiz->id, 'label' => $level->level->slug]),
                        ],
                        [
                            'label' => __('Edit'),
                            'icon' => 'ph ph-pencil',
                            'type' => 'modal',
                            'id' => 'question_level_edit_modal',
                            'row' => $level,
                            'href' => route('admin.quizzes.question-levels.update', ['quiz' => $quiz->id, 'question_level' => $level->id]),
                        ],
                        [
                            'label' => __('Delete'),
                            'icon' => 'ph ph-trash',
                            'type' => 'delete',
                            'href' => route('admin.quizzes.question-levels.destroy', ['quiz' => $quiz->id, 'question_level' => $level->id]),
                        ],
                    ];

                    return view('admin.components.table-action', compact('action_buttons'))->render();
                },
            ],
        ];

        $levels = Level::select('id', 'title', 'slug')->get();

        return view('admin.pages.quiz.question-level.index', compact('questionLevels', 'columns', 'buttons', 'quiz', 'levels', 'modalKeys'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request, Quiz $quiz)
    {
        adminUserHasPermission(permission: 'create');

        $validated = $request->validate([
            'level_id' => 'required|exists:levels,id',
        ]);

        if ($quiz->levels()->where('level_id', $validated['level_id'])->exists()) {
            throw new CustomWebException(__('level already exists'));
        }

        $quiz->levels()->attach($validated['level_id']);

        return response()->json([
            'message' => __('Question level successfully created'),
            'redirect' => route('admin.quizzes.question-levels.index', ['quiz' => $quiz->id, 'label' => $validated['level_id']]),
        ]);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Quiz $quiz, QuestionLevel $questionLevel)
    {
        adminUserHasPermission(permission: 'edit');

        $validated = $request->validate([
            'level_id' => 'required|exists:levels,id',
        ]);

        $exits = $quiz->questionLevels()
            ->where('id', '!=', $questionLevel->id)
            ->where('level_id', $validated['level_id'])
            ->exists();

        if ($exits) {
            throw new CustomWebException(__('level already exists'));
        }

        if ($questionLevel->quiz_id !== $quiz->id) {
            throw new CustomWebException(__('Unauthorized action'));
        }

        $quiz->levels()->sync($validated['level_id']);

        return response()->json([
            'message' => __('Question level was successfully updated'),
            'reload' => true,
        ]);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Quiz $quiz, QuestionLevel $questionLevel)
    {
        adminUserHasPermission(permission: 'delete');

        if ($questionLevel->quiz_id !== $quiz->id) {
            throw new CustomWebException(__('Unauthorized action'));
        }

        $quiz->levels()->detach($questionLevel->level_id);

        return response()->json([
            'message' => __('Question level deleted successfully'),
            'reload' => true,
        ]);
    }
}
