<?php

/**
 * @package         EngageBox
 * @version         6.3.8 Pro
 * 
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2020 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
*/

namespace EngageBox;

defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\Registry\Registry;
use Joomla\CMS\Factory;
use NRFramework\Cache;

class Helper 
{
    public static function getParams()
    {
        $hash = 'ebParams';

        if (Cache::has($hash))
        {
            return Cache::get($hash);
        }

        return Cache::set($hash, ComponentHelper::getParams('com_rstbox'));
    }

    
    /**
     * Get the excluded notices.
     * 
     * @return  array
     */
    public static function getExcludedNotices()
    {
        $list = [];

        if (!self::canShowGeolocationNotice())
        {
            $list[] = 'Geolocation';
        }
        
        return $list;
    }

    /**
     * Don't show the geolocation notice if:
     * 
     * 1) No license key is set
     * 2) No popup exists with any of the Geolocation conditions
     * 
     * @return  boolean
     */
    public static function canShowGeolocationNotice()
    {
		if (!self::getGeolocationPluginLicenseKey())
        {
            return false;
        }

        if (!self::popupsUseGeolocationConditions())
        {
            return false;
        }
        
        return true;
    }

    /**
     * Get the Geolocation Plugin License Key.
     * 
     * @return  string
     */
    public static function getGeolocationPluginLicenseKey()
    {
        $plugin = PluginHelper::getPlugin('system', 'tgeoip');

        if (!$plugin)
        {
            return '';
        }
        
		$params = new Registry($plugin->params);

		return $params->get('license_key', '');
    }

    /**
     * Check if any popup uses Geolocation conditions.
     * 
     * @return  boolean
     */
    public static function popupsUseGeolocationConditions()
    {
        $db = Factory::getDbo();

        $query = $db->getQuery(true)
            ->select($db->quoteName('params'))
            ->from($db->quoteName('#__rstbox'))
            ->where($db->quoteName('published') . ' = 1')
            ->setLimit(1000);

        $db->setQuery($query);

        $popups = $db->loadAssocList();

        $geolocationConditions = [
            'Geo\City',
            'Geo\Country',
            'Geo\Region',
            'Geo\Continent'
        ];

        $found = false;

        foreach ($popups as $popup)
        {
            $params = json_decode($popup['params'], true);
            $display_conditions_type = isset($params['display_conditions_type']) ? $params['display_conditions_type'] : '';

            if ($display_conditions_type !== 'custom')
            {
                continue;
            }

            $conditions = is_string($params['rules']) ? json_decode($params['rules'], true) : $params['rules'];

            if (!$conditions)
            {
                continue;
            }
            
            foreach ($conditions as $key => $set)
            {
                if (!isset($set['enabled']) || $set['enabled'] !== '1')
                {
                    continue;
                }
                
                foreach ($set['rules'] as $key2 => $rule)
                {
                    if (!in_array($rule['name'], $geolocationConditions))
                    {
                        continue;
                    }

                    if (!isset($rule['enabled']) || $rule['enabled'] !== '1')
                    {
                        continue;
                    }
                    
                    if (!\NRFramework\Conditions\ConditionBuilder::prepareTFRepeaterValue($rule['value']))
                    {
                        continue;
                    }
                    
                    $found = true;
                    break;
                }
            }
        }

        return $found;
    }

    /**
     *  Returns all available box types
     *
     *  @return  array
     */
    public static function getBoxTypes()
    {
        PluginHelper::importPlugin('engagebox');
        Factory::getApplication()->triggerEvent('onEngageBoxTypes', array(&$types));

        if (!$types)
        {
            return [];
        }
        
        asort($types);

        return $types;
    }
    

    /**
     *  Get Visitor ID
     *
     *  @return  string
     */
    public static function getVisitorID()
    {
        return \NRFramework\VisitorToken::getInstance()->get();
    }

    public static function arrayToCSSS($array)
    {
        $array = array_filter($array);

        if (empty($array))
        {
            return '';
        }

        $styles = '';

        foreach ($array as $key => $value)
        {
            $styles .= $key . ':' . $value . ';';
        }

        return $styles;
    }

    public static function licenseIsValid()
    {
        return \NRFramework\Functions::getDownloadKey();
    }

    
    /**
     * Checks if there are any EngageBox-related shortcodes available and replaces them.
     * 
     * @param   string  $text
     * 
     * @return  void
     */
    public static function replaceShortcodes(&$text)
    {
        if (!$text)
        {
            return;
        }
        
        // Check whether the plugin should process or not
        if (\Joomla\String\StringHelper::strpos($text, '{eb') === false)
        {
            return true;
        }

        // Search for this tag in the content
        $regex = "#{eb([^{}]++|\{(?1)\})+}#s";
        $text = preg_replace_callback($regex, [__CLASS__, 'processShortcode'], $text);
    }

    /**
     *  Callback to preg_replace_callback in the onContentPrepare event handler of this plugin. 
     * 
     *  Note: Unrecognized shortcodes will be skipped and won't be replaced. 
     *
     *  @param   array   $match  A match to any EngageBox-related shortcodes
     *
     *  @return  string  The processed result
     */
    private static function processShortcode($match)
    {
        if (!isset($match[0]))
        {
            return;
        }

        $originalShortcode = $match[0];

        // Find Shortcode
		$regex = 'eb([a-zA-Z]+)';
        preg_match_all('/' . $regex . '/is', 'eb' . $match[0], $params);
        if (!count($params[1]))
        {
            return $originalShortcode;
        }

        // Ensure shortcode exists
        $class = '\EngageBox\Shortcodes\\' . $params[1][0];
        if (!class_exists($class))
        {
            return $originalShortcode;
        }
        
        // Find options
        $regex = '(\w+)\s*=\s*(["\'])((?:(?!\2).)*)\2';
        preg_match_all('/' . $regex . '/is', $match[0], $params);
        if (!count($params[1]))
        {
            return $originalShortcode;
        }

        // Combine keys, values to create the shortcode options
        $opts = array_combine($params[1], $params[3]);
        
        // Render the shortcode
        return (new $class($opts))->render();
    }
    
}