<?php
/**
 * scanner.php — Dual Standard Scanner
 * Wraps index.html with domain pre-population + brand switching
 * AT 2026-04-05 | CC | NO nginx, NO config, NO restart
 * PTF-156: Rootz reference removed
 * Backup: scanner.php.bak-[timestamp] created by deploy script
 */

$domain = isset($_GET['domain']) ? trim($_GET['domain']) : '';
$domain = preg_replace('#^https?://#', '', $domain);
$domain = rtrim($domain, '/');
if (!empty($domain) && !preg_match('/^[a-zA-Z0-9][a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}$/', $domain)) {
    $domain = '';
}
$domainSafe   = htmlspecialchars($domain, ENT_QUOTES, 'UTF-8');
$domainJs     = addslashes($domain);

// Read index.html from same directory
$html = file_get_contents(__DIR__ . '/index.html');
if ($html === false) {
    http_response_code(500);
    echo 'Scanner unavailable.';
    exit;
}

// PTF-156: Remove Rootz reference — AI Discovery Standard only
$html = str_replace(
    'Rootz v1.2 · Open source baseline',
    'AI Discovery Standard v1.2',
    $html
);

// MIUSA brand swap when served from home.miusa.one
$host = $_SERVER['HTTP_HOST'] ?? '';
if (strpos($host, 'miusa') !== false) {
    $html = str_replace(
        'AI Authority Scanner — Verity One Ltd. | TRUTH MATTERS®',
        'AI Authority Scanner — Made in USA Inc. | OTC: USDW',
        $html
    );
    $html = str_replace(
        'Is AI getting your business<br>wrong?',
        'Is AI getting your business<br>wrong?',
        $html
    );
    $html = str_replace(
        "href=\"https://wk.verity.one/shop/category/ai-verification-compliance-1\"",
        "href=\"https://wk.miusa.one/certify\"",
        $html
    );
    $html = str_replace(
        'home.verity.one — TRUTH MATTERS®',
        'home.miusa.one — TRUST BUT CERTIFY™',
        $html
    );
    $html = str_replace(
        "source=home.verity.one",
        "source=home.miusa.one",
        $html
    );
}

// Auto-populate domain and trigger scan if ?domain= provided
if (!empty($domain)) {
    $autoScan = "
<script>
document.addEventListener('DOMContentLoaded', function() {
    var inp = document.getElementById('domainInput');
    if (inp) {
        inp.value = '" . $domainJs . "';
        setTimeout(function(){ if(typeof runScan === 'function') runScan(); }, 150);
    }
});
</script>";
    $html = str_replace('</body>', $autoScan . "\n</body>", $html);
}

// Set cache headers — 0 cache (live scan results)
header('Content-Type: text/html; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('X-Powered-By: Veritize AI Authority | TRUTH MATTERS®');

echo $html;
