<?php
/**
 * ReferralLink.php
 *
 * The ReferralLink class file for Wooecho Rewards.
 * This file handles the referral link functionality for the plugin,
 * allowing users to share links and apply discounts based on referral codes.
 *
 * @package ECRE
 * @since   1.0.0
 */

namespace ECRE;

if ( ! class_exists( 'Ecre_ReferralLink' ) ) {
	/**
	 * Class ReferralLink
	 *
	 * Handles the referral link functionality, including setting referral cookies,
	 * applying discounts, and clearing referral information.
	 *
	 * @package ECRE
	 * @since   1.0.0
	 */
	class Ecre_ReferralLink {
		/**
		 * Initializes referral link functionality by hooking methods to WordPress actions.
		 *
		 * @since 1.0.0
		 */
		public function __construct() {
			add_action( 'template_redirect', array( $this, 'ecre_handle_referral_link' ) );
			add_action( 'woocommerce_add_to_cart', array( $this, 'ecre_apply_referral_discount_with_link' ) );
			add_action( 'woocommerce_thankyou', array( $this, 'ecre_set_discount_used_cookie' ) );
		}

		/**
		 * Handles referral link processing by capturing referral code and setting it in a cookie.
		 *
		 * If a "ref" parameter is found in the URL, stores the referral code in a cookie
		 * for 6 months and redirects to the shop page.
		 *
		 * @since 1.0.0
		 */
		public function ecre_handle_referral_link() {
			$referral_coupon = filter_input( INPUT_GET, 'ref' );

			if ( ! empty( $referral_coupon ) ) {

				// Check if a cookie for this specific referral coupon already exists.
				if ( ! isset( $_COOKIE[ 'ecre_referral_used_' . $referral_coupon ] ) ) {
					// Store referrer ID in a cookie for 6 months.
					setcookie( 'ecre_referral_coupon', $referral_coupon, time() + ( 30 * DAY_IN_SECONDS ), COOKIEPATH, COOKIE_DOMAIN );

					// Redirect to shop page.
					wp_safe_redirect( home_url( '/shop' ) );
					exit;
				} else {
					// Redirect to shop page.
					wp_safe_redirect( home_url( '/shop' ) );
					exit;
				}
			} else {
				return;
			}
		}

		/**
		 * Applies the referral discount using the coupon code stored in the referral cookie.
		 *
		 * Checks if a valid referral cookie is set and, if so, applies the corresponding coupon
		 * to the WooCommerce cart unless it is already applied and has not been used.
		 *
		 * @since 1.0.0
		 */
		public function ecre_apply_referral_discount_with_link() {
			if ( isset( $_COOKIE['ecre_referral_coupon'] ) && ! empty( $_COOKIE['ecre_referral_coupon'] ) ) {
				$coupon_code = sanitize_text_field( wp_unslash( $_COOKIE['ecre_referral_coupon'] ) );

				// Check if this referral discount has already been used.
				if ( ! isset( $_COOKIE[ 'ecre_referral_used_' . $coupon_code ] ) && ! WC()->cart->has_discount( $coupon_code ) ) {
					// Force cart calculation before applying coupon to ensure totals are available.
					if ( ! WC()->cart->is_empty() ) {
						// Set a flag to prevent infinite loops during coupon validation.
						if ( ! did_action( 'woocommerce_before_calculate_totals' ) ) {
							WC()->cart->calculate_totals();
						}
					}

					// Apply the coupon.
					WC()->cart->apply_coupon( $coupon_code );
				}
			} else {
				return;
			}
		}

		/**
		 * Sets a unique cookie to track that the referral coupon has been used.
		 *
		 * This function sets a cookie specific to the referral code after the first purchase,
		 * ensuring the coupon is not reused with the same referral link.
		 *
		 * @param int $order_id The ID of the completed order.
		 * @since 1.0.0
		 */
		public function ecre_set_discount_used_cookie( $order_id ) {
			if ( isset( $_COOKIE['ecre_referral_coupon'] ) ) {
				$coupon_code = sanitize_text_field( wp_unslash( $_COOKIE['ecre_referral_coupon'] ) );

				// Set a cookie to mark this specific referral code as used, valid for 6 months.
				setcookie( 'ecre_referral_used_' . $coupon_code, 'yes', time() + ( 6 * MONTH_IN_SECONDS ), COOKIEPATH, COOKIE_DOMAIN );

				// Clear the temporary referral coupon cookie.
				setcookie( 'ecre_referral_coupon', '', time() - 3600, COOKIEPATH, COOKIE_DOMAIN );
			}
		}
	}
}
