<?php

namespace App\Http\Resources;

use App\Facades\Settings;
use App\Traits\MediaHasSizes;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Mtc\MercuryDataModels\Form;
use Mtc\MercuryDataModels\MediaUse;
use Mtc\MercuryDataModels\PropertyAttributeValue;
use Mtc\MercuryDataModels\SeoData;
use Mtc\MercuryDataModels\SeoDefault;

class PropertyEntry extends JsonResource
{
    use MediaHasSizes;

    private Request $request;
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    #[\Override]
    public function toArray(Request $request): array
    {
        $this->request = $request;
        $this->resource->makeHidden([
            'id',
            'active',
            'created_at',
            'updated_at',
            'category_id',
            'attribute_values',
        ]);

        collect($this->resource->attributeValues)
            ->each(fn($attribute) => $this->resource[$attribute->slug] = $this->getAttributeValue($attribute));

        $resource = parent::toArray($request);
        $resource['seo'] = $this->fillSeo();
        $resource['canonical'] = $resource['data']['canonical'] ?? $resource['seo']['canonical'] ?? null;
        $resource['social_meta'] = new SocialMetaResource($resource['seo']);
        return $resource;
    }

    private function getAttributeValue(PropertyAttributeValue $attribute): mixed
    {
        if (in_array($attribute->type, ['form', 'form-field'])) {
            return new FormViewResource(Form::query()->with('sections.questions')->find($attribute->getValue()))
                ->setValues(['property_id' => $this->resource->id]);
        }
        if ($attribute->type == 'image') {
            return MediaUse::query()
                ->whereIn('media_id', $attribute->getValue())
                ->with('media')
                ->get()
                ->map(fn($mediaUse) => [
                    'src' => $mediaUse->getUrl('square-tile'),
                    'sizes' => $this->allSizesForUse($this->resource, $mediaUse),
                    'alt' => $mediaUse->alt_text,
                    'caption' => $mediaUse->caption,
                    'title' => $mediaUse->title,
                ]);
        }
        return $attribute->getValue();
    }


    private function fillSeo(): array
    {
        $seoData = $this->resource['seo'] ?? [];
        if (!empty($seoData['title']) && !empty($seoData['description'])) {
            return $seoData;
        }

        $data = SeoData::query()->where('path', $this->request->header('x-path'))->first();
        if ($data) {
            $data->makeHidden(['id', 'content_element_id']);
            return $data->toArray();
        }

        $default = SeoDefault::query()->where('section', 'page')->first();
        if (!$default) {
            return $seoData;
        }

        if (empty($seoData['title'])) {
            $seoData['title'] = $this->replaceSeoTags([
                '{{TITLE}}' => $this->resource->title,
                '{{SITE_NAME}}' => Settings::get('app-name'),

            ], $default->title ?? $this->resource->title);
        }

        if (empty($seoData['description'])) {
            $seoData['description'] = $this->replaceSeoTags([
                '{{TITLE}}' => $this->resource->title,
                '{{SITE_NAME}}' => Settings::get('app-name'),
                '{{CONTENT_EXCERPT}}' => $this->resource->excerpt,

            ], $default->description ?? '');
        }
        return $seoData;
    }

    private function replaceSeoTags(array $replacements, string $string): string
    {
        return str_replace(array_keys($replacements), $replacements, $string);
    }
}
