<?php

namespace App;

use Mtc\ContentManager\Contracts\PageModel;
use Mtc\MercuryDataModels\Contracts\ModelWithUrlPath;
use Mtc\MercuryDataModels\SeoData;

trait SavesSeoData
{
    /**
     * Save Seo Data for page
     *
     * @param PageModel $page
     * @param array $input
     * @return void
     */
    protected function saveSeo(ModelWithUrlPath $page, array $input): void
    {
        $hasFields = collect($input)
            ->filter()
            ->hasAny(['title', 'description', 'heading', 'jsonSchema', 'json_schema', 'canonical']);

        if ($hasFields) {
            SeoData::query()
                ->updateOrCreate([
                    'path' => $page->urlPath(),
                ], [
                    'title' => $input['title'] ?? null,
                    'description' => $input['description'] ?? null,
                    'heading' => $input['heading'] ?? null,
                    'canonical' => $input['canonical'] ?? null,
                    'json_schema' => $input['jsonSchema'] ?? $input['json_schema'] ?? null,
                ]);
        } else {
            SeoData::query()
                ->where('path', $page->urlPath())
                ->delete();
        }
    }
}
