<?php
require_once '../includes/auth.php';

$auth = new Auth();
$auth->requireLogin();
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SEO優化器測試</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .header h1 {
            color: #333;
            margin: 0;
            font-size: 2.5rem;
        }
        
        .header p {
            color: #666;
            margin: 10px 0 0 0;
            font-size: 1.1rem;
        }
        
        .test-section {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .test-section h3 {
            color: #333;
            margin: 0 0 15px 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .test-form {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        
        .form-control {
            padding: 10px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }
        
        .form-control:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        .test-actions {
            display: flex;
            gap: 15px;
            justify-content: center;
            margin-top: 20px;
        }
        
        .result-section {
            background: white;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
            display: none;
        }
        
        .result-section h4 {
            color: #333;
            margin: 0 0 15px 0;
        }
        
        .result-content {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            max-height: 400px;
            overflow-y: auto;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        
        .loading i {
            font-size: 2rem;
            margin-bottom: 10px;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            color: white;
            font-weight: 600;
            z-index: 1000;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .notification.success {
            background: #28a745;
        }
        
        .notification.error {
            background: #dc3545;
        }
        
        .notification.info {
            background: #17a2b8;
        }
        
        @media (max-width: 768px) {
            .test-form {
                grid-template-columns: 1fr;
            }
            
            .test-actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-search"></i> SEO優化器測試</h1>
            <p>測試SEO優化功能的各個組件</p>
        </div>
        
        <!-- 內容分析測試 -->
        <div class="test-section">
            <h3><i class="fas fa-chart-line"></i> 內容分析測試</h3>
            <div class="test-form">
                <div class="form-group">
                    <label for="testTitle">文章標題</label>
                    <input type="text" id="testTitle" class="form-control" 
                           value="如何提升網站SEO排名：完整指南" placeholder="請輸入文章標題">
                </div>
                <div class="form-group">
                    <label for="testKeywords">目標關鍵字</label>
                    <input type="text" id="testKeywords" class="form-control" 
                           value="SEO, 網站優化, 搜尋引擎排名" placeholder="請輸入關鍵字，用逗號分隔">
                </div>
                <div class="form-group">
                    <label for="testUrl">目標網址</label>
                    <input type="url" id="testUrl" class="form-control" 
                           value="https://example.com/seo-guide" placeholder="請輸入網址">
                </div>
                <div class="form-group">
                    <label for="testContent">文章內容</label>
                    <textarea id="testContent" class="form-control" rows="4" 
                              placeholder="請輸入文章內容">SEO（搜尋引擎優化）是提升網站在搜尋引擎中排名的重要策略。通過優化網站內容、技術結構和外部連結，可以有效提升網站的搜尋引擎可見性。本文將詳細介紹SEO的基本概念、實施方法和最佳實踐。</textarea>
                </div>
            </div>
            <div class="test-actions">
                <button class="btn btn-primary" onclick="testContentAnalysis()">
                    <i class="fas fa-chart-line"></i> 測試內容分析
                </button>
                <button class="btn btn-secondary" onclick="clearResults()">
                    <i class="fas fa-trash"></i> 清除結果
                </button>
            </div>
            <div id="analysisResult" class="result-section">
                <h4>分析結果</h4>
                <div id="analysisContent" class="result-content"></div>
            </div>
        </div>
        
        <!-- Meta標籤生成測試 -->
        <div class="test-section">
            <h3><i class="fas fa-tags"></i> Meta標籤生成測試</h3>
            <div class="test-form">
                <div class="form-group">
                    <label for="metaTitle">標題</label>
                    <input type="text" id="metaTitle" class="form-control" 
                           value="SEO優化完整指南" placeholder="請輸入標題">
                </div>
                <div class="form-group">
                    <label for="metaKeywords">關鍵字</label>
                    <input type="text" id="metaKeywords" class="form-control" 
                           value="SEO, 網站優化, 搜尋引擎" placeholder="請輸入關鍵字">
                </div>
                <div class="form-group">
                    <label for="metaBrand">品牌名稱</label>
                    <input type="text" id="metaBrand" class="form-control" 
                           value="SEO大師" placeholder="請輸入品牌名稱">
                </div>
                <div class="form-group">
                    <label for="metaContent">內容摘要</label>
                    <textarea id="metaContent" class="form-control" rows="3" 
                              placeholder="請輸入內容摘要">學習如何通過SEO優化提升網站排名，包含關鍵字研究、內容優化、技術SEO等完整策略。</textarea>
                </div>
            </div>
            <div class="test-actions">
                <button class="btn btn-primary" onclick="testMetaGeneration()">
                    <i class="fas fa-tags"></i> 測試Meta生成
                </button>
            </div>
            <div id="metaResult" class="result-section">
                <h4>Meta標籤結果</h4>
                <div id="metaContent" class="result-content"></div>
            </div>
        </div>
        
        <!-- 關鍵字分析測試 -->
        <div class="test-section">
            <h3><i class="fas fa-key"></i> 關鍵字分析測試</h3>
            <div class="test-form">
                <div class="form-group">
                    <label for="keywordContent">內容</label>
                    <textarea id="keywordContent" class="form-control" rows="4" 
                              placeholder="請輸入要分析的內容">SEO優化是提升網站排名的關鍵策略。通過有效的關鍵字研究和內容優化，可以顯著提升網站在搜尋引擎中的可見性。本文將深入探討SEO優化的各個方面。</textarea>
                </div>
                <div class="form-group">
                    <label for="keywordTarget">目標關鍵字</label>
                    <input type="text" id="keywordTarget" class="form-control" 
                           value="SEO優化, 網站排名" placeholder="請輸入目標關鍵字">
                </div>
            </div>
            <div class="test-actions">
                <button class="btn btn-primary" onclick="testKeywordAnalysis()">
                    <i class="fas fa-key"></i> 測試關鍵字分析
                </button>
            </div>
            <div id="keywordResult" class="result-section">
                <h4>關鍵字分析結果</h4>
                <div id="keywordContent" class="result-content"></div>
            </div>
        </div>
    </div>
    
    <script>
        async function testContentAnalysis() {
            const title = document.getElementById('testTitle').value;
            const content = document.getElementById('testContent').value;
            const keywords = document.getElementById('testKeywords').value;
            const url = document.getElementById('testUrl').value;
            
            if (!content) {
                showNotification('請輸入文章內容', 'error');
                return;
            }
            
            const resultDiv = document.getElementById('analysisResult');
            const contentDiv = document.getElementById('analysisContent');
            
            resultDiv.style.display = 'block';
            contentDiv.innerHTML = '<div class="loading"><i class="fas fa-spinner"></i><br>分析中...</div>';
            
            try {
                const response = await fetch('/api/seo_optimizer.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'same-origin',
                    body: JSON.stringify({
                        action: 'analyze_content',
                        title: title,
                        content: content,
                        keywords: keywords,
                        url: url
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    displayAnalysisResult(result.data);
                    showNotification('內容分析完成！', 'success');
                } else {
                    contentDiv.innerHTML = `<div style="color: #dc3545;">分析失敗: ${result.message}</div>`;
                    showNotification('分析失敗: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                contentDiv.innerHTML = '<div style="color: #dc3545;">網路錯誤，請稍後再試</div>';
                showNotification('網路錯誤，請稍後再試', 'error');
            }
        }
        
        async function testMetaGeneration() {
            const title = document.getElementById('metaTitle').value;
            const content = document.getElementById('metaContent').value;
            const keywords = document.getElementById('metaKeywords').value;
            const brandName = document.getElementById('metaBrand').value;
            
            if (!title && !content) {
                showNotification('請輸入標題或內容', 'error');
                return;
            }
            
            const resultDiv = document.getElementById('metaResult');
            const contentDiv = document.getElementById('metaContent');
            
            resultDiv.style.display = 'block';
            contentDiv.innerHTML = '<div class="loading"><i class="fas fa-spinner"></i><br>生成中...</div>';
            
            try {
                const response = await fetch('/api/seo_optimizer.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'same-origin',
                    body: JSON.stringify({
                        action: 'generate_meta',
                        title: title,
                        content: content,
                        keywords: keywords,
                        brand_name: brandName
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    displayMetaResult(result.data);
                    showNotification('Meta標籤生成完成！', 'success');
                } else {
                    contentDiv.innerHTML = `<div style="color: #dc3545;">生成失敗: ${result.message}</div>`;
                    showNotification('生成失敗: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                contentDiv.innerHTML = '<div style="color: #dc3545;">網路錯誤，請稍後再試</div>';
                showNotification('網路錯誤，請稍後再試', 'error');
            }
        }
        
        async function testKeywordAnalysis() {
            const content = document.getElementById('keywordContent').value;
            const keywords = document.getElementById('keywordTarget').value;
            
            if (!content) {
                showNotification('請輸入內容', 'error');
                return;
            }
            
            const resultDiv = document.getElementById('keywordResult');
            const contentDiv = document.getElementById('keywordContent');
            
            resultDiv.style.display = 'block';
            contentDiv.innerHTML = '<div class="loading"><i class="fas fa-spinner"></i><br>分析中...</div>';
            
            try {
                const response = await fetch('/api/seo_optimizer.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'same-origin',
                    body: JSON.stringify({
                        action: 'analyze_keywords',
                        content: content,
                        target_keywords: keywords
                    })
                });
                
                const result = await response.json();
                
                if (result.success) {
                    displayKeywordResult(result.data);
                    showNotification('關鍵字分析完成！', 'success');
                } else {
                    contentDiv.innerHTML = `<div style="color: #dc3545;">分析失敗: ${result.message}</div>`;
                    showNotification('分析失敗: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                contentDiv.innerHTML = '<div style="color: #dc3545;">網路錯誤，請稍後再試</div>';
                showNotification('網路錯誤，請稍後再試', 'error');
            }
        }
        
        function displayAnalysisResult(data) {
            const contentDiv = document.getElementById('analysisContent');
            let html = '';
            
            if (data.overall_score) {
                const scoreClass = data.overall_score >= 80 ? 'excellent' : 
                                 (data.overall_score >= 60 ? 'good' : 
                                 (data.overall_score >= 40 ? 'average' : 'poor'));
                
                html += `
                    <div style="text-align: center; margin-bottom: 20px;">
                        <div style="display: inline-block; width: 80px; height: 80px; border-radius: 50%; background: linear-gradient(135deg, #667eea, #764ba2); color: white; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; font-weight: bold; margin-bottom: 10px;">
                            ${data.overall_score}
                        </div>
                        <h4>SEO總分</h4>
                        <p>基於內容、關鍵字、技術等多個維度的綜合評分</p>
                    </div>
                `;
            }
            
            if (data.keyword_analysis) {
                html += `
                    <div style="margin-bottom: 20px;">
                        <h4 style="color: #333; border-bottom: 1px solid #e0e0e0; padding-bottom: 5px;">關鍵字分析</h4>
                        <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; margin-bottom: 10px;">
                            <strong>關鍵字密度:</strong> ${data.keyword_analysis.density}%<br>
                            <strong>分佈評估:</strong> ${data.keyword_analysis.distribution}<br>
                            <strong>相關性分數:</strong> ${data.keyword_analysis.relevance}/10
                        </div>
                    </div>
                `;
            }
            
            if (data.improvements && data.improvements.length > 0) {
                html += `
                    <div style="margin-bottom: 20px;">
                        <h4 style="color: #333; border-bottom: 1px solid #e0e0e0; padding-bottom: 5px;">改進建議</h4>
                        <ul style="list-style: none; padding: 0;">
                            ${data.improvements.map(improvement => `
                                <li style="background: white; border: 1px solid #e0e0e0; border-radius: 6px; padding: 10px; margin-bottom: 8px; display: flex; align-items: center; gap: 10px;">
                                    💡 ${improvement}
                                </li>
                            `).join('')}
                        </ul>
                    </div>
                `;
            }
            
            contentDiv.innerHTML = html;
        }
        
        function displayMetaResult(data) {
            const contentDiv = document.getElementById('metaContent');
            let html = '';
            
            if (data.title_tag) {
                html += `
                    <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; margin-bottom: 15px;">
                        <h5 style="margin: 0 0 10px 0; color: #333;">Title標籤</h5>
                        <code style="background: #f8f9fa; padding: 2px 6px; border-radius: 4px; font-family: 'Courier New', monospace;">${data.title_tag}</code>
                    </div>
                `;
            }
            
            if (data.meta_description) {
                html += `
                    <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; margin-bottom: 15px;">
                        <h5 style="margin: 0 0 10px 0; color: #333;">Meta描述</h5>
                        <code style="background: #f8f9fa; padding: 2px 6px; border-radius: 4px; font-family: 'Courier New', monospace;">${data.meta_description}</code>
                    </div>
                `;
            }
            
            if (data.meta_keywords) {
                html += `
                    <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px; margin-bottom: 15px;">
                        <h5 style="margin: 0 0 10px 0; color: #333;">Meta關鍵字</h5>
                        <code style="background: #f8f9fa; padding: 2px 6px; border-radius: 4px; font-family: 'Courier New', monospace;">${data.meta_keywords}</code>
                    </div>
                `;
            }
            
            contentDiv.innerHTML = html;
        }
        
        function displayKeywordResult(data) {
            const contentDiv = document.getElementById('keywordContent');
            let html = '';
            
            if (data.keyword_density) {
                html += `
                    <div style="margin-bottom: 20px;">
                        <h4 style="color: #333; border-bottom: 1px solid #e0e0e0; padding-bottom: 5px;">關鍵字密度分析</h4>
                        <div style="background: white; border: 1px solid #e0e0e0; border-radius: 8px; padding: 15px;">
                            <strong>主要關鍵字:</strong> ${data.keyword_density.primary_keyword.keyword}<br>
                            <strong>密度:</strong> ${data.keyword_density.primary_keyword.density}%<br>
                            <strong>出現次數:</strong> ${data.keyword_density.primary_keyword.count}
                        </div>
                    </div>
                `;
            }
            
            if (data.suggestions && data.suggestions.length > 0) {
                html += `
                    <div style="margin-bottom: 20px;">
                        <h4 style="color: #333; border-bottom: 1px solid #e0e0e0; padding-bottom: 5px;">優化建議</h4>
                        <ul style="list-style: none; padding: 0;">
                            ${data.suggestions.map(suggestion => `
                                <li style="background: white; border: 1px solid #e0e0e0; border-radius: 6px; padding: 10px; margin-bottom: 8px; display: flex; align-items: center; gap: 10px;">
                                    💡 ${suggestion}
                                </li>
                            `).join('')}
                        </ul>
                    </div>
                `;
            }
            
            contentDiv.innerHTML = html;
        }
        
        function clearResults() {
            document.querySelectorAll('.result-section').forEach(section => {
                section.style.display = 'none';
            });
        }
        
        function showNotification(message, type = 'success') {
            const notification = document.createElement('div');
            notification.className = `notification ${type}`;
            notification.textContent = message;
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.classList.add('show');
            }, 100);
            
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => {
                    document.body.removeChild(notification);
                }, 300);
            }, 3000);
        }
    </script>
</body>
</html>
