<?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', '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'] ?? null,
                ]);
        } else {
            SeoData::query()
                ->where('path', $page->urlPath())
                ->delete();
        }
    }
}
