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

$auth = new Auth();
$auth->requireLogin();

// Get brands data
require_once '../config/database.php';
$database = new Database();
$db = $database->getConnection();

$brands = [];
$query = "SELECT * FROM brands ORDER BY created_at DESC";
$stmt = $db->prepare($query);
$stmt->execute();
$brands = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get recent reports
$reports_query = "SELECT sr.*, b.name as brand_name FROM seo_reports sr 
                 LEFT JOIN brands b ON sr.brand_id = b.id 
                 ORDER BY sr.created_at DESC LIMIT 10";
$reports_stmt = $db->prepare($reports_query);
$reports_stmt->execute();
$recent_reports = $reports_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get brand_id from URL parameter
$selected_brand_id = $_GET['brand_id'] ?? '';
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SEO分析 - SEO AI 自動化系統</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/admin.css" rel="stylesheet">
</head>
<body>
    <div class="admin-layout">
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <div class="logo">
                    <i class="fas fa-robot"></i>
                    <span>SEO AI</span>
                </div>
            </div>
            
            <nav class="sidebar-nav">
                <ul>
                    <li>
                        <a href="dashboard.php">
                            <i class="fas fa-tachometer-alt"></i>
                            <span>儀表板</span>
                        </a>
                    </li>
                    <li>
                        <a href="brands.php">
                            <i class="fas fa-building"></i>
                            <span>品牌管理</span>
                        </a>
                    </li>
                    <li>
                        <a href="reports.php">
                            <i class="fas fa-chart-bar"></i>
                            <span>SEO報告</span>
                        </a>
                    </li>
                    <li class="active">
                        <a href="seo_analysis.php">
                            <i class="fas fa-search"></i>
                            <span>SEO分析</span>
                        </a>
                    </li>
                    <li>
                        <a href="content.php">
                            <i class="fas fa-edit"></i>
                            <span>內容管理</span>
                        </a>
                    </li>
                    <li>
                        <a href="analytics.php">
                            <i class="fas fa-analytics"></i>
                            <span>成效分析</span>
                        </a>
                    </li>
                    <li>
                        <a href="settings.php">
                            <i class="fas fa-cog"></i>
                            <span>系統設定</span>
                        </a>
                    </li>
                    <li>
                        <a href="help.php">
                            <i class="fas fa-question-circle"></i>
                            <span>使用說明</span>
                        </a>
                    </li>
                    <li>
                        <a href="profile.php">
                            <i class="fas fa-user"></i>
                            <span>個人資料</span>
                        </a>
                    </li>
                </ul>
            </nav>
            
            <div class="sidebar-footer">
                <a href="logout.php" class="logout-btn">
                    <i class="fas fa-sign-out-alt"></i>
                    <span>登出</span>
                </a>
            </div>
        </aside>
        
        <!-- Main Content -->
        <main class="main-content">
            <header class="header">
                <div class="header-left">
                    <h1>SEO分析</h1>
                    <p>AI驅動的SEO分析和優化建議</p>
                </div>
                <div class="header-right">
                    <button class="btn btn-primary" onclick="showAnalysisModal()">
                        <i class="fas fa-plus"></i>
                        開始分析
                    </button>
                </div>
            </header>
            
            <div class="seo-analysis-content">
                <!-- Analysis Types -->
                <div class="analysis-types">
                    <h2>分析類型</h2>
                    <div class="types-grid">
                        <div class="type-card" onclick="selectAnalysisType('basic')">
                            <div class="type-icon">
                                <i class="fas fa-search"></i>
                            </div>
                            <h3>基礎分析</h3>
                            <p>品牌SEO現況評估和基本優化建議</p>
                        </div>
                        
                        <div class="type-card" onclick="selectAnalysisType('keyword')">
                            <div class="type-icon">
                                <i class="fas fa-key"></i>
                            </div>
                            <h3>關鍵字分析</h3>
                            <p>關鍵字競爭度分析和策略建議</p>
                        </div>
                        
                        <div class="type-card" onclick="selectAnalysisType('competitor')">
                            <div class="type-icon">
                                <i class="fas fa-users"></i>
                            </div>
                            <h3>競爭對手分析</h3>
                            <p>競爭對手SEO策略分析和超越建議</p>
                        </div>
                        
                        <div class="type-card" onclick="selectAnalysisType('technical')">
                            <div class="type-icon">
                                <i class="fas fa-cogs"></i>
                            </div>
                            <h3>技術SEO分析</h3>
                            <p>網站技術SEO檢查和優化建議</p>
                        </div>
                    </div>
                </div>
                
                <!-- Recent Reports -->
                <div class="recent-reports">
                    <h2>最近的分析報告</h2>
                    <?php if (empty($recent_reports)): ?>
                        <div class="empty-state">
                            <i class="fas fa-chart-line"></i>
                            <h3>還沒有分析報告</h3>
                            <p>開始您的第一次SEO分析</p>
                        </div>
                    <?php else: ?>
                        <div class="reports-grid">
                            <?php foreach ($recent_reports as $report): ?>
                                <div class="report-card">
                                    <div class="report-header">
                                        <h3><?php echo htmlspecialchars($report['title']); ?></h3>
                                        <span class="report-type"><?php echo getReportTypeName($report['report_type']); ?></span>
                                    </div>
                                    <div class="report-info">
                                        <div class="info-item">
                                            <i class="fas fa-building"></i>
                                            <span><?php echo htmlspecialchars($report['brand_name']); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <i class="fas fa-calendar"></i>
                                            <span><?php echo date('Y-m-d H:i', strtotime($report['created_at'])); ?></span>
                                        </div>
                                        <div class="info-item">
                                            <i class="fas fa-circle status-<?php echo $report['status']; ?>"></i>
                                            <span><?php echo getStatusName($report['status']); ?></span>
                                        </div>
                                    </div>
                                    <div class="report-actions">
                                        <button class="btn btn-secondary" onclick="viewReport(<?php echo $report['id']; ?>)">
                                            <i class="fas fa-eye"></i>
                                            查看報告
                                        </button>
                                        <button class="btn btn-primary" onclick="downloadReport(<?php echo $report['id']; ?>)">
                                            <i class="fas fa-download"></i>
                                            下載
                                        </button>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
    
    <!-- Analysis Modal -->
    <div id="analysisModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>開始SEO分析</h2>
                <button class="modal-close" onclick="closeModal('analysisModal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="analysisForm">
                <div class="modal-body">
                    <div class="form-group">
                        <label for="analysisBrand">選擇品牌 *</label>
                        <select id="analysisBrand" name="brand_id" class="form-control" required>
                            <option value="">請選擇品牌</option>
                            <?php foreach ($brands as $brand): ?>
                                <option value="<?php echo $brand['id']; ?>" <?php echo ($selected_brand_id == $brand['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($brand['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="analysisType">分析類型 *</label>
                        <select id="analysisType" name="analysis_type" class="form-control" required>
                            <option value="">請選擇分析類型</option>
                            <option value="basic">基礎分析</option>
                            <option value="keyword">關鍵字分析</option>
                            <option value="competitor">競爭對手分析</option>
                            <option value="technical">技術SEO分析</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>分析說明</label>
                        <div class="analysis-description" id="analysisDescription">
                            請選擇分析類型以查看詳細說明
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('analysisModal')">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-play"></i>
                        開始分析
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Report Modal -->
    <div id="reportModal" class="modal">
        <div class="modal-content report-modal">
            <div class="modal-header">
                <h2 id="reportTitle">分析報告</h2>
                <button class="modal-close" onclick="closeModal('reportModal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <div class="modal-body">
                <div id="reportContent" class="report-content">
                    <div class="loading">
                        <i class="fas fa-spinner fa-spin"></i>
                        <p>載入中...</p>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('reportModal')">關閉</button>
                <button type="button" class="btn btn-primary" onclick="downloadCurrentReport()">
                    <i class="fas fa-download"></i>
                    下載報告
                </button>
            </div>
        </div>
    </div>
    
    <style>
        .seo-analysis-content {
            padding: 30px;
        }
        
        .analysis-types {
            margin-bottom: 40px;
        }
        
        .analysis-types h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5rem;
        }
        
        .types-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }
        
        .type-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
        }
        
        .type-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
        }
        
        .type-card.selected {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }
        
        .type-icon {
            font-size: 2.5rem;
            color: #667eea;
            margin-bottom: 15px;
        }
        
        .type-card.selected .type-icon {
            color: white;
        }
        
        .type-card h3 {
            font-size: 1.2rem;
            margin-bottom: 10px;
        }
        
        .type-card p {
            color: #666;
            font-size: 0.9rem;
            line-height: 1.5;
        }
        
        .type-card.selected p {
            color: rgba(255, 255, 255, 0.9);
        }
        
        .recent-reports h2 {
            color: #333;
            margin-bottom: 20px;
            font-size: 1.5rem;
        }
        
        .reports-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
        }
        
        .report-card {
            background: white;
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: transform 0.3s ease;
        }
        
        .report-card:hover {
            transform: translateY(-3px);
        }
        
        .report-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
        .report-header h3 {
            font-size: 1.1rem;
            color: #333;
            margin: 0;
        }
        
        .report-type {
            background: #667eea;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
        }
        
        .report-info {
            margin-bottom: 15px;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
            color: #666;
            font-size: 0.9rem;
        }
        
        .info-item i {
            width: 16px;
            color: #667eea;
        }
        
        .status-completed {
            color: #28a745;
        }
        
        .status-processing {
            color: #ffc107;
        }
        
        .status-failed {
            color: #dc3545;
        }
        
        .report-actions {
            display: flex;
            gap: 10px;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        }
        
        .empty-state i {
            font-size: 3rem;
            color: #667eea;
            margin-bottom: 15px;
        }
        
        .empty-state h3 {
            color: #333;
            margin-bottom: 10px;
        }
        
        .empty-state p {
            color: #666;
        }
        
        .analysis-description {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            color: #666;
            font-size: 0.9rem;
            line-height: 1.5;
        }
        
        .report-modal .modal-content {
            max-width: 800px;
        }
        
        .report-content {
            max-height: 60vh;
            overflow-y: auto;
            white-space: pre-wrap;
            line-height: 1.6;
            color: #333;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .loading i {
            font-size: 2rem;
            margin-bottom: 15px;
        }
        
        /* Modal Styles */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            border-radius: 15px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
        }
        
        .modal-header {
            padding: 25px 30px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .modal-header h2 {
            font-size: 1.5rem;
            font-weight: 600;
            color: #333;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 1.5rem;
            color: #666;
            cursor: pointer;
            padding: 5px;
        }
        
        .modal-body {
            padding: 30px;
        }
        
        .modal-footer {
            padding: 20px 30px 30px;
            border-top: 1px solid #e0e0e0;
            display: flex;
            justify-content: flex-end;
            gap: 15px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: 500;
        }
        
        .form-control {
            width: 100%;
            padding: 12px;
            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 25px;
            border: none;
            border-radius: 8px;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            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;
        }
        
        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            padding: 15px 20px;
            z-index: 2000;
            transform: translateX(400px);
            transition: transform 0.3s ease;
        }
        
        .notification.show {
            transform: translateX(0);
        }
        
        .notification-success {
            border-left: 4px solid #28a745;
        }
        
        .notification-error {
            border-left: 4px solid #dc3545;
        }
        
        .notification-info {
            border-left: 4px solid #17a2b8;
        }
        
        .notification-content {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .notification-content i {
            font-size: 1.2rem;
        }
        
        .notification-success .notification-content i {
            color: #28a745;
        }
        
        .notification-error .notification-content i {
            color: #dc3545;
        }
        
        .notification-info .notification-content i {
            color: #17a2b8;
        }
    </style>
    
    <script>
        let currentReportId = null;
        let selectedAnalysisType = '';
        
        document.addEventListener('DOMContentLoaded', function() {
            // Bind form submission
            const form = document.getElementById('analysisForm');
            if (form) {
                form.addEventListener('submit', function(e) {
                    e.preventDefault();
                    startAnalysis();
                });
            }
            
            // Bind analysis type selection
            const analysisTypeSelect = document.getElementById('analysisType');
            if (analysisTypeSelect) {
                analysisTypeSelect.addEventListener('change', function() {
                    updateAnalysisDescription(this.value);
                });
            }
            
            // Auto-open modal if brand is pre-selected
            const selectedBrandId = '<?php echo $selected_brand_id; ?>';
            if (selectedBrandId) {
                setTimeout(() => {
                    showAnalysisModal();
                }, 500);
            }
        });
        
        function selectAnalysisType(type) {
            selectedAnalysisType = type;
            
            // Update visual selection
            document.querySelectorAll('.type-card').forEach(card => {
                card.classList.remove('selected');
            });
            event.target.closest('.type-card').classList.add('selected');
            
            // Update form
            document.getElementById('analysisType').value = type;
            updateAnalysisDescription(type);
        }
        
        function updateAnalysisDescription(type) {
            const descriptions = {
                'basic': '基礎分析將評估品牌的SEO現況，包括網站結構、內容質量、關鍵字使用等基本要素，並提供初步的優化建議。',
                'keyword': '關鍵字分析將深入分析目標關鍵字的競爭度、搜尋量、難度等指標，並提供關鍵字策略建議和內容規劃方向。',
                'competitor': '競爭對手分析將研究同業的SEO策略，包括關鍵字使用、內容策略、技術實現等，並提供超越競爭對手的具體建議。',
                'technical': '技術SEO分析將檢查網站的技術層面，包括頁面速度、移動端優化、結構化數據、內部連結等技術要素。'
            };
            
            document.getElementById('analysisDescription').textContent = descriptions[type] || '請選擇分析類型以查看詳細說明';
        }
        
        function showAnalysisModal() {
            document.getElementById('analysisModal').style.display = 'block';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        async function startAnalysis() {
            const form = document.getElementById('analysisForm');
            const formData = new FormData(form);
            const data = Object.fromEntries(formData);
            
            if (!data.brand_id || !data.analysis_type) {
                showNotification('請選擇品牌和分析類型', 'error');
                return;
            }
            
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 分析中...';
            submitBtn.disabled = true;
            
            try {
                const response = await fetch('/api/seo_analysis.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    credentials: 'same-origin',
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showNotification('SEO分析完成！', 'success');
                    closeModal('analysisModal');
                    form.reset();
                    // Reload page to show new report
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    showNotification('分析失敗: ' + result.message, 'error');
                }
            } catch (error) {
                console.error('Error:', error);
                showNotification('網路錯誤，請稍後再試', 'error');
            } finally {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            }
        }
        
        async function viewReport(reportId) {
            currentReportId = reportId;
            document.getElementById('reportModal').style.display = 'block';
            
            try {
                const response = await fetch(`/api/seo_analysis.php?report_id=${reportId}`, {
                    credentials: 'same-origin'
                });
                
                const result = await response.json();
                
                if (result.success) {
                    document.getElementById('reportTitle').textContent = result.data.title;
                    document.getElementById('reportContent').textContent = result.data.content;
                } else {
                    document.getElementById('reportContent').textContent = '載入報告失敗: ' + result.message;
                }
            } catch (error) {
                document.getElementById('reportContent').textContent = '載入報告失敗: ' + error.message;
            }
        }
        
        function downloadReport(reportId) {
            // TODO: Implement report download
            showNotification('下載功能開發中...', 'info');
        }
        
        function downloadCurrentReport() {
            if (currentReportId) {
                downloadReport(currentReportId);
            }
        }
        
        function showNotification(message, type = 'success') {
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.innerHTML = `
                <div class="notification-content">
                    <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                    <span>${message}</span>
                </div>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                notification.classList.add('show');
            }, 100);
            
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => {
                    if (document.body.contains(notification)) {
                        document.body.removeChild(notification);
                    }
                }, 300);
            }, 3000);
        }
    </script>
</body>
</html>

<?php
function getReportTypeName($type) {
    $types = [
        'basic' => '基礎分析',
        'keyword' => '關鍵字分析',
        'competitor' => '競爭對手分析',
        'technical' => '技術SEO分析'
    ];
    return $types[$type] ?? $type;
}

function getStatusName($status) {
    $statuses = [
        'completed' => '已完成',
        'processing' => '處理中',
        'failed' => '失敗'
    ];
    return $statuses[$status] ?? $status;
}
?>
