<?php

/**
 * @package    Essentials for VirtueMart
 * @author     Abhishek Das <info@virtueplanet.com>
 * @copyright  Copyright (C) 2012-2024 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

use Joomla\CMS\Application\CMSApplication;
use Joomla\Registry\Registry;

jimport('cms.layout.file');
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.path');

JLoader::register('VMEssentialsHelperUtility', VMESSENTIALS_SITE . '/helpers/utility.php');
JLoader::register('VMEssentialsHelperRoute', VMESSENTIALS_SITE . '/helpers/route.php');

/**
 * VMEssentials Html Helper
 *
 * @since  1.0
 */
abstract class JHtmlVMEssentials
{
    public static $assetsLoaded = false;
    public static $return = null;
    public static $version = null;

    public static function addtowishlist($product, $iconOnly = null)
    {
        if (!is_object($product) || empty($product->virtuemart_product_id)) {
            return '';
        }

        $app    = JFactory::getApplication();
        $params = $app->getParams('com_vmessentials');
        $user   = JFactory::getUser();

        if (!$params->get('enable_wishlist', 1)) {
            return '';
        }

        if ($user->get('guest') && !$params->get('guest_wishlist', 1)) {
            return '';
        }

        if (!$product->orderable && !$params->get('allow_wishlist_not_orderable', 1)) {
            return '';
        }

        if ($iconOnly !== true && $iconOnly !== false) {
            $iconOnly = self::isList($product->virtuemart_product_id);
        }

        $product_id    = (int) $product->virtuemart_product_id;
        $model         = self::getModel('wishlist');
        $addedProducts = $model->getAllItemIds();
        $isAdded       = in_array($product_id, $addedProducts);

        $displayData = array();
        $displayData['product']   = $product;
        $displayData['iconOnly']  = $iconOnly;
        $displayData['params']    = $params;
        $displayData['isAdded']   = $isAdded;
        $displayData['url']       = JRoute::_(VMEssentialsHelperRoute::getRoute('wishlist'));
        $displayData['iconClass'] = $isAdded ? $params->get('wishlist_add_icon_class', 'fa fa-heart') : $params->get('wishlist_added_icon_class', 'fa fa-heart');
        $displayData['btnClass']  = $isAdded ? $params->get('wishlist_add_btn_class', 'btn-vme-round') : $params->get('wishlist_added_btn_class', 'btn-vme-round');

        $options = new Registry();
        $options->set('component', 'com_vmessentials');

        $layout         = new JLayoutFile('addtowishlist', null, $options);
        $renderedLayout = $layout->render($displayData);

        return $renderedLayout;
    }

    public static function addtocompare($product, $iconOnly = null)
    {
        if (!is_object($product) || empty($product->virtuemart_product_id)) {
            return '';
        }

        $app    = JFactory::getApplication();
        $params = $app->getParams('com_vmessentials');

        if (!$params->get('enable_compare', 1)) {
            return '';
        }

        if (!$product->orderable && !$params->get('allow_compare_not_orderable', 1)) {
            return '';
        }

        if ($iconOnly !== true && $iconOnly !== false) {
            $iconOnly = self::isList($product->virtuemart_product_id);
        }

        $product_id    = (int) $product->virtuemart_product_id;
        $model         = self::getModel('compare');
        $addedProducts = $model->getAllItemIds();
        $isAdded       = in_array($product_id, $addedProducts);

        $displayData = array();
        $displayData['product']   = $product;
        $displayData['iconOnly']  = $iconOnly;
        $displayData['params']    = $params;
        $displayData['isAdded']   = $isAdded;
        $displayData['url']       = JRoute::_(VMEssentialsHelperRoute::getRoute('compare'));
        $displayData['iconClass'] = $isAdded ? $params->get('compare_added_icon_class', 'fa fa-random') : $params->get('compare_add_icon_class', 'fa fa-random');
        $displayData['btnClass']  = $isAdded ? $params->get('compare_added_btn_class', 'btn-vme-round') : $params->get('compare_add_btn_class', 'btn-vme-round');

        $options = new Registry();
        $options->set('component', 'com_vmessentials');

        $layout         = new JLayoutFile('addtocompare', null, $options);
        $renderedLayout = $layout->render($displayData);

        return $renderedLayout;
    }

    public static function quickview($product, $iconOnly = null)
    {
        if (!is_object($product) || empty($product->virtuemart_product_id)) {
            return '';
        }

        $app    = JFactory::getApplication();
        $params = $app->getParams('com_vmessentials');

        if (!$params->get('enable_quickview', 1)) {
            return '';
        }

        if ($iconOnly !== true && $iconOnly !== false) {
            $iconOnly = self::isList($product->virtuemart_product_id);
        }

        $displayData = array();
        $displayData['product']   = $product;
        $displayData['params']    = $params;
        $displayData['iconOnly']  = $iconOnly;
        $displayData['url']       = JRoute::_('index.php?option=com_vmessentials&view=quickview&tmpl=component&virtuemart_product_id=' . (int) $product->virtuemart_product_id);
        $displayData['iconClass'] = $params->get('quickview_icon_class', 'fa fa-eye');
        $displayData['btnClass']  = $params->get('quickview_btn_class', 'btn-vme-round');

        $options = new Registry();
        $options->set('component', 'com_vmessentials');

        $layout         = new JLayoutFile('quickview', null, $options);
        $renderedLayout = $layout->render($displayData);

        return $renderedLayout;
    }

    public static function allbuttons($product)
    {
        if (is_int($product)) {
            $model   = VmModel::getModel('product');
            $product = $model->getProduct($product, true, true, true);
        }

        if (!is_object($product) || empty($product->virtuemart_product_id)) {
            return '';
        }

        $app    = JFactory::getApplication();
        $params = $app->getParams('com_vmessentials');
        $isList = self::isList($product->virtuemart_product_id);

        $displayData = array();
        $displayData['product']       = $product;
        $displayData['params']        = $params;
        $displayData['iconOnly']      = $isList;
        $displayData['addtowishlist'] = self::addtowishlist($product, $isList);
        $displayData['addtocompare']  = self::addtocompare($product, $isList);
        $displayData['quickview']     = $isList ? self::quickview($product, $isList) : '';

        if (empty($displayData['addtowishlist']) && empty($displayData['addtocompare']) && empty($displayData['quickview'])) {
            return '';
        }

        $options = new Registry();
        $options->set('component', 'com_vmessentials');

        $layout         = new JLayoutFile('allbuttons', null, $options);
        $renderedLayout = $layout->render($displayData);

        return $renderedLayout;
    }

    public static function rating($product)
    {
        static $jsLoaded = false;

        if (is_int($product)) {
            $model   = VmModel::getModel('product');
            $product = $model->getProduct($product, true, true, true);
        }

        if (!is_object($product) || empty($product->virtuemart_product_id)) {
            return '';
        }

        if (!$jsLoaded) {
            JHtml::_('script', 'com_vmessentials/vp-rating.min.js', array('relative' => true, 'version' => 'v1.0'));

            $jsLoaded = true;
        }

        $app    = JFactory::getApplication();
        $params = $app->getParams('com_vmessentials');

        $displayData = array();
        $displayData['product'] = $product;
        $displayData['params']  = $params;

        $options = new Registry();
        $options->set('component', 'com_vmessentials');

        $layout         = new JLayoutFile('rating', null, $options);
        $renderedLayout = $layout->render($displayData);

        return $renderedLayout;
    }

    public static function returnUri()
    {
        if (self::$return === null) {
            /** @var CMSApplication $app */
            $app    = JFactory::getApplication();
            $menu   = $app->getMenu();
            $uri    = clone JUri::getInstance();
            $vars   = $uri->getQuery(true);
            $input  = $app->input;
            $option = strtolower($input->getCmd('option', ''));
            $view   = strtolower($input->getCmd('view', ''));

            if (JFactory::getConfig()->get('sef')) {
                $router = $app->getRouter();

                if (version_compare(JVERSION, '4.0', '<')) {
                    $vars = $router->parse($uri);
                } else {
                    // Look for the home menu
                    if (JLanguageMultilang::isEnabled()) {
                        $defaultMenu = $menu->getDefault(JFactory::getLanguage()->getTag());
                    } else {
                        $defaultMenu = $menu->getDefault();
                    }

                    $activeMenu = $menu->getActive() ?: $defaultMenu;

                    try {
                        $vars = $router->parse($uri, true);
                    } catch (Exception $e) {
                        // We do not need to handle the exception here.
                    }

                    // Joomla\CMS\Router\SiteRouter sets active menu after parsing since Joomla 4.
                    // So we need to reset it.
                    if ($activeMenu) {
                        $menu->setActive($activeMenu->id);
                    }
                }
            }

            if ($option != 'com_vmessentials' || $view != 'quickview') {
                unset($vars['tmpl']);
            }

            if (JFactory::getConfig()->get('sef')) {
                if (isset($vars['Itemid'])) {
                    $itemid = $vars['Itemid'];
                    $item   = $menu->getItem($itemid);

                    unset($vars['Itemid']);

                    if (isset($item) && $vars == $item->query) {
                        $url = 'index.php?Itemid=' . $itemid;
                    } else {
                        $url = 'index.php?' . JUri::buildQuery($vars) . '&Itemid=' . $itemid;
                    }
                } else {
                    $url = 'index.php?' . JUri::buildQuery($vars);
                }
            } else {
                $url = 'index.php?' . JUri::buildQuery($vars);
            }

            self::$return = $url;
        }

        return '<input type="hidden" name="return" value="' . VMEssentialsHelperUtility::encode(self::$return) . '" />';
    }

    protected static function isList($product_id)
    {
        $virtuemart_product_idArray = vRequest::getInt('virtuemart_product_id', 0);

        if (is_array($virtuemart_product_idArray) && count($virtuemart_product_idArray) > 0) {
            $virtuemart_product_id = (int)$virtuemart_product_idArray[0];
        } else {
            $virtuemart_product_id = (int) $virtuemart_product_idArray;
        }

        $app    = JFactory::getApplication();
        $input  = $app->input;
        $option = strtolower($input->getCmd('option', ''));
        $view   = strtolower($input->getCmd('view', ''));
        $isList = true;

        if (
            (($option == 'com_virtuemart' && $view == 'productdetails')
            || ($option == 'com_vmessentials' && $view == 'quickview'))
            && !empty($virtuemart_product_id) && $virtuemart_product_id == $product_id
        ) {
            $isList = false;
        }

        return $isList;
    }

    public static function assets()
    {
        if (!self::$assetsLoaded) {
            JHtml::_('behavior.keepalive');

            VmConfig::loadConfig();

            $app     = JFactory::getApplication();
            $doc     = JFactory::getDocument();
            $tab     = $doc->_getTab();
            $lineEnd = $doc->_getLineEnd();
            $params  = $app->getParams('com_vmessentials');
            $version = self::version();

            if ($params->get('enable_quickview', 1)) {
                if (class_exists('vmJsApi')) {
                    vmJsApi::jPrice();
                }

                JHtml::_('stylesheet', 'com_vmessentials/iframe-modal.css', array('relative' => true, 'version' => 'v' . $version));
                JHtml::_('script', 'com_vmessentials/iframe-modal.min.js', array('relative' => true, 'version' => 'v' . $version));
            }

            if ($params->get('load_fontawesome', 1)) {
                JHtml::_('stylesheet', 'com_vmessentials/font-awesome.min.css', array('relative' => true, 'version' => 'v4.7.0'));
            }

            if ($params->get('load_stylesheet', 1)) {
                JHtml::_('stylesheet', 'com_vmessentials/style.css', array('relative' => true, 'version' => 'v' . $version));
            }

            // Load custom css file if available
            JHtml::_('stylesheet', 'com_vmessentials/custom.css', array('relative' => true));

            JHtml::_('script', 'com_vmessentials/script.min.js', array('relative' => true, 'version' => 'v' . $version));
            JHtml::_('script', 'com_vmessentials/status-update.min.js', array('relative' => true, 'version' => 'v' . $version));

            $options = new stdClass();

            $options->base   = JUri::base();
            $options->itemid = $app->input->getInt('Itemid', 0);

            $script = $lineEnd . $tab . $tab . '<script type="application/json" id="vme-script-options">' . json_encode($options) . '</script>';

            $doc->addCustomTag($script);

            self::$assetsLoaded = true;
        }
    }

    public static function version()
    {
        if (self::$version === null) {
            self::$version = 'unknown';

            $manifest = VMESSENTIALS_ADMINISTRATOR . '/vmessentials.xml';

            if (file_exists($manifest)) {
                $xml     = simplexml_load_file($manifest);
                $version = (string) $xml->version;

                if (!empty($version)) {
                    self::$version = $version;
                }
            }
        }

        return self::$version;
    }

    protected static function getModel($type)
    {
        // Import JModelLegacy
        jimport('legacy.model.legacy');

        // Include models path
        JModelLegacy::addIncludePath(VMESSENTIALS_SITE . '/models');

        return JModelLegacy::getInstance(ucfirst($type), 'VMEssentialsModel', array('ignore_request' => true));
    }
}
