<?php
/**
 * @package    JBusinessDirectory
 *
 * @author CMSJunkie http://www.cmsjunkie.com
 * @copyright  Copyright (C) 2007 - 2021 CMSJunkie. All rights reserved.
 * @license   https://www.gnu.org/licenses/agpl-3.0.en.html
 */
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\Cache\CacheControllerFactoryInterface;

require_once JPATH_SITE.'/components/com_jbusinessdirectory/helpers/defines.php';
require_once HELPERS_PATH.'/utils.php';

JBusinessUtil::enqueueStyle('css/common.css');
JHtml::_('stylesheet', 'media/com_jbusinessdirectory/css/latest-module.css');
JHtml::_('stylesheet', 'modules/mod_jbusiness_listings/assets/style.css');
JHtml::_('script', 'modules/mod_jbusiness_listings/assets/js/script.js');

JHtml::_('jquery.framework', true, true);

JBusinessUtil::loadBaseScripts();
JBusinessUtil::loadMapScripts();
JBusinessUtil::setMenuItemId();

$appSettings = JBusinessUtil::getApplicationSettings();

JHtml::_('jquery.framework', true, true);

if ($params->get('viewtype') == 'slider' || $params->get('viewtype') == 'slider_2' || $params->get('viewtype') == 'tier') {
	JBusinessUtil::enqueueStyle('libraries/slick/slick.css');
	JBusinessUtil::enqueueScript('libraries/slick/slick.js');
}

if ($appSettings->enable_ratings) {
	JBusinessUtil::enqueueStyle('libraries/star-rating/star-rating.css');
	JBusinessUtil::enqueueScript('libraries/star-rating/star-rating.js');
}

JBusinessUtil::enqueueStyle('libraries/modal/jquery.modal.css');
JBusinessUtil::enqueueScript('libraries/modal/jquery.modal.js');

require_once HELPERS_PATH.'/translations.php';

// Include the syndicate functions only once
require_once __DIR__ . '/helper.php';

JBusinessUtil::includeCSSLibraries();
JBusinessUtil::loadSiteLanguage();

//load items through cache mechanism
$cache = Factory::getCache('mod_jbusiness_listings', '');
$key = 'mod_jbusiness_listings'.$module->id;
if ($cache->contains($key)) {
	$items = $cache->get($key);
} else {
	$items = modJBusinessListingsHelper::getList($params);
	$cache->store($items, $key);
}

if (!empty($items)) {
	foreach ($items as $company) {
		if (GET_DATA_FROM_YELP) {
			$yelpData = JBusinessUtil::getYelpData($company->yelp_id, false);
			if (isset($yelpData->error) || empty($company->yelp_id)) {
				$company->review_score = 0;
			} else {
				$company->review_score = $yelpData->rating;
			}
		}
	}
}

$newTab = ($appSettings->open_listing_on_new_tab)?" target='_blank'":"";
$jsSettings = JBusinessUtil::addJSSettings();
$jsSettings->isProfile = 1;

$token = rand(10, 1000);

if (!defined('JBD_UTILS_LOADED')) {
	$document  = JFactory::getDocument();
	$document->addScriptDeclaration('
		window.addEventListener("load",function() {
		    jbdUtils.setProperties(' . json_encode($jsSettings) . ');
		});
	');
	define('JBD_UTILS_LOADED', 1);
}

$document  = JFactory::getDocument();
$campaignCall = "";
$campaignCallClass = "";
if (!empty($params->get('plan')) && !empty($params->get('only_campaign'))) {
	$campaignCallClass = 'campaignCall';
	$campaignCall =
		"
            var campaignUrl = jbdUtils.getAjaxUrl('decreaseCampaignBudget', 'campaign', 'managecampaign');
            var planId = '".$params->get('plan')."';

            jQuery.ajax({
                type:'GET',
                url: campaignUrl,
                data: { planId: planId, companyId: companyId },
                dataType: 'json',
                cache: false,
                success: function(data) {
                    console.log(data);
                }
            });
        ";
}
$document->addScriptDeclaration("  
	window.addEventListener('load',function() {
        jQuery('.campaignCall').on('click', function() {
          companyId = jQuery(this).attr('data-companyId');
          ".$campaignCall."
        });
    });
");

if ($appSettings->enable_multilingual) {
	JBusinessDirectoryTranslations::updateBusinessListingsTranslation($items);
	JBusinessDirectoryTranslations::updateBusinessListingsSloganTranslation($items);
}

$moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));

$backgroundCss="";
if ($params->get('backgroundColor')) {
	$backgroundCss = "background-color:".$params->get('backgroundColor').";";
}

$borderCss="";
if ($params->get('borderColor')) {
	$borderCss="border: 1px solid ".$params->get('borderColor').";";
}

$menuItemId ="";
if ($params->get('mItemId')) {
	$menuItemId="&Itemid=".$params->get('mItemId');
}
$categoryParam = "";
$categoriesIds = $params->get('categoryIds');
if (isset($categoriesIds) && count($categoriesIds)>0 && $categoriesIds[0]!= 0 && $categoriesIds[0]!= "") {
	$categoryParam="&categorySearch=".$categoriesIds[0];
}

$viewAllLink = JRoute::_('index.php?option=com_jbusinessdirectory&view=search'.$menuItemId.$categoryParam);

$jinput = JFactory::getApplication()->input;
$geoLocationParams = "";
$latitude = $jinput->get("latitude");
$longitude = $jinput->get("longitude");

if (!empty($latitude)) {
	$geoLocationParams = "?geo-latitude=$latitude&geo-longitude=$longitude&geolocation=1&radius=50";
}

$span = $params->get('layout-type')=="vertical"?"col-12":$params->get('phoneGridOption', 'col-12').' '.$params->get('tabletGridOption', 'col-md-6').' '.$params->get('desktopGridOption', "col-lg-4");

require JModuleHelper::getLayoutPath('mod_jbusiness_listings', "default_".$params->get('viewtype', "simple"));
