<?php if ( ! defined( 'ABSPATH' ) ) {exit;} // Exit if accessed directly.

/**
 * Codevz API monitor and block multiple API connections on each page refresh.
 * 
 * @since  5.5.0
 */
class Codevz_API_Monitor {

    use Codevz_Plus_Instance;

    private static array $blacklist = [
        'revslider',
        'essential-grid',
        'layer-slider',
        'wpbakery',
        'composer',
        'elementor',
    ];

    private static array $whitelist = [
		'admin-ajax.php',
		'wordpress',
		'cloudflare',
		'jetpack',
        'wpml',
		'license',
		'demo',
		'xtra',
		'codevz',
		'themetor',
		'register',
		'sign',
		'template',
		'download',
		'font',
		'pack',
		'mail',
		'code',
		'zoho',
		'account',
    ];

    public static function init() {
        add_filter( 'pre_http_request', [ __CLASS__, 'throttle' ], 10, 3 );
    }

    public static function throttle( $preempt, $args, $url ) {

        foreach ( self::$whitelist as $allowed ) {
            if ( Codevz_Plus::contains( $url, $allowed ) ) {
                return false;
            }
        }

        $is_blacklisted = false;

        foreach ( self::$blacklist as $blocked ) {
            if ( Codevz_Plus::contains( $url, $blocked ) ) {
                $is_blacklisted = true;
                break;
            }
        }

        if ( ! $is_blacklisted ) {
            return false;
        }

        $key = 'codevz_api_throttle_' . md5( strtok( $url, '?' ) );
        $now = time();

        $cooldown  = 6 * HOUR_IN_SECONDS;
        $locked_at = get_site_transient( $key );

        if ( $locked_at ) {
            $remaining = max( 0, $cooldown - ( $now - $locked_at ) );

            return new WP_Error(
                'codevz_api_throttled',
                'API blocked for next ' . $remaining . 's',
                [ 'seconds_left' => $remaining ]
            );
        }

        set_site_transient( $key, $now, $cooldown );

        return false;
    }

}
add_action( 'init', [ 'Codevz_API_Monitor', 'init' ] );