<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;
use App\Models\GenericBackoffice\Entry as EntryModel;
use App\Models\GenericBackoffice\WebsiteObject;
use App\Models\GenericBackoffice\WebsiteObjectLanguage;

class Entry extends JsonResource
{
    protected $isDetail = FALSE;

    public function __construct($resource, $isDetail = FALSE)
    {
        $this->resource = $resource;
        $this->isDetail = $isDetail;
    }

    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $activeLang = getActiveLanguage();
        $url = $activeLang === 'en' ? $this->lang_uri : '/' . $activeLang . $this->lang_uri;

        $out = [
            'id'          => (int)$this->id,
            'title'       => $this->title,
            'slug'        => '/' . $this->lang_slug,
            'language_id' => $this->language_id,
            'url'         => $url,
            'parent'      => null
        ];

        $objects = WebsiteObjectLanguage::where('website_object_id', $this->website_object_id)->get();
        $langUris = [];
        foreach ($objects as $object) {
            $langUris[$object->wo_language_id] = $object->lang_uri;
        }
        $out['langUris'] = $langUris;

        if ($this->parent_id != null) {
            $obj = WebsiteObject::find($this->parent_id);
            $parent = EntryModel::full()->where('id', $obj->object_id)->first();
            $out['parent'] = [
                'title' => $parent->title,
                'url' => $parent->lang_uri
            ];
        }

        if ($this->isDetail) {
            // SEO IMAGE
            $metaImage = $this->metaImage ? getImage($this->metaImage, 'w600') : NULL;

            $out = array_merge($out, [
                'meta'        => (object)[
                    'title'       => $this->meta_title ? $this->meta_title : $this->title,
                    'description' => $this->meta_description,
                    'image'       => $metaImage
                ],
                'blocks' => new BlockCollection($this->blocks),
            ]);

            if ((empty($out['meta']->description) || !$metaImage) && $this->slug != 'home') {
                
                $homePage = EntryModel::full()
                    ->where('slug', 'home')
                    ->first();
                if (empty($out['meta']->description)) {
                    $out['meta']->description = $homePage->meta_description;
                }
                if (!$metaImage) {
                    $metaImage = $homePage->metaImage ? getImage($homePage->metaImage, 'w600') : NULL;
                    $out['meta']->image = $metaImage;
                }
            }
        }

        return $out;
    }
}
