<?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\ECommerce\Vm;

defined('_JEXEC') or die;

use NP\Builder\ProductDataBuilder;
use NP\Utility\CategoriesFilter;
use NP\Utility\SortingFilter;

class VmProductListTemplateProcessor extends VmProductListProcessor
{
    /**
     * @param string $html    Control html
     * @param array  $options Global options
     */
    public function __construct($html, $options)
    {
        $this->_html = $html;
        parent::__construct($html, $options);
    }

    /**
     * Build control
     *
     * @return string|void
     */
    public function build() {

        $result = '';
        $iterator = 0;
        $templateHtml = $this->_html;
        $templateData = $this->_options['templateData'];
        foreach ($templateData['products'] as $type => $productsModel) {
            $iterator++;
            if ($iterator == 1) {
                $sorting = $templateData['orderByList'];
                $createCategories = true;
            } else {
                $sorting = '';
                $createCategories = false;
            }

            $products = array();
            foreach ($productsModel as $item) {
                $builder = new ProductDataBuilder($item);
                $product = $builder->getData();
                array_push($products, $product);
            }

            if (count($products) < 1) {
                continue;
            }

            $this->_html = $templateHtml;
            $this->processProductItem($products);
            $this->processSortingFilter($sorting);
            $this->processCategoriesFilter(
                $this->_getCategories(),
                array(
                    'isVmTemplate' => true,
                    'createCategories' => $createCategories
                )
            );

            $this->clearHtml();

            if (count($templateData['products']) > 1 && $type != 'products') {
                $this->removePagination();
            } else {
                $this->processPagination();
            }

            $result .= $this->_html;
        }
        $this->_html = $result;
    }

    /**
     * Clear html
     *
     * @return void
     */
    public function clearHtml() {
        $this->_html = str_replace('data-products-datasource="site"', '', $this->_html);
    }

    /**
     * Remove pagination
     *
     * @return void
     */
    public function removePagination()
    {
        $this->_html = preg_replace('/<\!--products_pagination-->([\s\S]+?)<\!--\/products_pagination-->/', '', $this->_html);
    }

    /**
     * Process pagination
     *
     * @return array|string|string[]|null
     */
    public function processPagination() {
        $this->_html = preg_replace_callback('/<\!--products_pagination-->([\s\S]+?)<\!--\/products_pagination-->/', array(&$this, '_processProductsPagination'), $this->_html);
    }

    /**
     * Process pagination
     *
     * @param array $paginationMatch Matches
     *
     * @return false|mixed|string
     */
    private function _processProductsPagination($paginationMatch) {
        if (!$this->_options['templateData']['pagination']) {
            return '';
        }
        $paginationHtml = $paginationMatch[1];
        if (preg_match('/<\!--products_pagination_options_json--><\!--([\s\S]+?)--><\!--\/products_pagination_options_json-->/', $paginationHtml, $matches)) {
            $GLOBALS['theme_pagination_styles'] = json_decode($matches[1], true);
        }
        return $this->_options['templateData']['pagination']->getPagesLinks();
    }

    /**
     * Process categories filter in product list
     *
     * @param array $categoriesModel Page html
     * @param array $options         Options
     *
     * @return array|string|string[]|null
     */
    public function processCategoriesFilter($categoriesModel, $options) {
        $filter = new CategoriesFilter($categoriesModel, $options);
        $this->_html = $options['createCategories'] ? $filter->process($this->_html) : $filter->remove($this->_html);
    }

}
