<?php

namespace App\Daylight\Http\Controllers\Content;

use App\Daylight\Http\Requests\Content\QuestionCategories\StoreQuestionCategoryRequest;
use App\Daylight\Http\Requests\Content\QuestionCategories\UpdateQuestionCategoryRequest;
use App\Http\Controllers\Controller;
use App\Models\QuestionCategory;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class QuestionCategoryController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:create:pages', only: ['create', 'store']),
            new Middleware('can:read:pages', only: ['index', 'show']),
            new Middleware('can:update:pages', only: ['edit', 'update']),
            new Middleware('can:delete:pages', only: ['destroy']),
        ];
    }

    public function index()
    {
        return view('daylight.content.question-categories.index');

    }

    public function create()
    {
        return view('daylight.content.question-categories.create');
    }

    public function store(StoreQuestionCategoryRequest $request)
    {
        $questionCategory = QuestionCategory::create();

        $questionCategory->translations()->create([
            'locale' => $request->input('locale'),
            'name' => $request->input('name'),
        ]);

        return redirect()
            ->route('daylight.content.question-categories.edit', [
                'question_category' => $questionCategory,
                'locale' => $request->get('locale'),
            ])
            ->with('success', __('Question category created'));
    }

    public function edit(QuestionCategory $questionCategory)
    {
        $questionCategory->load([
            'translations' => function ($query) {
                $query->where('locale', request()->get('locale', app()->getLocale()));
            },
        ]);

        return view('daylight.content.question-categories.edit', [
            'questionCategory' => $questionCategory,
        ]);
    }

    public function update(UpdateQuestionCategoryRequest $request, QuestionCategory $questionCategory)
    {
        $questionCategory->translations()->updateOrCreate(
            [
                'locale' => $request->input('locale'),
            ],
            [
                'name' => $request->input('name'),
            ],
        );

        return redirect()
            ->route('daylight.content.question-categories.edit', [
                'question_category' => $questionCategory,
                'locale' => $request->get('locale'),
            ])
            ->with('success', __('Question category updated'));
    }

    public function destroy(QuestionCategory $questionCategory)
    {
        $questionCategory->delete();

        return redirect()
            ->route('daylight.content.question-categories.index')
            ->with('success', __('Question category deleted'));
    }
}
