<?php
/**
 * Glass Shortener - 最终稳定版 (修复HTML渲染问题)
 */

// ================= 1. 配置区域 =================
$config = [
    'db_host' => 'localhost',
    'db_port' => '3306',
    'db_name' => 'ser506580505755',
    'db_user' => 'ser506580505755',
    'db_pass' => 'NFXF3Axw764Q',
    'api_key' => 'my_secure_api_key_123',
];

// ================= 2. 核心函数 =================
function getDb($cfg) {
    try {
        $dsn = "mysql:host={$cfg['db_host']};port={$cfg['db_port']};dbname={$cfg['db_name']};charset=utf8mb4";
        $pdo = new PDO($dsn, $cfg['db_user'], $cfg['db_pass']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        return null;
    }
}

function ensureTable($pdo) {
    if (!$pdo) return false;
    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS links (
            id INT AUTO_INCREMENT PRIMARY KEY,
            short_code VARCHAR(10) UNIQUE NOT NULL,
            original_url TEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            clicks INT DEFAULT 0
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        return true;
    } catch (PDOException $e) {
        return false;
    }
}

function genCode($len = 6) {
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    return substr(str_shuffle(str_repeat($chars, ceil($len / strlen($chars)))), 0, $len);
}

function saveLink($url, $code, $cfg) {
    $pdo = getDb($cfg);
    if (!$pdo) return false;
    if (!ensureTable($pdo)) return false;
    
    try {
        $stmt = $pdo->prepare("INSERT INTO links (short_code, original_url) VALUES (:c, :u)");
        $stmt->execute([':c' => $code, ':u' => $url]);
        return true;
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) return saveLink($url, genCode(), $cfg);
        return false;
    }
}

// ================= 3. 路由逻辑 =================
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];
$isApi = isset($_REQUEST['type']) && $_REQUEST['type'] === 'api';

// A. 短链接跳转: GET /{code}
if ($method === 'GET' && preg_match('/^\/([a-zA-Z0-9]{6})$/', $path, $m)) {
    $pdo = getDb($config);
    if ($pdo && ensureTable($pdo)) {
        $stmt = $pdo->prepare("SELECT original_url FROM links WHERE short_code = :c");
        $stmt->execute([':c' => $m]); // 注意取 $m
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            $pdo->prepare("UPDATE links SET clicks=clicks+1 WHERE short_code=:c")->execute([':c' => $m]);
            header("Location: " . $row['original_url'], true, 301);
            exit;
        }
    }
    http_response_code(404);
    echo "<h1 style='font-family:sans-serif;text-align:center;margin-top:50px;'>404 Link Not Found</h1>";
    exit;
}

// B. API 生成: ?type=api
if ($isApi) {
    header('Content-Type: application/json; charset=utf-8');
    $key = $_SERVER['HTTP_X_API_KEY'] ?? ($_REQUEST['key'] ?? '');
    if ($key !== $config['api_key']) {
        http_response_code(401);
        echo json_encode(['success'=>false, 'message'=>'Invalid Key']);
        exit;
    }

    $url = $_REQUEST['url'] ?? json_decode(file_get_contents('php://input'), true)['url'] ?? '';
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        http_response_code(400);
        echo json_encode(['success'=>false, 'message'=>'Invalid URL']);
        exit;
    }

    $code = genCode();
    if (saveLink($url, $code, $config)) {
        $proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on') ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'];
        echo json_encode(['success'=>true, 'short_code'=>$code, 'short_url'=>"$proto://$host/$code", 'original_url'=>$url]);
    } else {
        http_response_code(500);
        echo json_encode(['success'=>false, 'message'=>'Save Failed']);
    }
    exit;
}

// C. 网页表单提交: POST /
if ($method === 'POST' && !$isApi) {
    $url = $_POST['url'] ?? '';
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        echo "<script>alert('URL无效');history.back();</script>";
        exit;
    }
    
    $code = genCode();
    if (saveLink($url, $code, $config)) {
        $proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on') ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'];
        $shortUrl = "$proto://$host/$code";
        
        // 自动复制脚本
        echo <<<JS
        <script>
            navigator.clipboard.writeText("$shortUrl").then(function() {
                alert("✅ 生成成功！链接已自动复制：\n$shortUrl");
                window.location.href = "/";
            }, function(err) {
                alert("✅ 生成成功！请手动复制：\n$shortUrl");
                window.location.href = "/";
            });
        </script>
JS;
    } else {
        echo "<script>alert('❌ 生成失败，请检查数据库配置');history.back();</script>";
    }
    exit;
}

// D. 首页显示: GET /
if ($method === 'GET' && ($path === '/' || $path === '/index.php')) {
    // 强制声明 HTML 类型，防止被当作文本显示
    header('Content-Type: text/html; charset=utf-8');
    
    $pdo = getDb($config);
    $dbOk = $pdo ? ensureTable($pdo) : false;
    $proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on') ? "https" : "http";
    $host = $_SERVER['HTTP_HOST'];
    
    $statusMsg = $dbOk ? '' : '<div class="bg-red-500/80 p-2 rounded mb-4 text-sm text-white">⚠️ 数据库连接失败</div>';

    ?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Glass Shortener</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; font-family: sans-serif; }
        .glass { background: rgba(255,255,255,0.25); backdrop-filter: blur(10px); border-radius: 16px; border: 1px solid rgba(255,255,255,0.3); }
    </style>
</head>
<body class="flex items-center justify-center p-4">
    <div class="glass w-full max-w-md p-8 text-center text-white shadow-xl">
        <h1 class="text-3xl font-bold mb-6">🔗 Glass Link</h1>
        
        <?= $statusMsg ?>
        
        <form method="POST" class="space-y-4">
            <input type="url" name="url" required placeholder="输入长链接 https://..." 
                   class="w-full p-3 rounded-lg bg-white/50 text-gray-800 placeholder-gray-500 focus:outline-none focus:ring-2 focus:ring-purple-300">
            <button type="submit" class="w-full bg-white/30 hover:bg-white/50 py-3 rounded-lg transition font-semibold">
                生成并自动复制
            </button>
        </form>
        
        <div class="mt-6 text-xs text-white/70 bg-black/20 p-3 rounded text-left">
            <p><strong>API 调用:</strong></p>
            <p class="font-mono mt-1">GET <?= $proto ?>://<?= $host ?>/?type=api&key=<?= $config['api_key'] ?>&url=...</p>
        </div>
    </div>
</body>
</html>
    <?php
    exit;
}

// 默认 404
http_response_code(404);
echo "Not Found";
?>
