<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Facades\Site;
use Illuminate\Support\Facades\Auth;
use Mtc\ContentManager\Http\Resources\PageViewResource as BasePageViewResource;
use Mtc\MercuryDataModels\SeoData;

class PageViewResource extends BasePageViewResource
{
    public function toArray($request)
    {
        $this->resource->password_protected = !empty($this->resource->password);
        $this->resource->seo = $this->getSeo();
        $this->resource->makeVisible([
            'password',
            'slug',
        ]);

        $this->resource->site_url = Site::pageUrl($this->resource, true);
        $resource =  parent::toArray($request);
        $resource['types'] = $this->getPageTypes();
        return $resource;
    }

    private function userCanEditResource(): bool
    {
        return Auth::user()->hasPermissionTo('publish-content');
        // TODO: Further implementation of per-page restrictions on editor rights
    }


    private function getSeo()
    {
        return SeoData::query()
            ->where('path', $this->resource->urlPath())->first();
    }

    private function getPageTypes()
    {
        $types = [
            [
                'id' => null,
                'name' => __('pages.types.content_page'),
            ],
        ];

        if (Settings::get('app-content-blog-enabled')) {
            $types[] = [
                'id' => 'blog',
                'name' => __('pages.types.blog'),
            ];
        }
        if (Settings::get('app-content-news-enabled')) {
            $types[] = [
                'id' => 'news',
                'name' => __('pages.types.news'),
            ];
        }

        return $types;
    }
}
