<?php
/*
 * Software Name: Eorisis Pixels
 * Software URI: https://eorisis.com/shop/software/joomla/pixels
 * Author: Eorisis
 * Author URI: https://eorisis.com
 * Copyright: Copyright (C) 2011-2025 EORISIS. All Rights Reserved.
 * License: GNU General Public License version 2; See https://eorisis.com/gpl
 * Terms of Service: https://eorisis.com/tos
 */
namespace com_eorisis_pixels\framework\lib\core\model;
\defined('_JEXEC') or die;

use com_eorisis_pixels\framework\lib\core\controller\request;
use com_eorisis_pixels\framework\lib\core\cms\language as cms_language;
use com_eorisis_pixels\framework\lib\core\cms\head as cms_head;
use com_eorisis_pixels\framework\lib\core\model\language as language_model;
use com_eorisis_pixels\framework\lib\core\model\extension;
use com_eorisis_pixels\framework\lib\core\view\javascript;

class metapixel
{
	private static $abort = false;
	private static $pixel_id = 0;

	// -------------------------------------------------

	public function __construct() {}

	// --------------------------------------------------

	public function set_head(array $item) : bool
	{
		self::$pixel_id = $item['pixel_id'];
		self::$abort = !self::$pixel_id;
		extension::$abort = self::$abort;

		if (!self::$pixel_id)
		{
			return false;
		}

		// DNT / Opt-Out
		$optout = $item['integrate_consent'] && $this->consent_opted_out();
		$is_dnt = $item['dnt'] && request::header('HTTP_DNT');

		if ($optout or $is_dnt)
		{
			$option = $optout ? 'optout' : 'dnt';

			$tags = $this->get_tags($option);
			$html = "\n".$tags['start']."\n";
			cms_head::add_custom_element($html);

			self::$abort = true;
			extension::$abort = true;
			return false;
		}

		$agent = $item['agent'] ? ", {}, {agent: '".$item['agent']."'}" : '';

		$script  = "\t\t!function(f,b,e,v,n,t,s)\n";
		$script .= "\t\t{if(f.fbq)return;n=f.fbq=function(){n.callMethod?\n";
		$script .= "\t\tn.callMethod.apply(n,arguments):n.queue.push(arguments)};\n";
		$script .= "\t\tif(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';\n";
		$script .= "\t\tn.queue=[];t=b.createElement(e);t.async=!0;\n";
		$script .= "\t\tt.src=v;s=b.getElementsByTagName(e)[0];\n";
		$script .= "\t\ts.parentNode.insertBefore(t,s)}(window,document,'script',\n";
		$script .= "\t\t'https://connect.facebook.net/en_US/fbevents.js');\n";
		$script .= !$item['autoconfig'] ? "\t\tfbq('set', 'autoConfig', false, '".self::$pixel_id."');\n" : '';
		$script .= "\t\tfbq('init', '".self::$pixel_id."'".$agent.");\n";
		$script .= "\t\tfbq('track', 'PageView');";

		$script = javascript::script_inline("\n".$script."\n\t");

		$tags = $this->get_tags();
		$data = "\n".$tags['start']."\t".$script."\t".$tags['end']."\n";
		cms_head::add_custom_element($data);
		return true;
	}

	// --------------------------------------------------

	public function get_img() : string
	{
		if (self::$abort or !self::$pixel_id)
		{
			return '';
		}

		$img = '<img src="https://www.facebook.com/tr?id='.self::$pixel_id.'&ev=PageView&noscript=1" alt="fbpx" height="1" width="1" style="display:none" />';
		$tags = $this->get_tags();
		return "\n".$tags['start'].'<noscript>'.$img."</noscript>\n".$tags['end']."\n";
	}

	// --------------------------------------------------

	private function get_tags(string $option = '')
	{
		static $arr = null;
		if ($arr !== null)
		{
			return $arr;
		}

		language_model::jload('pub');

		$txt = cms_language::text('EO_METAPIXEL_TAG');
		$key = $option && $option == 'optout' ? 'EO_OPTOUT_TAG' : 'EO_DNT_OPTOUT_TAG';

		$arr = [];
		$arr['start']  = "<!-- ".$txt." -->\n";
		$arr['start'] .= $option ? "\t<!-- ".cms_language::text($key)." -->\n" : '';
		$arr['end'] = "<!-- /".$txt." -->";
		return $arr;
	}

	// --------------------------------------------------

	private function consent_opted_out() : bool
	{
		// Integration
		// Check for file first or we get a warning
		if (!\is_file(JPATH_ADMINISTRATOR.'/components/com_eorisis_consent/framework/lib/core/model/metapixel.php'))
		{
			return false;
		}
		
		if (!\class_exists('com_eorisis_consent\framework\lib\core\model\metapixel', true))
		{
			return false;
		}

		$model = new \com_eorisis_consent\framework\lib\core\model\metapixel;
		if (\method_exists($model, 'get_state'))
		{
			return $model->get_state() == 0;
		}

		return false;
	}
}
