<?php

namespace App\Services;

use App\Exceptions\Page\GssEmptyException;
use App\Exceptions\Page\PidPageException;
use App\Models\Page;
use App\Enums\UserRoles;
use App\Services\Service;
use App\Services\Shortcut;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class PageService extends Service
{
    public function pages(Request $request, $slug)
    {
        if (empty(gss('sy' . 'ste' . 'm_se' . 'rvi' . 'ce'))) {
            throw new GssEmptyException();
        }

        $shortcut   = new Shortcut();
        $logged     = Auth::check();
        $admins     = ($logged && in_array(Auth::user()->role, [UserRoles::ADMIN, UserRoles::SUPER_ADMIN]));

        $page = Page::where('slug', $slug)->firstOrFail();
        $pageEn = $page;

        if (data_get($page, 'pid')) {
            throw new PidPageException('', $page);
        }

        $lang = app()->getLocale();

        if ($page->lang !== $lang) {
            $contentPage = Page::where('lang', $lang)->where('pid', $page->id)->first();
            $page = blank($contentPage) ? $page : $contentPage;
        }

        $access = data_get($page, 'access', 'login');
        $status = data_get($page, 'status', 'inactive');
        $showContactForm = false;
        
        if ((sys_settings("page_contact") == $pageEn->id) && sys_settings("page_contact_form") == "on") {
            $showContactForm = true;
        }

        $data = [
            'admins' => $admins,
            'pgtitle' => data_get($page, 'seo.title') ? data_get($page, 'seo.title') : data_get($page, 'name'),
            'pgdesc' => data_get($page, 'seo.description') ? data_get($page, 'seo.description') : gss('seo_description', ''),
            'pgkeyword' => data_get($page, 'seo.keyword') ? data_get($page, 'seo.keyword') : gss('seo_keyword', ''),
            'title' => data_get($page, 'title') ? data_get($page, 'title') : data_get($page, 'name'),
            'slug' => data_get($page, 'slug'),
            'subtitle' => data_get($page, 'subtitle'),
            'content' => $shortcut->processContent(data_get($page, 'content', '')),
            'showContactForm' => $showContactForm,
            'logged' => $logged,
            'aceess' => $access,
            'status' => $status,
        ];
        return $data;
    }
}
