<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';

$frontendHost = isset($_GET['host']) ? trim((string)$_GET['host']) : '';
$requestedSlug = isset($_GET['slug']) ? trim((string)$_GET['slug']) : '';
$normalizedHost = normalize_request_host($frontendHost);
$normalizedSlug = normalize_tag_slug($requestedSlug);
$domain = $normalizedHost !== '' ? find_domain_by_host($normalizedHost) : null;
$matchedTag = null;
$candidates = array();
$error = '';

try {
    if ($domain && $normalizedSlug !== '') {
        $matchedTag = find_tag_by_domain_and_slug((int)$domain['id'], $normalizedSlug);
        $pdo = db_connection();
        $stmt = $pdo->prepare('SELECT id, domain_id, name, slug, status, updated_at FROM tags WHERE domain_id = :domain_id ORDER BY id DESC LIMIT 200');
        $stmt->execute(array(':domain_id' => (int)$domain['id']));
        foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $item) {
            $storedSlug = isset($item['slug']) ? normalize_tag_slug((string)$item['slug']) : '';
            $derivedSlug = isset($item['name']) ? normalize_tag_slug((string)$item['name']) : '';
            $name = isset($item['name']) ? (string)$item['name'] : '';
            $isLikely = $normalizedSlug !== '' && (
                $storedSlug === $normalizedSlug ||
                $derivedSlug === $normalizedSlug ||
                strpos($storedSlug, $normalizedSlug) !== false ||
                strpos($normalizedSlug, $storedSlug) !== false ||
                strpos($derivedSlug, $normalizedSlug) !== false ||
                strpos($normalizedSlug, $derivedSlug) !== false ||
                ($name !== '' && mb_stripos($name, $requestedSlug) !== false)
            );
            if ($isLikely) {
                $candidates[] = array(
                    'id' => isset($item['id']) ? (int)$item['id'] : 0,
                    'name' => $name,
                    'stored_slug' => $storedSlug,
                    'derived_slug' => $derivedSlug,
                    'status' => isset($item['status']) ? (string)$item['status'] : '',
                    'updated_at' => isset($item['updated_at']) ? (string)$item['updated_at'] : ''
                );
            }
        }
    }
} catch (Exception $e) {
    $error = $e->getMessage();
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tag 调试</title>
    <style>
        body{margin:0;font-family:"PingFang SC","Microsoft YaHei",sans-serif;background:#f8fafc;color:#0f172a}
        .wrap{max-width:1100px;margin:0 auto;padding:24px}
        h1{margin:0 0 20px;font-size:28px}
        form,.card{background:#fff;border:1px solid #e2e8f0;border-radius:16px;padding:18px 20px;margin-bottom:18px}
        label{display:block;font-size:13px;color:#475569;margin-bottom:6px}
        input{width:100%;padding:10px 12px;border:1px solid #cbd5e1;border-radius:10px;margin-bottom:14px;font-size:14px;box-sizing:border-box}
        button{border:0;background:#2563eb;color:#fff;padding:10px 16px;border-radius:10px;font-size:14px;cursor:pointer}
        .grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
        .mono{font-family:Consolas,Monaco,monospace;word-break:break-all}
        table{width:100%;border-collapse:collapse}
        th,td{text-align:left;padding:10px 8px;border-top:1px solid #e2e8f0;font-size:14px;vertical-align:top}
        th{color:#475569;font-weight:600}
        .empty{color:#94a3b8}
        .ok{color:#15803d;font-weight:700}
        .bad{color:#b91c1c;font-weight:700}
        @media (max-width: 860px){.grid{grid-template-columns:1fr}}
    </style>
</head>
<body>
<div class="wrap">
    <h1>Tag 调试页</h1>
    <form method="get">
        <label for="host">前端域名</label>
        <input id="host" name="host" value="<?php echo e($frontendHost); ?>" placeholder="例如 test001.com">
        <label for="slug">Tag slug</label>
        <input id="slug" name="slug" value="<?php echo e($requestedSlug); ?>" placeholder="例如 wpsquchuguanggaofuwu">
        <button type="submit">开始调试</button>
    </form>

    <?php if ($error !== ''): ?>
    <div class="card bad"><?php echo e($error); ?></div>
    <?php endif; ?>

    <div class="grid">
        <div class="card">
            <h2>请求信息</h2>
            <p><strong>输入域名：</strong> <span class="mono"><?php echo e($frontendHost); ?></span></p>
            <p><strong>标准域名：</strong> <span class="mono"><?php echo e($normalizedHost); ?></span></p>
            <p><strong>输入 slug：</strong> <span class="mono"><?php echo e($requestedSlug); ?></span></p>
            <p><strong>标准 slug：</strong> <span class="mono"><?php echo e($normalizedSlug); ?></span></p>
        </div>
        <div class="card">
            <h2>域名命中</h2>
            <?php if ($domain): ?>
                <p><strong>domain_id：</strong> <?php echo (int)$domain['id']; ?></p>
                <p><strong>domain：</strong> <span class="mono"><?php echo e(isset($domain['domain']) ? (string)$domain['domain'] : ''); ?></span></p>
                <p><strong>site_name：</strong> <?php echo e(isset($domain['site_name']) ? (string)$domain['site_name'] : ''); ?></p>
                <p><strong>status：</strong> <?php echo e(isset($domain['status']) ? (string)$domain['status'] : ''); ?></p>
            <?php else: ?>
                <p class="bad">未命中域名配置</p>
            <?php endif; ?>
        </div>
    </div>

    <div class="card">
        <h2>Tag 直接命中结果</h2>
        <?php if ($matchedTag): ?>
            <p class="ok">已命中 Tag</p>
            <p><strong>ID：</strong> <?php echo (int)$matchedTag['id']; ?></p>
            <p><strong>名称：</strong> <?php echo e(isset($matchedTag['name']) ? (string)$matchedTag['name'] : ''); ?></p>
            <p><strong>数据库 slug：</strong> <span class="mono"><?php echo e(isset($matchedTag['slug']) ? (string)$matchedTag['slug'] : ''); ?></span></p>
            <p><strong>推导 slug：</strong> <span class="mono"><?php echo e(tag_effective_slug($matchedTag)); ?></span></p>
            <p><strong>状态：</strong> <?php echo e(isset($matchedTag['status']) ? (string)$matchedTag['status'] : ''); ?></p>
        <?php else: ?>
            <p class="bad">未直接命中 Tag</p>
        <?php endif; ?>
    </div>

    <div class="card">
        <h2>候选 Tag 列表</h2>
        <?php if (!empty($candidates)): ?>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>数据库 slug</th>
                        <th>名称推导 slug</th>
                        <th>状态</th>
                        <th>更新时间</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($candidates as $item): ?>
                    <tr>
                        <td><?php echo (int)$item['id']; ?></td>
                        <td><?php echo e($item['name']); ?></td>
                        <td class="mono"><?php echo e($item['stored_slug']); ?></td>
                        <td class="mono"><?php echo e($item['derived_slug']); ?></td>
                        <td><?php echo e($item['status']); ?></td>
                        <td><?php echo e($item['updated_at']); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <p class="empty">没有找到接近当前 slug 的候选标签。</p>
        <?php endif; ?>
    </div>
</div>
</body>
</html>
