<?php

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

class AIEO_One_Tap {

    
    private static $instance = null;

    public static function instance() {
        if (self::$instance === null) { self::$instance = new self(); }
        return self::$instance;
    }

    public static function register() {
        add_action('wp_footer', array(self::instance(), 'print_loader'), 30);
    }

    public function print_loader() {
        if (is_admin()) { return; }
        
        
        
        if (defined('AIEO_RUNTIME_OWNS_ONE_TAP')) { return; }
        
        $cs = get_option('aieo_consent_settings', array());
        if (($cs['one_tap_enabled'] ?? '') !== 'yes') { return; }
        $client_id = $this->google_client_id();
        if ($client_id === '') { return; }

        $cfg = array(
            'clientId' => $client_id,
            'endpoint' => esc_url_raw(rest_url('aieo/v1/sso/onetap')),
        );
        $ver = defined('AIEO_VERSION') ? AIEO_VERSION : '1';
        $src = plugins_url('assets/js/aieo-one-tap.js', AIEO_FILE) . '?v=' . rawurlencode($ver);
        
        
        
        if (class_exists('AIEO_Asset_Min') && !(defined('SCRIPT_DEBUG') && SCRIPT_DEBUG)) {
            $src = AIEO_Asset_Min::rewrite($src);
        }
        echo "\n<script>window.aieoOneTap=" . wp_json_encode($cfg) . ";</script>\n";
        echo '<script src="' . esc_url($src) . '" async defer></script>' . "\n";
    }

    
    private function google_client_id() {
        if (!class_exists('AIEO_SSO_Buttons_Data')) { return ''; }
        $settings = AIEO_SSO_Buttons_Data::get_settings();
        $g = isset($settings['providers']['google']) ? $settings['providers']['google'] : array();
        return isset($g['client_id']) ? trim((string) $g['client_id']) : '';
    }
}
