<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Inertia\Inertia;

use App\Helpers\PageBlocksHelper;

use App\Models\Page;
use App\Models\PageRevision;
use App\Models\ImageNode;

class PageRender extends Controller
{
    public function view(Request $request, $slug) {
        $page = Page::where('slug', $slug)->firstOrFail();

        if ($page->main) {
            abort(404);
        }

        if (!$page->is_published) {
            abort(403);
        }

        if ($page->visibility === 'private') {
            if (!Auth::check()) {
                abort(403);
            }
        }

        $images = ImageNode::all();

        $revision = $page->activeRevision;
        $revision->load(['page', 'editor']);

        $neededFetchers = collect();

        $blocks = json_decode($revision->content, true);

        foreach ($blocks as $block) {
            if (!empty($block['needs'])) {
                $neededFetchers = $neededFetchers->merge($block['needs']);
            }
        }

        $neededFetchers = $neededFetchers->unique();

        $blockData = [];

        foreach ($neededFetchers as $fetcher) {
            if (method_exists(PageBlocksHelper::class, $fetcher)) {
                $blockData[$fetcher] = PageBlocksHelper::$fetcher();
            }
        }

        return Inertia::render('Root', [
            'revision' => [
                'id'        => $revision->id,
                'uuid'      => $revision->uuid,
                'version'   => $revision->version,
                'title'     => $revision->title,
                'slug'      => $revision->slug,
                'label'     => $revision->label,
                'active'    => $revision->active,
                'content'   => json_decode($revision->content, true),
                'page' => [
                    'id'          => $revision->page->id,
                    'uuid'        => $revision->page->uuid,
                    'is_published'=> $revision->page->is_published,
                    'main'        => $revision->page->main,
                    'visibility'  => $revision->page->visibility,
                ]
            ],
            'images'    => $images,
            'blockData' => $blockData
        ]);
    }
}
