<?php

namespace Database\Seeders\Tenant;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Mtc\MercuryDataModels\ContentElement;
use Mtc\ContentManager\Models\GlobalContent;
use Mtc\ContentManager\Models\Template;

class {{ class }} extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->elements();
        $this->template();
    }

    private function template(): void
    {
        $template = Template::query()->create({{ templateData }});
        collect({{ templateElementList }})
            ->each(function ($element) use ($template) {
                $element['template_id'] = $template->id;
                $element['data'] = json_decode($element['data'], true);
                $element['meta'] = json_decode($element['meta'], true);
                $entry = $template->elements()->create($element);
            });
    }

    private function elements(): void
    {
        $data = collect({{ elementList }});
        $data->each(fn($entry) => ContentElement::query()->create($entry));

        // Now add all fields
        $data->filter(fn($entry) => !empty($entry['fields']))
            ->each(function ($entry) {

                $entry['data'] = json_decode($entry['data'], true);
                /** @var ContentElement $element */
                $element = ContentElement::query()->where('slug', $entry['slug'])->first();
                collect($entry['fields'])
                    ->each(function ($field) use ($element) {
                        if (!empty($field['child_element_id'])) {
                            $field['child_element_id'] = ContentElement::query()
                                ->where('slug', $field['child_element_id'])
                                ->firstOrFail()
                                ->id;
                        }
                        $field['data'] = json_decode($field['data'], true);
                        $field['meta'] = json_decode($field['meta'], true);
                        $element->fields()->create($field);
                    });
            });
    }
}
