<?php
/**
 * ============================================================================
 *  Stage 4b — mbe_redirect_handler.php
 *
 *  Catch-all PHP handler for motherboardexpress.com → GAHK redirect
 *
 *  由 .htaccess catch-all rule 觸發。每個 request 嚟到先：
 *    1. 攞 Request URI
 *    2. 主頁 special case (/ /index.php) → 301 GAHK_FALLBACK
 *    3. 查 _mbe_redirect_map.json (URL variants O(1) lookup)
 *    4. kind = redirect → 301 去 GAHK 對應 page
 *    5. kind = 410      → 410 Gone
 *    6. 全部 miss       → 410 Gone
 *
 *  特性（inherit PWD90 final 8 個 fix）：
 *    - JSON 用 static cache（每 request 只讀 1 次）
 *    - hashmap by URL O(1) lookup
 *    - URL variants：rawurldecode / rawurlencode / trailing slash / www variant
 *    - Fail-safe：JSON 缺失 → fallback 去 GAHK 首頁（唔好白屏）
 *    - 主頁 special case
 *    - Entry point guard（避免 require 時誤跑 redirect）
 *
 *  部署：上載呢個 file 去 /mbe_to_gahk_deploy/
 *  訪問 debug：?_debug=1
 * ============================================================================
 */

@ini_set('display_errors', '0');
error_reporting(E_ERROR | E_PARSE);

const MBE_MAP_FILE      = __DIR__ . '/data/_mbe_redirect_map.json';
const MBE_GAHK_FALLBACK = 'https://www.gahk.com.hk/';
const MBE_BASE_HOSTS    = ['www.motherboardexpress.com', 'motherboardexpress.com'];

/** 為一個 URL 生成多種 normalized variants */
function mbe_h_url_variants($url) {
    $out = [];
    $url = (string)$url;
    if ($url === '') return $out;

    $candidates = [$url];
    $dec = @rawurldecode($url);
    if ($dec !== false && $dec !== $url) $candidates[] = $dec;

    $parts = @parse_url($url);
    if (is_array($parts) && isset($parts['path'])) {
        $pathDec = @rawurldecode($parts['path']);
        $segs = explode('/', $pathDec);
        $segs = array_map('rawurlencode', $segs);
        $pathReEnc = implode('/', $segs);
        $built = ($parts['scheme'] ?? 'https') . '://' . ($parts['host'] ?? '') . $pathReEnc;
        if (isset($parts['query'])) $built .= '?' . $parts['query'];
        $candidates[] = $built;
        $candidates[] = $pathReEnc;
        $candidates[] = $pathDec;
        $candidates[] = $parts['path'];
    }

    foreach ($candidates as $c) {
        if ($c !== '') $out[$c] = true;
    }
    return array_keys($out);
}

function mbe_h_load_map() {
    static $cache = null;
    if ($cache !== null) return $cache;

    if (!file_exists(MBE_MAP_FILE) || !is_readable(MBE_MAP_FILE)) {
        $cache = ['rows_by_url' => [], 'rows_by_path' => [], 'count' => 0];
        return $cache;
    }
    $raw = @file_get_contents(MBE_MAP_FILE);
    $j = @json_decode($raw, true);
    if (!is_array($j) || empty($j['rows'])) {
        $cache = ['rows_by_url' => [], 'rows_by_path' => [], 'count' => 0];
        return $cache;
    }

    $by_url = [];
    $by_path = [];
    foreach ($j['rows'] as $r) {
        if (empty($r['url'])) continue;
        foreach (mbe_h_url_variants($r['url']) as $v) $by_url[$v] = $r;
        $p = @parse_url($r['url'], PHP_URL_PATH);
        if ($p !== null && $p !== '' && $p !== false) {
            $pVariants = [$p, @rawurldecode($p), rtrim($p, '/'), rtrim(@rawurldecode($p), '/')];
            foreach ($pVariants as $pv) {
                if ($pv !== '' && $pv !== false) $by_path[$pv] = $r;
            }
        }
    }
    $cache = ['rows_by_url' => $by_url, 'rows_by_path' => $by_path, 'count' => count($j['rows'])];
    return $cache;
}

function mbe_h_normalize_request() {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'www.motherboardexpress.com';
    $uri = $_SERVER['REQUEST_URI'] ?? '/';
    $q = strpos($uri, '?');
    if ($q !== false) $uri = substr($uri, 0, $q);
    return [
        'full' => $scheme . '://' . $host . $uri,
        'path' => $uri,
        'host' => $host,
    ];
}

function mbe_h_send_410() {
    http_response_code(410);
    header('Content-Type: text/html; charset=utf-8');
    header('X-Robots-Tag: noindex');
    header('X-Redirect-By: mbe-handler');
    echo "<!DOCTYPE html><html><head><meta charset='utf-8'><title>410 Gone</title>";
    echo "<style>body{font-family:system-ui,sans-serif;max-width:600px;margin:80px auto;padding:0 20px;text-align:center;color:#333}h1{color:#c00}</style>";
    echo "</head><body>";
    echo "<h1>410 Gone</h1>";
    echo "<p>此頁面已永久移除。</p>";
    echo "<p>若您搵維修服務，請瀏覽 <a href='" . MBE_GAHK_FALLBACK . "'>維修快</a>（全港 5 大維修 silo）。</p>";
    echo "</body></html>";
    exit;
}

function mbe_h_send_301($target) {
    if (empty($target)) $target = MBE_GAHK_FALLBACK;
    http_response_code(301);
    header('Location: ' . $target);
    header('Cache-Control: max-age=86400');
    header('X-Redirect-By: mbe-handler');
    exit;
}

/** 確認呢個 file 係 .htaccess catch-all 觸發嘅 entrypoint */
function mbe_h_is_handler_entrypoint(): bool {
    $bn = 'mbe_redirect_handler.php';
    $sn = (string)($_SERVER['SCRIPT_NAME'] ?? '');
    if ($sn !== '' && substr($sn, -strlen($bn)) === $bn) return true;
    $sf = (string)($_SERVER['SCRIPT_FILENAME'] ?? '');
    if ($sf !== '' && basename($sf) === $bn) return true;
    return false;
}

// ============================================================================
//  Main
// ============================================================================
if (!mbe_h_is_handler_entrypoint()) return;

$req = mbe_h_normalize_request();
$map = mbe_h_load_map();
$debug = !empty($_GET['_debug']);

// Debug：show lookup 過程，唔做 redirect
if ($debug) {
    header('Content-Type: text/html; charset=utf-8');
    echo "<!DOCTYPE html><html><head><meta charset='utf-8'><title>MBE Handler Debug</title>";
    echo "<style>body{font-family:system-ui,monospace;max-width:1200px;margin:20px auto;padding:0 20px}";
    echo "table{border-collapse:collapse;margin:10px 0;width:100%}td{padding:6px;border-bottom:1px solid #eee;vertical-align:top;font-size:12px}";
    echo "th{background:#f0f0f0;text-align:left;padding:8px}.ok{color:#0a0;font-weight:600}.err{color:#c00;font-weight:600}";
    echo "</style></head><body><h1>🔍 MBE Handler Debug</h1>";

    echo "<h2>1. Request</h2><table>";
    foreach (['REQUEST_URI','HTTP_HOST','HTTPS','SCRIPT_NAME','PHP_SELF','REQUEST_METHOD','QUERY_STRING'] as $k) {
        echo "<tr><th>{$k}</th><td>" . htmlspecialchars((string)($_SERVER[$k] ?? '(empty)')) . "</td></tr>";
    }
    echo "<tr><th>computed full</th><td>" . htmlspecialchars($req['full']) . "</td></tr>";
    echo "<tr><th>computed path</th><td>" . htmlspecialchars($req['path']) . "</td></tr>";
    echo "</table>";

    echo "<h2>2. Map</h2><table>";
    echo "<tr><th>JSON 存在</th><td>" . (file_exists(MBE_MAP_FILE) ? '<span class="ok">✓</span>' : '<span class="err">✗</span>') . "</td></tr>";
    if (file_exists(MBE_MAP_FILE)) {
        echo "<tr><th>JSON size</th><td>" . round(filesize(MBE_MAP_FILE)/1024,1) . " KB</td></tr>";
    }
    echo "<tr><th>Rows</th><td>{$map['count']}</td></tr>";
    echo "<tr><th>by_url variants</th><td>" . count($map['rows_by_url']) . "</td></tr>";
    echo "<tr><th>by_path variants</th><td>" . count($map['rows_by_path']) . "</td></tr>";
    echo "</table>";

    echo "<h2>3. Lookup 試算</h2><table>";
    foreach (mbe_h_url_variants($req['full']) as $v) {
        $hit = isset($map['rows_by_url'][$v]) ? '<span class="ok">✓ HIT</span>' : '<span class="err">— miss</span>';
        echo "<tr><td>{$hit}</td><td>" . htmlspecialchars($v) . "</td></tr>";
    }
    foreach ([$req['path'], @rawurldecode($req['path']), rtrim($req['path'],'/'), rtrim(@rawurldecode($req['path']),'/')] as $pv) {
        if ($pv === '' || $pv === false) continue;
        $hit = isset($map['rows_by_path'][$pv]) ? '<span class="ok">✓ HIT (path)</span>' : '<span class="err">— miss (path)</span>';
        echo "<tr><td>{$hit}</td><td>" . htmlspecialchars($pv) . "</td></tr>";
    }
    echo "</table>";
    echo "<p><strong>用法：</strong>呢個 page 應該被 .htaccess catch-all 觸發。直接 ?_debug=1 等於 hit 主頁。</p>";
    echo "<p><strong>Test：</strong>訪問 <code>/keyword?_debug=1</code> show 試算結果。</p>";
    echo "</body></html>";
    exit;
}

// 0. 主頁 special case
if ($req['path'] === '/' || $req['path'] === '' || $req['path'] === '/index.php' || $req['path'] === '/index.html') {
    mbe_h_send_301(MBE_GAHK_FALLBACK);
}

// 1. Try all variants of full URL
foreach (mbe_h_url_variants($req['full']) as $v) {
    if (isset($map['rows_by_url'][$v])) {
        $r = $map['rows_by_url'][$v];
        if (($r['kind'] ?? '') === '410') mbe_h_send_410();
        mbe_h_send_301($r['target'] ?? '');
    }
}

// 2. Host variants
foreach (MBE_BASE_HOSTS as $h) {
    $alt = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http') . '://' . $h . $req['path'];
    foreach (mbe_h_url_variants($alt) as $v) {
        if (isset($map['rows_by_url'][$v])) {
            $r = $map['rows_by_url'][$v];
            if (($r['kind'] ?? '') === '410') mbe_h_send_410();
            mbe_h_send_301($r['target'] ?? '');
        }
    }
}

// 3. Path-only match
foreach ([$req['path'], @rawurldecode($req['path']), rtrim($req['path'], '/'), rtrim(@rawurldecode($req['path']), '/')] as $pv) {
    if ($pv === '' || $pv === false) continue;
    if (isset($map['rows_by_path'][$pv])) {
        $r = $map['rows_by_path'][$pv];
        if (($r['kind'] ?? '') === '410') mbe_h_send_410();
        mbe_h_send_301($r['target'] ?? '');
    }
}

// 4. 都搵唔到 → 410 Gone
mbe_h_send_410();
