<?php

namespace App\Http\Resources;

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

class PropertyEntryList extends JsonResource
{
    use HasPlaceholderImage;

    private Request $request;
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $this->request = $request;
        $this->resource->through(fn(Property $property) => $this->map($property));
        $resource = parent::toArray($request);
        $resource['seo'] = $this->fillSeo();
        $resource['social_meta'] = new SocialMetaResource($resource['seo']);
        return $resource;
    }

    public function map(Property $property): array
    {
        $property->makeHidden([
            'id',
            'active',
            'updated_at',
            'category_id',
            'attribute_values',
            'attributeValues',
        ]);

        collect($property->attributeValues)
            ->each(function (PropertyAttributeValue $attribute) use ($property) {
                if (in_array($attribute->propertyField->type, ['form', 'form-field'])) {
                    $form = Form::query()->with('sections.questions')->find($attribute->getValue());
                    $property[$attribute->slug] = (new FormViewResource($form))
                        ->setValues(['property_id' => $property->id]);
                } elseif ($attribute->propertyField->type === 'image') {
                    $property[$attribute->slug] = $this->getGallery($attribute);
                } else {
                    $property[$attribute->slug] = $attribute->getValue();
                }
            });

        return $property->toArray();
    }

    protected function largeImageDimensions(): string
    {
        return 'large';
    }

    protected function mediumImageDimensions(): string
    {
        return 'square';
    }

    protected function thumbnailImageDimensions(): string
    {
        return 'thumb';
    }

    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;
        }

        $first = $this->resource->first();

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

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

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

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