<?php

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

namespace SmilePack\Helpers;

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

use NRFramework\Conditions\ConditionBuilder;
/**
 * Conditions Helper
 */
class Conditions
{
    /**
     * Check if the module should be displayed based on the display conditions.
     * 
     * @param   object  $module  The module object
     * 
     * @return  bool
     */
    public static function pass($module)
    {
        // Sanity check
        if (!$module)
        {
            return true;
        }

        if (is_string($module->params))
        {
            $params = json_decode($module->params, true);
        }
        
        // If no valid conditions are found, the module should be displayed.
        if (!isset($params['rules']) || empty($params['rules']))
        {
            return true;
        }

        // OK. We have some valid conditions. Let's check them.
        $displayConditionsType = isset($params['display_conditions_type']) ? $params['display_conditions_type'] : false;

        // Abort if the module is set to appear sitewide
        if (!$displayConditionsType)
        {
            return true;
        }
        
        // Default Display Conditions point to custom display conditions
        $rules = $params['rules'];

        // Bug: Re-save a module without opening the Display Conditions tab. Now the 'rules' property is still a string.
        // Until we figure out what's going wrong, we'll convert the string to an array.
        $rules = is_string($rules) ? json_decode($rules, true) : $rules;

        // Mirror Display Conditions of another module
        $mirror_module_id = isset($params['mirror_module']) ? $params['mirror_module'] : false;
        if ($displayConditionsType == 'mirror')
        {
            // If the mirror module not found, the original module should be displayed
            if (!$mirror_module_id || !$module = \NRFramework\Extension::getModuleById($mirror_module_id))
            {
                return true;
            }

            $module_params = is_string($module['params']) ? json_decode($module['params'], true) : $module['params'];

            $rules = isset($module_params['rules']) ? $module_params['rules'] : [];
        }

        return ConditionBuilder::pass($rules);
    }
}