<?php

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

function init_churnsolution_wall()
{
    if (is_admin() || ! is_user_logged_in()) return;

    $current_user = wp_get_current_user();

    $subscription_id = '';

    if (! class_exists('PMPro_Subscription')) return;

    $subscriptions = PMPro_Subscription::get_subscriptions_for_user($current_user->ID);

    if (! empty($subscriptions)) {
        foreach ($subscriptions as $sub) {
            $subscription_id = $sub->get_subscription_transaction_id();
            break;
        }
    }

    if (empty($subscription_id)) return;

    if (! class_exists('Churnsolution_Connection')) return;

    $connection = Churnsolution_Connection::get_connection();

    if (empty($connection)) return;

    $api_key = $connection->getApiKey();
    $app_id  = $connection->getAppId();

    if (empty($api_key) || empty($app_id)) return;

    $hash     = hash_hmac('sha256', $subscription_id, $api_key, true);
    $auth_key = bin2hex($hash);
?>
    <script>
        (function() {
            function runWallScript() {
                window.churnSolution?.checkWall(
                    <?php echo wp_json_encode($auth_key); ?>,
                    <?php echo wp_json_encode($subscription_id); ?>,
                    <?php echo wp_json_encode($app_id); ?>, {
                        softWall: false,
                        gracePeriodDays: 7,
                        handleDone: () => window.location.reload(),
                    }
                );
            }

            function onChurnSolutionLoad(callback, timeout = 10000, interval = 100) {
                const startTime = Date.now();
                const check = () => {
                    if (window.churnSolution) {
                        callback();
                    } else if (Date.now() - startTime < timeout) {
                        setTimeout(check, interval);
                    } else {
                        console.warn("Churn Solution script did not load in time.");
                    }
                };
                check();
            }

            onChurnSolutionLoad(runWallScript);
        })();
    </script>
<?php
}

add_action('wp_footer', 'init_churnsolution_wall', 20);
