<?php

/**
 * @package     VP Prime Ajax Product Search
 *
 * @author      Abhishek Das <info@virtueplanet.com>
 * @link        https://www.virtueplanet.com
 * @copyright   Copyright (C) 2012-2023 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\Registry\Registry;
use Virtueplanet\Module\AjaxSearch\Site\Helper\SearchHelper;

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

abstract class ModVpprimeAjaxSearchHelper
{
    public static function getAjax()
    {
        $app   = Factory::getApplication();
        $input = $app->input;
        $mid   = $input->getInt('mid', 0);

        if ($mid <= 0) {
            return;
        }

        if (!$module = SearchHelper::getModuleById($mid)) {
            return;
        }

        JLoader::register('VmConfig', JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');

        VmConfig::loadConfig();
        VmConfig::loadJLang('com_virtuemart', true);

        $limit        = $input->getInt('limit', 6);
        $limitstart   = $input->getInt('limitstart', 0);
        $keyword      = $input->getString('keyword', false);
        $params       = new Registry($module->params);
        $products     = self::getSearchResults($keyword, $params);
        $currency     = CurrencyDisplay::getInstance();
        $showCategory = $params->get('show_category', 1);
        $showPrice    = $params->get('show_price', 1);
        $priceType    = $params->get('displayed_price_type', 'salesPrice');
        $results      = [];
        $count        = 0;
        $end          = true;

        if (!empty($products)) {
            $count = count($products);

            if ($count >= $limit) {
                $end = false;
            }

            foreach ($products as $product) {
                $product->categoryNames = !empty($product->categories) ? SearchHelper::getCategoryNames($product->categories) : [];

                ob_start();
                require ModuleHelper::getLayoutPath('mod_vpprime_ajax_search', 'result');
                $results[] = ob_get_clean();
            }
        }

        $data = [
            'query'       => $keyword,
            'suggestions' => $results,
            'limitstart'  => $limitstart,
            'limit'       => $limit,
            'count'       => $count,
            'end'         => $end
        ];

        return self::outputAjax($data);
    }

    private static function getSearchResults($keyword, $params)
    {
        $app         = Factory::getApplication();
        $input       = $app->input;
        $category_id = $input->getInt('virtuemart_category_id', 0);
        $products    = [];

        if (!$keyword) {
            return $products;
        }

        $input->set('virtuemart_category_id', -1);
        $input->set('view', 'ajaxsearch');

        $model = VmModel::getModel('product');

        $product_ids = $model->sortSearchListQuery(true, $category_id);

        if (!empty($product_ids)) {
            $products = $model->getProducts($product_ids);

            if ($params->get('show_images', 1)) {
                $model->addImages($products, 1);
            }
        }

        return $products;
    }

    private static function outputAjax($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();
    }
}
