<?php

namespace App\Utilities;

use Illuminate\Support\Str;
use Illuminate\Support\Arr;
use App\Models\Page;

class PageLink
{
    public static function convertLink($value)
    {
        if (!$value) {
            return null;
        }
        if (!editing() || request('preview')) {
            preg_match('/(^\d+)(#c-(.*))?/', $value, $match);

            if (count($match)) {
                $page = cache()->tags(['page-'.$match[1]])->rememberForever(cache_name('page-'.$match[1]).'-page', function() use($match) {
                    return Page::find($match[1]);
                });

                if ($page instanceof Page) {
                    $full_slug = self::processUrl($page, array_key_exists(3, $match) ? $match[3] : null);
                }

                return preg_replace('/'.$match[0].'/', $full_slug, $value);
            }
        }
        return $value;
    }

    public static function convertLinkText($value)
    {
        if ((!editing() || request('preview')) && $value) {
            $replace = [];

            //preg_match_all('/\<a.*?(href="(\d+).*(#c-([^"]+))?").*?\>([^\<]*)\<\/a>/', $value, $match);
            preg_match_all('/\<a.*?(href="(\d+)(\?.*?)?(#c-([^"]+))?").*?\>(?:[^\<]*)\<\/a>/', $value, $match);

            // match[0] = full a tag
            // match[1] = href attribute
            // match[2] = page id
            // match[3] = search
            // match[4] = hash
            // match[5] = uuid
            // match[6] = link text

            $find = collect($match[1])->map(function ($string) {
                $string = str_replace('?', '\?', $string);
                return '/'.str_replace('/', '\/', $string).'/';
            })->all();

            foreach ($match[2] as $index => $page_id) {
                $page = cache()->tags(['page-'.$page_id])->rememberForever(cache_name('page-'.$page_id).'-page', function() use($page_id) {
                    return Page::find($page_id);
                });
                if ($page instanceof Page) {
                    $replace[] = 'href="'.self::processUrl($page, array_key_exists(5, $match) ? $match[5][$index] : null).'"';
                }
            }

            $processed_text = preg_replace($find, $replace, $value);
            return $processed_text;
        }
        return $value;
    }

    public static function convertAnchorText($text)
    {
        return Str::kebab(preg_replace('/[^\p{L}\p{N} -]+/', '', $text));
    }

    protected static function getAnchor($page, $match = null)
    {
        $anchor = false;
        if ($match) { // content element link
            $ce = $page->content->firstWhere('uuid', $match);
            if ($ce?->anchor) {
                $anchor = $ce->anchor;
            }
        }
        return $anchor;
    }

    protected static function processUrl(Page $page, $uuid = null)
    {
        if ($page->full_slug !== '/') {
            $full_slug = '/'.$page->full_slug;
        } else {
            $full_slug = '/';
        }

        $anchor = false;
        if ($uuid) {
            $anchor = self::getAnchor($page, $uuid);
        }

        $url = $full_slug;

        /* Not sure we need this as we wont have params in our links
        if ($match[3][$index]) { // search
            $new_link .= $match[3][$index];
        }
         */

        if (request('preview') && $page->preview_url) {
            $url .= substr($page->preview_url, strpos($page->preview_url, "?"));
        }

        if ($anchor) { // content element link
            $url .= '#'.$anchor;
        }

        return $url;
    }

    public static function getSlugFromIdAndHash($input)
    {
        $class = 'App\\Models\\'.Str::studly(Arr::get($input, 'item_type'));

        $item = Arr::get($input, 'item_id');
        $uuid = false;
        if (Str::contains($item, '#')) {
            preg_match('/(\d+)#c-(.*)/', $item, $split);
            $item_id = $split[1];
            $uuid = $split[2];
        } else {
            $item_id = $item;
        }

        $item = (new $class())->find($item_id);

        if (!$item) {
            return null;
        }

        $slug = '';

        if ($item->full_slug) {
            $slug .= $item->full_slug;
            if ($uuid) {
                $anchor = $item->content->firstWhere('uuid', $uuid)?->anchor;
                if ($anchor) {
                    $slug .= '#'.$anchor;
                }
            }
        }

        return $slug;
    }
}
