<?php

/**
 * @package     VP Prime Framework
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2023-2025 Virtueplanet Services LLP. All Rights Reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 *
 * @phpcs:disable PSR1.Classes.ClassDeclaration.MissingNamespace
 */

use Joomla\CMS\Factory;
use Joomla\CMS\Helper\ModuleHelper;
use Joomla\CMS\Router\Route;
use Virtueplanet\Plugin\System\Prime\Helper\ModuleHelper as HelperModuleHelper;

// phpcs:disable PSR1.Files.SideEffects
defined('_JEXEC') or die;

if (!class_exists('VmConfig')) {
    require_once JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php';
}

VmConfig::loadConfig();
// phpcs:enable PSR1.Files.SideEffects

abstract class ModVpprimeMinicartHelper
{
    /**
     * Cart object
     *
     * @var VirtueMartCart|null
     */
    public static $cart = null;

    /**
     * Get the cart object
     *
     * @param   \Joomla\Registry\Registry  $params  Module parameters
     *
     * @return VirtueMartCart
     */
    public static function getCart($params)
    {
        if (!class_exists('VirtueMartCart')) {
            require_once JPATH_ROOT . '/components/com_virtuemart/helpers/cart.php';
        }

        vmLanguage::loadJLang('mod_virtuemart_cart', true);
        vmLanguage::loadJLang('com_virtuemart', true);

        if (static::$cart === null) {
            /** @var \Joomla\CMS\Application\SiteApplication $app */
            $app  = Factory::getApplication();
            $doc  = $app->getDocument();
            $type = strtoupper($doc->getType());
            $cart = VirtueMartCart::getCart(false);

            if ($params->get('delay_loading', 1) && $type == 'HTML') {
                $cart->prepareAjaxData();
            } else {
                $cart->prepareCartData();
            }

            if (empty($cart->cartPrices['billTotal']) || $cart->cartPrices['billTotal'] < 0 || empty($cart->products)) {
                $cart->cartPrices['billTotal'] = 0;
            }

            static::$cart = $cart;
        }

        return static::$cart;
    }

    /**
     * Get total product count in cart
     *
     * @param   \Joomla\Registry\Registry  $params  Module parameters
     *
     * @return int
     */
    public static function getProductCount($params)
    {
        $cart  = self::getCart($params);
        $count = 0;

        if (!empty($cart->products)) {
            foreach ($cart->products as $i => $product) {
                $count += $product->quantity;
            }
        }

        return $count;
    }

    /**
     * Get unique product count in cart
     *
     * @param   \Joomla\Registry\Registry  $params  Module parameters
     *
     * @return int
     */
    public static function getUniqueProductCount($params)
    {
        $cart  = self::getCart($params);
        $count = 0;

        if (!empty($cart->products)) {
            $count = count($cart->products);
        }

        return $count;
    }

    /**
     * Get cart link text and URL
     *
     * @param   \Joomla\Registry\Registry  $params  Module parameters
     *
     * @return array
     */
    public static function getCartLink($params)
    {
        $cart = self::getCart($params);

        if (false && ($cart->_dataValidated == true)) {
            $taskRoute = '&task=confirm';
            $text      = vmText::_('COM_VIRTUEMART_ORDER_CONFIRM_MNU');
        } else {
            $taskRoute = '';
            $text      = vmText::_('COM_VIRTUEMART_CART_SHOW');
        }

        $url = Route::_('index.php?option=com_virtuemart&view=cart' . $taskRoute);

        return [$text, $url];
    }

    /**
     * Get module HTML via AJAX
     *
     * @return void
     */
    public static function getAjax()
    {
        $app = Factory::getApplication();
        $id  = $app->input->get('id', 0);

        if ($id && ($module = HelperModuleHelper::get($id))) {
            $html = ModuleHelper::renderModule($module);

            return self::jsonReturn(['error' => false, 'html' => $html, 'message' => '']);
        }
    }

    /**
     * Remove product from cart via AJAX
     *
     * @return void
     */
    public static function removeProductAjax()
    {
        JLoader::register('VirtueMartCart', JPATH_ROOT . '/components/com_virtuemart/helpers/cart.php');

        /** @var \Joomla\CMS\Application\SiteApplication $app */
        $app       = Factory::getApplication();
        $productId = $app->input->post->getInt('cart_product_id', $app->input->getInt('cart_product_id', 0));
        $token     = $app->input->post->getString('token', '');

        /** @var VirtueMartCart $cart */
        $cart = VirtueMartCart::getCart();

        if (!empty($token)) {
            vRequest::setVar($token, 1);
        }

        if (version_compare(vmVersion::$RELEASE, '4.4.0', 'lt')) {
            vRequest::setVar('cart_virtuemart_product_id', $productId);

            if (!$cart->removeProductCart($productId)) {
                return self::jsonReturn(['error' => true, 'html' => '', 'message' => vmText::_('COM_VIRTUEMART_PRODUCT_NOT_REMOVED_SUCCESSFULLY')]);
            }
        } else {
            vRequest::setVar('quantity', [$productId => 0]);

            if (!$cart->updateProductCart()) {
                return self::jsonReturn(['error' => true, 'html' => '', 'message' => vmText::_('COM_VIRTUEMART_PRODUCT_NOT_REMOVED_SUCCESSFULLY')]);
            }
        }

        return self::jsonReturn(['error' => false, 'html' => '', 'message' => vmText::_('COM_VIRTUEMART_PRODUCT_REMOVED_SUCCESSFULLY')]);
    }

    /**
     * Return JSON response
     *
     * @param   array  $data  Data to return as JSON
     *
     * @return void
     */
    private static function jsonReturn($data)
    {
        $obLevel = ob_get_level();

        if ($obLevel) {
            while ($obLevel > 0) {
                ob_end_clean();
                $obLevel--;
            }
        } else {
            ob_clean();
        }

        if (isset($_SERVER['HTTP_ACCEPT']) && (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
            header('Content-type: application/text');
        } else {
            header('Content-type: application/json');
        }

        header('Cache-Control: public,max-age=1,must-revalidate');
        header('Expires: ' . gmdate('D, d M Y H:i:s', ($_SERVER['REQUEST_TIME'] + 1)) . ' GMT');
        header('Last-modified: ' . gmdate('D, d M Y H:i:s', $_SERVER['REQUEST_TIME']) . ' GMT');

        if (function_exists('header_remove')) {
            header_remove('Pragma');
        }

        echo json_encode($data);

        Factory::getApplication()->close();
    }
}
