<?php
/**
 * @package   Nicepage Website Builder
 * @author    Nicepage https://www.nicepage.com
 * @copyright Copyright (c) 2016 - 2019 Nicepage
 * @license   http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 or later
 */

namespace NP\Processor;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ModuleHelper;
use Joomla\Registry\Registry;

class BreadcrumbsProcessor
{
    /**
     * Process all bredcrumbs on the page
     *
     * @param string $content Page content
     *
     * @return mixed
     */
    public function process($content) {
        return preg_replace_callback('/<\!--breadcrumbs_template-->([\s\S]+?)<\!--\/breadcrumbs_template-->/', array(&$this, '_processBreadcrumbs'), $content);
    }

    /**
     * Process breadcrumbs
     *
     * @param array $breadcrumbsMatch Breadcrumbs match
     *
     * @return string
     * @throws \Exception
     */
    private function _processBreadcrumbs($breadcrumbsMatch) {
        $breadcrumbsHtml = $breadcrumbsMatch[1];
        $breadcrumbsOptions = array();
        if (preg_match('/<\!--breadcrumbs_options_json--><\!--([\s\S]+?)--><\!--\/breadcrumbs_options_json-->/', $breadcrumbsHtml, $matches)) {
            $breadcrumbsOptions = json_decode($matches[1], true);
        }
        $document = Factory::getDocument();

        $breadcrumbsContent = '';
        if ($document->countModules('breadcrumbs') === 0) {
            return $breadcrumbsContent;
        }

        $app = Factory::getApplication();
        $m = Factory::getApplication()->bootModule('mod_breadcrumbs', 'site');

        foreach (ModuleHelper::getModules('breadcrumbs') as $module) {
            $params = new Registry($module->params);

            $dispatcher = $m->getDispatcher($module, $app);
            $dispatcher->dispatch();

            $list = $m->getHelper('BreadcrumbsHelper')->getBreadcrumbs($params, $app);
            $count = count($list);
            if (!$params->get('showHome', 1)) {
                $homeCrumb = $m->getHelper('BreadcrumbsHelper')->getHomeItem($params, $app);
            }
            ob_start();
            include JPATH_SITE . '/components/com_nicepage/views/html/mod_breadcrumbs/default.php';
            $breadcrumbsContent .= ob_get_clean();
        }
        return $breadcrumbsContent;
    }
}
