<?php

/**
 * Vvveb
 *
 * Copyright (C) 2022  Ziadin Givan
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 */

/*
Name: Table of content for posts
Slug: toc-posts
Category: content
Url: https://www.vvveb.com
Description: Show navigable table of content for posts
Author: givanz
Version: 0.1
Thumb: toc-posts.svg
Author url: https://www.vvveb.com
*/

use Vvveb\System\Core\View;
use Vvveb\System\Event;

if (! defined('V_VERSION')) {
	die('Invalid request!');
}

class TocPostsPlugin {
	private $headings;

	private $html;

	public function setHtml($html) {
		$this->html = $html;
		$this->setHeadings();
	}

	public function getHtml() {
		$this->setHeadingIds();

		return $this->html;
	}

	public function setHeadingIds() {
		$index = 0;

		$this->html = preg_replace_callback(
			'|<h([1-6])[^>]*>(.*?)</h\1>|i',
			function ($matches) use (&$index) {
				if (preg_match('/\sid=/i', $matches[0])) {
					$index++;

					return $matches[0];
				}

				$slug = $this->headings[2][$index++] ?? '';

				return preg_replace('/<h(\d+)/', "<h$1 id=\"$slug\"", $matches[0]);
			},
			$this->html
		);
	}

	public function list() {
		$matches = $this->headings;
		$list    = [];

		foreach ($matches[1] as $key => $item) {
			$depth = (int)substr($matches[0][$key], 2, 1);

			$list[] = [
				'name'    => strip_tags($item),
				'url'     => '#' . $matches[2][$key],
				'onclick' => '',
				'depth'   => $depth - 1,
			];
		}

		return $list;
	}

	private function setHeadings() {
		preg_match_all('|<h([1-6])[^>]*>(.*?)</h\1>|i', $this->html, $matches);

		$slugs = [];
		$used  = [];

		foreach ($matches[0] as $key => $heading) {
			$item = htmlspecialchars_decode($matches[2][$key]);

			if (preg_match('/\sid=["\']([^"\']*)["\']/i', $heading, $idMatch) && $idMatch[1] !== '') {
				$slugs[] = $idMatch[1];

				continue;
			}

			$slug = $this->slugify(strip_tags($item));

			if ($slug === '') {
				$slug = 'heading-' . (count($slugs) + 1);
			}

			if (isset($used[$slug])) {
				$slug .= '-' . ++$used[$slug];
			} else {
				$used[$slug] = 0;
			}

			$slugs[] = $slug;
		}

		$this->headings    = $matches;
		$this->headings[1] = $matches[2];
		$this->headings[2] = $slugs;
	}

	public function slugify($string, $replace = [], $delimiter = '-') {
		if (! empty($replace)) {
			$string = str_replace((array) $replace, ' ', $string);
		}
		$string = preg_replace('/[^a-zA-Z0-9\/_|+ -]/', '', $string);
		$string = strtolower($string);
		$string = preg_replace('/[\/_|+ -]+/', $delimiter, $string);
		$string = trim($string, $delimiter);

		return $string;
	}

	public function toc(&$post) {
		if (! isset($post['content'])) {
			return $post;
		}

		$this->setHtml($post['content']);
		$post['content'] = $this->getHtml();
		$post['toc']     = $this->list();

		return $post;
	}

	public function app() {
		//register component

		Event::on('Vvveb\Component\Post', 'results', __CLASS__, function ($results = false) {
			if ($results && isset($results['content'])) {
				$this->toc($results);
			}

			return [$results];
		});

		Event::on('Vvveb\Component\Posts', 'results', __CLASS__, function ($results = false) {
			if ($results && isset($results['post'][0]['content'])) {
				$this->toc($results['post'][0]);
			}

			return [$results];
		});

		$view       = View::getInstance();
		$template   = $view->getTemplateEngineInstance();
		$template->loadTemplateFile(__DIR__ . '/app/template/toc-posts.tpl');
	}

	public function __construct() {
		if (APP == 'app') {
			$this->app();
		}
	}
}

$tocPostsPlugin = new TocPostsPlugin();
