<?php
/*
Plugin Name: TB2X Firewall
Description: WordPress firewall die verbindt met TB2X cloud (tb2x.com) voor IP/country blocking.
Version: 1.1
Author: TB2X
*/
if (!defined('ABSPATH')) { exit; }

add_action('init', 'tb2x_firewall_check', 0);

function tb2x_firewall_check() {
    static $checked = false;
    if ($checked) return;
    $checked = true;

    if (is_user_logged_in()) return;
    if (get_option('firewall_enabled', '1') !== '1') return;

    $agent       = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $ipToCheck   = $_SERVER['REMOTE_ADDR'] ?? '';
    $countryCode = $_SERVER['HTTP_GEOIP_COUNTRY_CODE'] ?? ($_SERVER['GEOIP_COUNTRY_CODE'] ?? 'N/A');

    $scheme  = (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') ? 'http' : 'https';
    $host    = $_SERVER['HTTP_HOST'] ?? '';
    $uri     = $_SERVER['REQUEST_URI'] ?? '/';
    $website = $scheme . '://' . $host . $uri;

    if ($ipToCheck === '' || $host === '') return;

    $url = 'https://www.tb2x.com/admin/firewall.php?' . http_build_query([
        'ip'      => $ipToCheck,
        'country' => $countryCode,
        'website' => $website,
        'agent'   => $agent,
    ]);

    $response = tb2x_make_curl_request($url, 8);

    // fail-open if TB2X unreachable
    if (!$response || !is_array($response)) return;

    if (!empty($response['blocked'])) {
        wp_redirect('https://www.google.com', 302);
        exit;
    }
}

function tb2x_make_curl_request($url, $timeout = 10) {
    if (!function_exists('curl_init')) return null;

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 4);

    $response = curl_exec($ch);
    if (curl_errno($ch)) { curl_close($ch); return null; }

    $httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode !== 200 || !$response) return null;

    $data = json_decode($response, true);
    if (json_last_error() !== JSON_ERROR_NONE) return null;

    return $data;
}