<?php
/**
 * Cookie management helper functions.
 *
 * @package Awesomemotive\Rewardswp\Helpers
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Helpers;

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

use Awesomemotive\Rewardswp\Settings\Options\Referrals\CookieExpirationOption;


/**
 * Cookie Helper.
 *
 * @since 1.0.0
 */
class CookieHelper {
	/**
	 * Get the cookie domain.
	 *
	 * @since 1.0.0
	 * @return string Hostname (host.tld).
	 */
	public function get_cookie_domain(): string {
		return empty( COOKIE_DOMAIN )
			? wp_parse_url( get_home_url(), PHP_URL_HOST )
			: COOKIE_DOMAIN;
	}

	/**
	 * Get the cookie path.
	 *
	 * @since 1.0.0
	 * @return string Path.
	 */
	public function get_cookie_path(): ?string {
		return COOKIEPATH;
	}

	/**
	 * Set a cookie with expiration in days.
	 *
	 * @param string   $name     Cookie name.
	 * @param string   $value    Cookie value.
	 * @param int|null $days     Number of days until expire. If not provided will be used the value from settings
	 * @param bool     $override Whether to overwrite the previous cookie, if exists.
	 *
	 * @return void
	 */
	public function set_cookie( string $name, string $value, ?int $days = null, bool $override = false ): void {

		// Ignore cookie creation in case it already exists and override is set to false.
		if ( ! $override && isset( $_COOKIE[ $name ] ) ) {
			return;
		}

		setcookie(
			$name,
			$value,
			time() + ( ( $days ?? get_option_value( CookieExpirationOption::class ) ) * DAY_IN_SECONDS ),
			$this->get_cookie_path(),
			$this->get_cookie_domain()
		);
	}

	/**
	 * Retrieve the value of a cookie using filter_input.
	 *
	 * @param string $name The name of the cookie.
	 *
	 * @since 1.0.0
	 *
	 * @return string|null The sanitized value of the cookie, or null if not set.
	 */
	public function get_cookie( string $name ): ?string {
		return filter_input( INPUT_COOKIE, $name, FILTER_SANITIZE_FULL_SPECIAL_CHARS ) ?: null;
	}
}
