<?php
/**
 * Tracking service for cookies and referral visit tracking.
 *
 * @package RewardsWP
 */

namespace Awesomemotive\Rewardswp\Services;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Awesomemotive\Rewardswp\Models\Member;
use Awesomemotive\Rewardswp\Helpers\CookieHelper;
use Awesomemotive\Rewardswp\Models\Event;
use function Awesomemotive\Rewardswp\Helpers\get_member_by;
use function Awesomemotive\Rewardswp\Helpers\create_event;

class TrackingService {
	/**
	 * Cookie name for visit ID.
	 *
	 * @since 1.0.0
	 */
	const VISIT_ID_COOKIE_NAME = 'rewardswp_visit_id';

	/**
	 * Cookie name for advocate ID.
	 *
	 * @since 1.0.0
	 */
	const ADVOCATE_ID_COOKIE_NAME = 'rewardswp_advocate_id';

	/**
	 * Cookie helper instance.
	 *
	 * @since 1.0.0
	 *
	 * @var CookieHelper
	 */
	private CookieHelper $cookie_helper;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 *
	 * @param CookieHelper $cookie_helper Cookie Helper.
	 */
	public function __construct( CookieHelper $cookie_helper ) {
		$this->cookie_helper = $cookie_helper;
	}

	/**
	 * Track a visit.
	 *
	 * @since 1.0.0
	 *
	 * @param string $referral_code Advocate referral code.
	 * @param string $referrer_url  The referrer URL.
	 * @param string $landing_url   The landing URL.
	 *
	 * @return Event|null The event object if created or null otherwise.
	 */
	public function track_visit(
		string $referral_code,
		string $referrer_url = '',
		string $landing_url = ''
	): ?Event {
		$advocate = get_member_by( 'referral_code', $referral_code );

		if ( ! is_a( $advocate, Member::class ) ) {
			return null; // No advocate to track the event.
		}

		$event = create_event(
			[
				'member_id'    => $advocate->id,
				'referrer_url' => $referrer_url,
				'landing_url'  => $landing_url,
			]
		);

		if ( is_wp_error( $event ) ) {
			return null; // Could not create the event.
		}

		// Set cookies.
		$this->cookie_helper->set_cookie( self::VISIT_ID_COOKIE_NAME, $event->id );
		$this->cookie_helper->set_cookie( self::ADVOCATE_ID_COOKIE_NAME, $advocate->id );

		return $event;
	}

	/**
	 * The cookie name.
	 *
	 * @since 1.0.0
	 *
	 * @param string $cookie_name The name of the cookie.
	 *
	 * @return string|null The cookie value or null if can't find.
	 */
	public function get_cookie( string $cookie_name ): ?string {
		return $this->cookie_helper->get_cookie( $cookie_name );
	}
}
