<?php

namespace App\Traits;

use App\Facades\Settings;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\SeoData;
use Mtc\MercuryDataModels\SeoDefault;

trait RetrievesSeoData
{
    use CacheObject;

    protected Collection $mediaSizes;

    private function fillSeo(string $section, ?string $urlPath = null): array
    {
        if (!empty($urlPath)) {
            $data = $this->getSeoForPath($urlPath);
            if ($data) {
                return $data->only([
                    'title',
                    'description',
                    'heading',
                    'content',
                    'canonical',
                    'json_schema',
                ]);
            }
        }

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


        $default = $this->cache(
            'seo-default-' . $section,
            15,
            fn () => SeoDefault::query()->where('section', $section)->first()
        );
        if (!$default) {
            return $seoData;
        }

        $replacements = $this->getSeoTagReplacements();

        if (empty($seoData['title'])) {
            $seoData['title'] = $this->replaceSeoTags(
                $replacements,
                $default->title ?? $this->resource->title
            );
        }

        if (empty($seoData['description'])) {
            $seoData['description'] = $this->replaceSeoTags(
                $replacements,
                $default->description ?? ''
            );
        }

        if (empty($seoData['heading']) && !empty($default->heading)) {
            $seoData['heading'] = $this->replaceSeoTags(
                $replacements,
                $default->heading
            );
        }

        if (empty($seoData['content_description']) && !empty($default->content_description)) {
            $seoData['content_description'] = $this->replaceSeoTags(
                $replacements,
                $default->content_description
            );
        }

        return $seoData;
    }

    private function getSeoTagReplacements(): array
    {
        return [
            '{{TITLE}}' => $this->resource->title ?? $this->resource->name,
            '{{MAKE}}' => $this->resource->make->name ?? '',
            '{{MODEL}}' => $this->resource->model->name ?? '',
            '{{DERIVATIVE}}' => $this->resource->derivative ?? '',
            '{{FUEL_TYPE}}' => $this->resource->fuelType->name ?? '',
            '{{BODY_STYLE}}' => $this->resource->bodyStyle->name ?? '',
            '{{TRANSMISSION}}' => $this->resource->transmission->name ?? '',
            '{{MANUFACTURE_YEAR}}' => $this->resource->manufacture_year ?? '',
            '{{COLOUR}}' => $this->resource->colour ?? '',
            '{{VEHICLE_TYPE}}' => $this->resource->vehicle_type ?? '',
            '{{CONDITION}}' => $this->getConditionValue(),
            '{{SITE_NAME}}' => Settings::get('app-name'),
            '{{CONTENT_EXCERPT}}' => Str::limit($this->resource->description, 150),
            '{{NEW_USED}}' => $this->resource->is_new
                ? __('labels.vehicle.new')
                : __('labels.vehicle.used'),
            '{{SOLD_STATUS}}' => $this->resource->is_sold
                ? __('labels.vehicle.sold')
                : __('labels.vehicle.for-sale'),
        ];
    }

    protected function getConditionValue()
    {
        if ($this->resource->is_new) {
            return __('labels.vehicle.new');
        }

        return $this->resource->ex_demo ? __('labels.vehicle.ex-demo') : __('labels.vehicle.used');
    }

    private function replaceSeoTags(array $replacements, string $string): string
    {
        $result = str_replace(array_keys($replacements), $replacements, $string);
        return preg_replace('/\s+/', ' ', trim($result));
    }

    private function getSeoForPath(string $path): ?Model
    {
        return SeoData::query()->where('path', $path)->first();
    }
}
