<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Mtc\ContentManager\Contracts\PageModel;
use Mtc\ContentManager\Contracts\Template;
use Mtc\ContentManager\Facades\Media;
use Mtc\ContentManager\Facades\Page;
use Mtc\ContentManager\Models\ContentCategory;
use Mtc\ContentManager\Models\MediaFolder;

class SandownArticleImport implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * Create a new job instance.
     */
    public function __construct(
        private readonly array $data,
        private readonly array $imageLinks,
        private readonly Template $template,
        private readonly ?ContentCategory $category
    ) {
        //
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        if ($this->data[0] == 'id') {
            return;
        }
        $pageContent = json_decode((string) $this->data[2], true);
        $media_folder = MediaFolder::query()->firstOrCreate(['name' => 'News Articles Images']);

        $images = $this->getImages($pageContent);
        $thumbnail = '';

        if (!empty($pageContent['snipp_img_original'])) {
            $thumbnail = 'https://www.sandown-brabus.co.uk/files/' . $pageContent['snipp_img_original'];
        }

        $bannerImage = '';
        if (!empty($pageContent['banner_original'])) {
            $bannerImage = 'https://www.sandown-brabus.co.uk/files/' . $pageContent['banner_original'];
        }

        $page = app(PageModel::class)->updateOrCreate([
            'slug' => $this->data[3]
        ], [
            'title' => html_entity_decode((string) $this->data[1]),
            'status' => 'published',
            'published_at' => Carbon::parse($this->data[6]),
            'category' => 'news',
            'template_id' => $this->template->id,
        ]);

        if (!empty($this->category)) {
            $page->categories()->sync($this->category->id);
        }

        if (!empty($thumbnail) && $page->mediaUses()->exists() === false) {
            $thumbnail = Media::importImageFromUrl($thumbnail);
            $thumbnail->update(['folder_id' => $media_folder->id]);
            Media::setUsesForModel([$thumbnail->id], $page, ['primary' => true]);
        }

        Page::syncContentWithTemplate($page->id);

        if (!empty($pageContent)) {
            foreach ($page->content as $content) {
                if ($content->name == 'Blog Single') {
                    foreach ($content->subContent as $subContent) {
                        if ($subContent->name == 'Top Description') {
                            $subContent->content = $this->markdownToHtml($this->data[4]);
                        } elseif ($subContent->name == 'Bottom Description') {
                            $subContent->content = $this->markdownToHtml($pageContent['body']);
                        } elseif ($subContent->name == 'Images') {
                            if (!empty($images)) {
                                $imagesIds = [];
                                foreach ($images as $image) {
                                    $imagesIds[] = Media::importImageFromUrl($image)->id;
                                }
                                \Mtc\ContentManager\Models\Media::query()->whereIn('id', $imagesIds)
                                    ->update(['folder_id' => $media_folder->id]);
                                Media::setUsesForModel($imagesIds, $subContent);
                            }
                        } elseif ($subContent->name == 'Main Image') {
                            if (!empty($bannerImage)) {
                                $bannerImage = Media::importImageFromUrl($bannerImage);
                                $bannerImage->update(['folder_id' => $media_folder->id]);
                                Media::setUsesForModel([$bannerImage->id], $subContent);
                            }
                        }
                        $subContent->save();
                    }
                }
            }
        }
    }

    private function markdownToHtml($markdown): string
    {
        if (empty($markdown)) {
            return '';
        }

        $markdown = preg_replace('/\*\*(.*?)\*\*/u', '<strong>$1</strong>', (string) $markdown);
        $markdown = preg_replace('/#####(.*?)#####/s', '<h5>$1</h5>', $markdown);
        $markdown = preg_replace('/####(.*?)####/s', '<h4>$1</h4>', $markdown);
        $markdown = preg_replace('/###(.*?)###/s', '<h3>$1</h3>', $markdown);
        $markdown = preg_replace('/##(.*?)##/s', '<h2>$1</h2>', $markdown);
        $markdown = preg_replace('/(?:\*\*|-\s)(.*?)(?:\r\n|$)/', '<li>$1</li>', $markdown);
        $markdown = preg_replace('/\r\n<li>(.*?)<\/li>\r\n/s', '</p><ul><li>$1</li></ul><p>', $markdown);
        $markdown = preg_replace('/\r\n\r\n/', '</p><p>', $markdown);
        $markdown = str_replace("\r\n", '<br>', $markdown);
        $markdown = '<p>' . $markdown . '</p>';
        $markdown = str_replace(['<p></p>', '<p><br></p>'], '', $markdown);

        return $markdown;
    }

    private function getImages($pageContent = []): array
    {
        if (empty($pageContent)) {
            return [];
        }

        return collect($pageContent['article-imgs'] ?? [])
            ->map(fn($image) => 'https://www.sandown-brabus.co.uk/files/' . $image['a-img_original'])
            ->toArray();
    }
}
