<?php
/**
 * @package         FireBox
 * @version         3.1.1 Pro
 * 
 * @author          FirePlugins <info@fireplugins.com>
 * @link            https://www.fireplugins.com
 * @copyright       Copyright © 2025 FirePlugins All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

namespace FireBox\Core\FB;

if (!defined('ABSPATH'))
{
	exit; // Exit if accessed directly.
}

class ClickTracker
{
	/**
	 * Factory
	 * 
	 * @var  \FPFramework\Base\Factory
	 */
	private $factory;

	/**
	 * Constructor
	 * 
	 * @param  \FPFramework\Base\Factory|null  $factory
	 */
	public function __construct($factory = null)
	{
		if (!$factory)
		{
			$factory = new \FPFramework\Base\Factory();
		}

		$this->factory = $factory;

		$this->maybeTrackClicks();
	}

	/**
	 * Track clicks from cookie data when available.
	 * 
	 * @return  void
	 */
	public function maybeTrackClicks()
	{
		if ((is_admin() && !wp_doing_ajax()) || wp_doing_cron())
		{
			return;
		}

		$cookie = 'firebox_clicks_tracker';
		if (!isset($_COOKIE[$cookie]))
		{
			return;
		}

		$clicks_data = json_decode(wp_unslash($_COOKIE[$cookie]), true);
		if (!$clicks_data || !is_array($clicks_data))
		{
			$this->clearCookie($cookie);
			return;
		}

		foreach ($clicks_data as $popup_id => $data)
		{
			if (!isset($data['box_log_id']) || !isset($data['clicks']) || !is_array($data['clicks']))
			{
				continue;
			}

			$box_log_id = intval($data['box_log_id']);
			if (!$box_log_id)
			{
				continue;
			}

			$existing_labels = $this->getExistingClickLabels($box_log_id);

			foreach ($data['clicks'] as $click)
			{
				if (!isset($click['label']))
				{
					continue;
				}

				$label = sanitize_text_field($click['label']);
				if ($label === '' || in_array($label, $existing_labels, true))
				{
					continue;
				}

				$row = [
					'log_id' => $box_log_id,
					'event' => 'click',
					'event_source' => '',
					'event_label' => $label,
					'date' => $this->factory->getDate()->format('Y-m-d H:i:s')
				];

				firebox()->tables->boxlogdetails->insert($row);

				$existing_labels[] = $label;
			}
		}

		$this->clearCookie($cookie);
	}

	/**
	 * Retrieve existing click event labels for a log entry.
	 * 
	 * @param   int  $log_id
	 * 
	 * @return  array
	 */
	protected function getExistingClickLabels($log_id)
	{
		global $wpdb;

		$query = $wpdb->prepare(
			"SELECT event_label FROM {$wpdb->prefix}firebox_logs_details WHERE log_id = %d AND event = %s",
			$log_id,
			'click'
		);

		$labels = $wpdb->get_col($query);

		return is_array($labels) ? $labels : [];
	}

	/**
	 * Clear the tracking cookie after processing.
	 * 
	 * @param   string  $cookie
	 * 
	 * @return  void
	 */
	protected function clearCookie($cookie)
	{
		unset($_COOKIE[$cookie]);
		setcookie($cookie, '', time() - 3600, '/');
	}
}
