<?php
// Xử lý API tạo link
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    if (isset($data['action']) && $data['action'] === 'convert') {
        header('Content-Type: application/json');
        $input = trim($data['link'] ?? '');
    
    if (empty($input)) {
        echo json_encode(['status' => 'error', 'message' => 'Vui lòng nhập link!']);
        exit;
    }
    
    $token = '';
    
    // Parse URL để lấy token
    $input_url = strpos($input, 'http') === 0 ? $input : 'https://' . $input;
    $parsedUrl = parse_url($input_url);
    if (isset($parsedUrl['query'])) {
        parse_str($parsedUrl['query'], $queryParams);
        if (isset($queryParams['token'])) {
            $token = $queryParams['token'];
        }
    }
    
    // Nếu không lấy được bằng parse_url, thử dùng regex
    if (empty($token)) {
        if (preg_match('/([a-f0-9]{16,32})/i', $input, $matches)) {
            $token = $matches[1];
        }
    }
    
    if (empty($token)) {
        echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy token trong link!']);
        exit;
    }
    
$domain = "https://niala.nahhva.com";
$linkNa = $domain . "/sub/na.php?token=" . rawurlencode($token);
$linkSubscribe = $domain . "/api/v1/client/subscribe?token=" . rawurlencode($token);
    
    echo json_encode([
        'status' => 'success', 
        'link' => $convertedBaseLink
    ]);
    exit;
    }
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chuyển Đổi TB</title>
    <style>
        :root {
            --primary: #6366f1;
            --primary-hover: #4f46e5;
            --bg-color: #0f172a;
            --surface: #1e293b;
            --text: #f8fafc;
            --text-muted: #94a3b8;
            --border: #334155;
            --success: #10b981;
            --error: #ef4444;
            --warning: #f59e0b;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            background-color: var(--bg-color);
            color: var(--text);
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-image: radial-gradient(circle at 50% -20%, #312e81 0%, var(--bg-color) 70%);
        }

        .container {
            background-color: var(--surface);
            padding: 2.5rem;
            border-radius: 1.25rem;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.05) inset;
            width: 100%;
            max-width: 450px;
            border: 1px solid var(--border);
            backdrop-filter: blur(20px);
            position: relative;
            overflow: hidden;
        }

        .container::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, #6366f1, #a855f7, #ec4899);
        }

        h1 {
            margin-top: 0;
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            text-align: center;
            background: linear-gradient(135deg, #e0e7ff, #a5b4fc);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        
        .subtitle {
            text-align: center;
            color: var(--text-muted);
            font-size: 0.875rem;
            margin-bottom: 2rem;
        }

        .input-group {
            margin-bottom: 1.5rem;
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            color: #cbd5e1;
            font-weight: 500;
        }

        input[type="text"] {
            width: 100%;
            padding: 0.875rem 1rem;
            border-radius: 0.75rem;
            border: 1px solid var(--border);
            background-color: rgba(15, 23, 42, 0.6);
            color: var(--text);
            font-size: 1rem;
            transition: all 0.2s ease;
            box-sizing: border-box;
            outline: none;
            box-shadow: inset 0 2px 4px rgba(0,0,0,0.1);
        }

        input[type="text"]:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2), inset 0 2px 4px rgba(0,0,0,0.1);
        }

        input[type="text"]::placeholder {
            color: #475569;
        }

        button {
            width: 100%;
            padding: 0.875rem 1.5rem;
            border: none;
            border-radius: 0.75rem;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 0.5rem;
        }

        .btn-primary {
            background: linear-gradient(135deg, var(--primary), #8b5cf6);
            color: white;
            box-shadow: 0 4px 14px 0 rgba(99, 102, 241, 0.39);
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, var(--primary-hover), #7c3aed);
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(99, 102, 241, 0.4);
        }

        .btn-primary:active {
            transform: translateY(0);
            box-shadow: 0 2px 10px rgba(99, 102, 241, 0.3);
        }

        .result-section {
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 1px dashed var(--border);
            display: none;
            animation: fadeIn 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
        }

        .result-section.show {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .copy-group {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 0.75rem;
            margin-top: 1rem;
        }

        .btn-outline {
            background-color: rgba(30, 41, 59, 0.5);
            border: 1px solid var(--border);
            color: #e2e8f0;
            font-size: 0.9rem;
        }

        .btn-outline:hover {
            background-color: rgba(255, 255, 255, 0.08);
            border-color: #94a3b8;
            transform: translateY(-1px);
        }
        
        .btn-outline:active {
            transform: translateY(0);
        }

        .btn-clash:hover { border-color: #0ea5e9; color: #38bdf8; }
        .btn-shadowrocket:hover { border-color: #f43f5e; color: #fb7185; }

        .toast {
            position: fixed;
            bottom: 2rem;
            left: 50%;
            transform: translateX(-50%) translateY(100px);
            background-color: var(--success);
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 9999px;
            font-weight: 500;
            box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.2), 0 4px 6px -2px rgba(0, 0, 0, 0.1);
            transition: transform 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.4s ease;
            opacity: 0;
            z-index: 50;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }

        .toast.show {
            transform: translateX(-50%) translateY(0);
            opacity: 1;
        }

        .converted-url-display {
            margin-top: 1.5rem;
            padding: 0.75rem;
            background: rgba(0,0,0,0.2);
            border-radius: 0.5rem;
            border: 1px solid var(--border);
            font-family: monospace;
            font-size: 0.8rem;
            color: #a5b4fc;
            word-break: break-all;
            display: none;
        }
        .converted-url-display.show {
            display: block;
        }

        .qr-section {
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px dashed var(--border);
            display: none;
            flex-direction: column;
            align-items: center;
            animation: fadeIn 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards;
        }

        .qr-section.show {
            display: flex;
        }

        #qrcode {
            background: white;
            padding: 1rem;
            border-radius: 0.75rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
        }

        .qr-title {
            font-size: 0.875rem;
            color: var(--text-muted);
            margin-bottom: 0.75rem;
            font-weight: 500;
        }
    </style>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
</head>
<body>

    <div class="container">
        <h1>Sub Converter</h1>
        <div class="subtitle">Chuyển tiếp Turbo666</div>
        
        <div class="input-group">
            <label for="originalLink">Link Gốc</label>
            <input type="text" id="originalLink" placeholder="Dán link cần chuyển đổi vào đây" autocomplete="off">
        </div>

        <button class="btn-primary" onclick="convertLink()">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"/><polyline points="16 6 12 2 8 6"/><line x1="12" y1="2" x2="12" y2="15"/></svg>
            Tạo Link Chuyển đổi
        </button>

        <div class="result-section" id="resultSection">
            <label>Chọn app để copy link:</label>
            <div class="copy-group">
                <button class="btn-outline btn-clash" onclick="copyLink('clash')">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="5" ry="5"/><path d="M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z"/><line x1="17.5" y1="6.5" x2="17.51" y2="6.5"/></svg>
                    Clash Meta
                </button>
                <button class="btn-outline btn-shadowrocket" onclick="copyLink('shadowrocket')">
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242"/><path d="M12 12v9"/><path d="M8 17l4 4 4-4"/></svg>
                    Shadowrocket
                </button>
            </div>
            
            <div style="margin-top: 1rem;">
                <button class="btn-outline" style="width: 100%;" onclick="copyLink('base')">
                    Copy Link Gốc
                </button>
            </div>
            
            <div id="urlDisplay" class="converted-url-display"></div>
            
            <div id="qrSection" class="qr-section">
                <div class="qr-title" id="qrTitle">Mã QR</div>
                <div id="qrcode"></div>
            </div>
        </div>
    </div>

    <div class="toast" id="toast">
        <svg id="toastIcon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
        <span id="toastMsg">Thành công!</span>
    </div>

    <script>
        let convertedBaseLink = '';

        async function convertLink() {
            if (window.location.protocol === 'file:') {
                showToast('Lỗi: Phải chạy file PHP trên web server (Hosting/XAMPP)! Không thể mở trực tiếp.', 'var(--error)', 'error');
                return;
            }

            const input = document.getElementById('originalLink').value.trim();
            if (!input) {
                showToast('Vui lòng nhập link!', 'var(--warning)', 'warning');
                return;
            }

            try {
                // Gọi API PHP để xử lý bảo mật, tránh lộ cấu trúc link thật ở client
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ action: 'convert', link: input })
                });
                
                const data = await response.json();
                
                if (data.status === 'error') {
                    showToast(data.message, 'var(--error)', 'error');
                    return;
                }

                convertedBaseLink = data.link;
                
                // Show result section
                document.getElementById('resultSection').classList.add('show');
                
                // Show url in UI
                const urlDisplay = document.getElementById('urlDisplay');
                urlDisplay.textContent = convertedBaseLink;
                urlDisplay.classList.add('show');

                renderQR(convertedBaseLink, 'Link Gốc');

                showToast('Đã tạo link thành công!', 'var(--success)', 'success');
                
            } catch (e) {
                showToast('Lỗi khi kết nối tới server!', 'var(--error)', 'error');
            }
        }

        function copyLink(type) {
            let finalLink = convertedBaseLink;
            let appName = 'Link Gốc';
            
            if (type === 'clash') {
                finalLink += '&flag=clash';
                appName = 'Clash Meta';
            } else if (type === 'shadowrocket') {
                finalLink += '&flag=shadowrocket';
                appName = 'Shadowrocket';
            }

            navigator.clipboard.writeText(finalLink).then(() => {
                showToast(`Đã copy cho ${appName}`, 'var(--success)', 'success');
                renderQR(finalLink, appName);
            }).catch(err => {
                showToast('Lỗi khi copy vào clipboard!', 'var(--error)', 'error');
            });
        }

        function renderQR(text, title) {
            const qrSection = document.getElementById('qrSection');
            const qrTitle = document.getElementById('qrTitle');
            const qrcodeDiv = document.getElementById('qrcode');
            
            qrSection.classList.add('show');
            qrTitle.textContent = `Mã QR: ${title}`;
            
            qrcodeDiv.innerHTML = '';
            new QRCode(qrcodeDiv, {
                text: text,
                width: 160,
                height: 160,
                colorDark : "#000000",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.M
            });
        }

        function showToast(message, color, type) {
            const toast = document.getElementById('toast');
            const toastMsg = document.getElementById('toastMsg');
            const toastIcon = document.getElementById('toastIcon');
            
            toastMsg.textContent = message;
            toast.style.backgroundColor = color;
            
            if (type === 'error' || type === 'warning') {
                toastIcon.innerHTML = '<circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/>';
            } else {
                toastIcon.innerHTML = '<path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/>';
            }

            toast.classList.add('show');
            
            if (window.toastTimeout) {
                clearTimeout(window.toastTimeout);
            }
            
            window.toastTimeout = setTimeout(() => {
                toast.classList.remove('show');
            }, 3000);
        }
    </script>
</body>
</html>
