<?php

namespace App\Http\Controllers;

use App\Models\Post;
use App\Models\QuestionCategory;
use Daylight\Core\Models\Translations\PageTranslation;
use Daylight\Core\Modules\Multilingualism\Entities\LocalizedRoute;
use Daylight\Core\Modules\Multilingualism\Multilingualism;
use Daylight\Core\Settings\General;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\View\View;

class PageController extends Controller
{
    public function __invoke(?string $slug = null): View
    {
        if (in_array($slug, Multilingualism::getAvailableLocales()->toArray())) {
            $slug = null;
        }

        $page = PageTranslation::query()
            ->whereLocale(app()->getLocale())
            ->when(is_null($slug), function (Builder $query) {
                $query->whereHas('page', function ($query) {
                    return $query->where('id', app(General::class)->frontPage);
                });
            })
            ->when(! is_null($slug), function ($query) use ($slug) {
                return $query->where('slug', $slug);
            })
            ->with([
                'page.translations',
                'page.defaultTranslation',
                'components.media',
                'components.relatables.relatable',
                'components.products.variants',
                'components.products.translations' => function ($query) {
                    $query->where('locale', app()->getLocale());
                },
                'components.testimonials.translations' => function ($query) {
                    $query->where('locale', app()->getLocale());
                },
                'components.questionCategories.translations' => function ($query) {
                    $query->where('locale', app()->getLocale());
                },
                'components.questionCategories.questions.translations' => function ($query) {
                    $query->where('locale', app()->getLocale());
                },
                'components.products.labels.translations' => function ($query) {
                    $query->where('locale', app()->getLocale());
                },
            ])
            ->firstOrFail();

        $localizedRoute = LocalizedRoute::create()
            ->setRoute('page', $page->slug)
            ->setDefaultTranslation($page->page->defaultTranslation)
            ->setTranslations($page->page->translations);

        if ($page->page->template && $page->page->template !== 'default') {
            return view('pages.'.$page->page->template, [
                'page' => $page,
                'templateContent' => $this->getTemplateContent($page->page->template),
                'localizedRoute' => $localizedRoute,
            ]);
        }

        return view('pages.show', [
            'page' => $page,
            'localizedRoute' => $localizedRoute,
        ]);
    }

    public function getTemplateContent(string $template): array
    {
        return match ($template) {
            'news' => $this->getNewsContent(),
            'faq' => $this->getFaqContent(),
        };
    }

    private function getNewsContent(): array
    {
        return [
            'news' => Post::query()
                ->with([
                    'image',
                    'translations' => function ($query) {
                        $query->where('locale', app()->getLocale());
                    },
                ])
                ->when(request()->get('sortBy', null), function ($q, $sortBy) {
                    $q->orderBy('created_at', $sortBy === 'newest' ? 'desc' : 'asc');
                })
                ->paginate(6)
                ->withQueryString(),
        ];
    }

    private function getFaqContent(): array
    {
        $questionCategories = QuestionCategory::query()
            ->with([
                'translations' => function ($query) {
                    $query->where('locale', app()->getLocale());
                },
                'questions.translations' => function ($query) {
                    $query->where('locale', app()->getLocale());
                },
            ])
            ->get();

        return [
            'questionCategories' => $questionCategories,
        ];
    }
}
