<?php

namespace Mtc\MercuryDemoData;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\File;
use Mtc\ContentManager\Facades\Media;
use Mtc\ContentManager\Models\ContentElement;
use Mtc\ContentManager\Models\Template;
use Mtc\ContentManager\PageStatus;
use Mtc\MercuryDataModels\Page;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleMake;
use Symfony\Component\Finder\SplFileInfo;

class DemoContentSeed extends Seeder
{

    private Collection $media;

    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $this->addMedia();
        $this->homeContent();
        $this->newsSeed();
        $this->newsRoomSeed();
    }

    private function homeContent()
    {
        /** @var Page $page */
        $page = Page::query()->where('slug', 'home')->firstOrFail();
        Media::setUsesForModel([ $this->media['page-4.jpg']->id], $page, ['primary' => true], true);
        Vehicle::query()
            ->inRandomOrder()
            ->take(7)
            ->update([
                'featured' => 1,
            ]);
        $this->updateHomeHero($page);
        $this->updateHomeCallToActions($page);
        $this->updateHomeNews($page);
    }

    private function addMedia()
    {
        $this->media = collect(File::files(dirname(__DIR__) . '/data/content-images'))
            ->keyBy(fn (SplFileInfo $file) => $file->getFilename())
            ->map(fn (SplFileInfo $file) => Media::importImageFromUrl($file->getPathname()));
    }

    private function newsRoomSeed()
    {
        $page = Page::query()->where('slug', 'news')->firstOrFail();

        $page->allContent()
            ->where('slug', 'text')
            ->update([
                'content' => json_encode('Newsroom')
            ]);

        $page->allContent()
            ->where('slug', 'article-type')
            ->update([
                'content' => [
                    'name' => 'News Articles',
                    'value' => 'news',
                ],
            ]);
    }

    private function newsSeed()
    {
        $titles = [
            'Top 10 cars of 2022',
            'Driving with allergies',
            "The world's most in-demand cars",
            'All new 2023 BMW 4 series',
            'Top electric cars actually worth a look',
        ];

        $template = Template::query()->where('slug', 'news-article')->firstOrFail();
        foreach ($titles as $index => $title) {
            $page = \Mtc\ContentManager\Facades\Page::create($title, $template->id);
            $page->update([
                'status' => PageStatus::PUBLISHED->value,
                'category' => 'news',

            ]);
            Media::setUsesForModel([$this->media['page-' . ($index + 1) . '.jpg']->id], $page, ['primary' => true], true);

            $url = "https://baconipsum.com/api/?type=all-meat&paras=" . random_int(2, 6) . "&start-with-lorem=1";
            $page->allContent()
                ->where('slug', 'text-content')
                ->update([
                    'content' => json_encode(collect(json_decode(file_get_contents($url), true))
                        ->map(fn ($paragraph) => "<p>$paragraph</p>")
                        ->implode("\n"))
                ]);

            $imageContent = $page->allContent()
                ->where('slug', 'image')
                ->first();
            Media::setUsesForModel([$this->media['page-' . ($index + 1) . '.jpg']->id], $imageContent, ['primary' => true], true);
        }
    }

    private function updateHomeHero(Page $page)
    {
        $hero = $page->allContent()->where('name', 'Hero')->first();
        $imageContent = $page->allContent()
            ->where('parent_id', $hero->id)
            ->where('slug', 'image')
            ->first();

        Media::setUsesForModel([ $this->media['page-4.jpg']->id], $imageContent, [], true);

        $page->allContent()
            ->where('parent_id', $hero->id)
            ->where('slug', 'title')
            ->update([
                'content' => json_encode('Making buying a car simple')
            ]);

        $page->allContent()
            ->where('parent_id', $hero->id)
            ->where('slug', 'brands')
            ->update([
                'content' => VehicleMake::query()
                    ->whereIn('name', ['Audi', 'BMW', 'Jaguar', 'Land Rover', 'Mercedes-Benz', 'Volkswagen'])
                    ->pluck('id'),
            ]);
    }

    private function updateHomeCallToActions(Page $page)
    {
        $callToAction = $page->allContent()->where('slug', 'call-to-action')->first();
        $imageContent = $page->allContent()
            ->where('parent_id', $callToAction->id)
            ->where('slug', 'image')
            ->first();

        Media::setUsesForModel([ $this->media['page-1.jpg']->id], $imageContent, [], true);

        $page->allContent()
            ->where('parent_id', $callToAction->id)
            ->where('slug', 'title')
            ->update([
                'content' => json_encode('The easiest way to purchase a new car'),
            ]);
        $page->allContent()
            ->where('parent_id', $callToAction->id)
            ->where('slug', 'label')
            ->update([
                'content' => json_encode('View Offers'),
            ]);
        $page->allContent()
            ->where('parent_id', $callToAction->id)
            ->where('slug', 'link')
            ->update([
                'content' => json_encode('/offers/'),
            ]);

        $element = ContentElement::query()
            ->with('fields.childElement.fields.childElement.fields.childElement.fields.childElement')
            ->where('slug', 'call-to-action')
            ->first();
        $parent = $page->allContent()->where('slug', 'call-to-action')->first()->parent;
        $content = \Mtc\ContentManager\Facades\Page::addElement($parent, $element);

        $imageContent = $content->subContent()
            ->where('slug', 'image')
            ->first();

        Media::setUsesForModel([ $this->media['page-3.jpg']->id], $imageContent, [], true);

        $content->subContent()
            ->where('slug', 'title')
            ->update([
                'content' => json_encode('The easiest way to purchase a new car'),
            ]);

        $content->subContent()
            ->where('slug', 'label')
            ->update([
                'content' => json_encode('View Used Cars'),
            ]);

        $content->subContent()
            ->where('slug', 'link')
            ->update([
                'content' => json_encode('/catalog/'),
            ]);
    }

    private function updateHomeNews(Page $page)
    {
        $page->allContent()
            ->where('slug', 'article-type')
            ->update([
                'content' => [
                    'name' => 'News Articles',
                    'value' => 'news',
                ],
            ]);
    }
}
