<?php
namespace WoolentorPro\Modules\FreeShippingBar\Frontend;
use WooLentorPro\Traits\Singleton;
use WoolentorPro\Modules\FreeShippingBar\Free_Shipping_Bar_Pro;

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

class AB_Testing {
    use Singleton;

    private function __construct() {
        add_action( 'init', [ $this, 'assign_cookie' ], 5 );
    }

    /**
     * Assign the A/B variant cookie early (on 'init') before any output.
     * Only runs when A/B testing is enabled and the visitor has no cookie yet.
     */
    public function assign_cookie() {
        if ( Free_Shipping_Bar_Pro::setting( 'enable_ab_test', 'off' ) !== 'on' ) {
            return;
        }
        if ( isset( $_COOKIE[ Free_Shipping_Bar_Pro::AB_COOKIE ] ) ) {
            return;
        }
        $variant = ( random_int( 0, 1 ) === 1 ) ? 'b' : 'a';
        setcookie(
            Free_Shipping_Bar_Pro::AB_COOKIE,
            $variant,
            time() + ( 30 * DAY_IN_SECONDS ),
            COOKIEPATH,
            COOKIE_DOMAIN,
            is_ssl(),
            true
        );
        $_COOKIE[ Free_Shipping_Bar_Pro::AB_COOKIE ] = $variant;
    }

    /**
     * Return the A/B variant ('a' or 'b') for the current visitor.
     */
    public function get_variant() {
        if ( isset( $_COOKIE[ Free_Shipping_Bar_Pro::AB_COOKIE ] ) ) {
            return $_COOKIE[ Free_Shipping_Bar_Pro::AB_COOKIE ] === 'b' ? 'b' : 'a';
        }
        return ( random_int( 0, 1 ) === 1 ) ? 'b' : 'a';
    }
}
