<?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\Utility;

defined('_JEXEC') or die;

/**
 * Categories  filter processor
 */
class SortingFilter
{
    private $_sorting;

    /**
     * Constructor
     *
     * @param string $sorting Sorting content
     */
    public function __construct($sorting)
    {
        $this->_sorting = $sorting;
    }

    /**
     * Process sorting
     *
     * @param string $html Page html
     *
     * @return array|string|string[]|null
     */
    public function process($html)
    {
        $re = '/<\!--products_sorting-->([\s\S]+?)<\!--\/products_sorting-->/';
        return preg_replace_callback($re, array(&$this, '_processSorting'), $html);
    }

    /**
     * Process sorting options
     *
     * @param array $sortingMatch Sorting match
     *
     * @return array|string|string[]
     */
    private function _processSorting($sortingMatch) {
        if (!$this->_sorting) {
            return '';
        }
        $selectClass = 'vm-orderby-select';
        if (strpos($this->_sorting, 'vm-orderby-select-custom') !== false) {
            $selectClass .= '-custom';
        }

        $sortingHtml = $sortingMatch[1];
        $sortingHtml = preg_replace('/(<select[^>]+?>)([\s\S]+?)(<\/select>)/', '$1' . $this->_sorting . '$3', $sortingHtml);
        $sortingHtml = str_replace('<select', '<select id="' . $selectClass . '"', $sortingHtml);
        return $sortingHtml;
    }
}
