<?php

declare(strict_types=1);

if (!defined('STICKY_REFERRAL_SESSION_KEY')) {
    define('STICKY_REFERRAL_SESSION_KEY', 'sticky_referral_code');
}

if (!defined('STICKY_REFERRAL_COOKIE_NAME')) {
    define('STICKY_REFERRAL_COOKIE_NAME', 'MEGAN28_REFERRAL');
}

if (!defined('STICKY_REFERRAL_COOKIE_DAYS')) {
    define('STICKY_REFERRAL_COOKIE_DAYS', 365);
}

if (!function_exists('stickyReferralNormalize')) {
    function stickyReferralNormalize($value): string
    {
        $value = strtoupper(trim((string) $value));

        return preg_match('/^[A-Z0-9]{6,20}$/', $value) === 1
            ? $value
            : '';
    }
}

if (!function_exists('stickyReferralCookieOptions')) {
    function stickyReferralCookieOptions(int $expiresAt): array
    {
        return [
            'expires' => $expiresAt,
            'path' => '/',
            'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off',
            'httponly' => true,
            'samesite' => 'Lax',
        ];
    }
}

if (!function_exists('stickyReferralStore')) {
    function stickyReferralStore(string $code): void
    {
        $code = stickyReferralNormalize($code);

        if ($code === '') {
            return;
        }

        $_SESSION[STICKY_REFERRAL_SESSION_KEY] = $code;

        setcookie(
            STICKY_REFERRAL_COOKIE_NAME,
            $code,
            stickyReferralCookieOptions(
                time() + (STICKY_REFERRAL_COOKIE_DAYS * 86400)
            )
        );

        $_COOKIE[STICKY_REFERRAL_COOKIE_NAME] = $code;
    }
}

if (!function_exists('stickyReferralCapture')) {
    function stickyReferralCapture(): string
    {
        $incomingCode = stickyReferralNormalize($_GET['ref'] ?? '');

        if ($incomingCode !== '') {
            stickyReferralStore($incomingCode);
            return $incomingCode;
        }

        $sessionCode = stickyReferralNormalize(
            $_SESSION[STICKY_REFERRAL_SESSION_KEY] ?? ''
        );

        if ($sessionCode !== '') {
            return $sessionCode;
        }

        $cookieCode = stickyReferralNormalize(
            $_COOKIE[STICKY_REFERRAL_COOKIE_NAME] ?? ''
        );

        if ($cookieCode !== '') {
            $_SESSION[STICKY_REFERRAL_SESSION_KEY] = $cookieCode;
            return $cookieCode;
        }

        return '';
    }
}

if (!function_exists('stickyReferralCurrent')) {
    function stickyReferralCurrent(): string
    {
        return stickyReferralCapture();
    }
}

stickyReferralCapture();
