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

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

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

// Get tracking data
$tracking_data = [];
$query = "SELECT st.*, b.name as brand_name FROM seo_tracking st 
          LEFT JOIN brands b ON st.brand_id = b.id 
          ORDER BY st.tracking_date DESC LIMIT 50";
$stmt = $db->prepare($query);
$stmt->execute();
$tracking_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get summary stats
$stats = [];
$stats['total_keywords'] = $db->query("SELECT COUNT(DISTINCT keyword) FROM seo_tracking")->fetchColumn();
$stats['total_brands'] = $db->query("SELECT COUNT(*) FROM brands")->fetchColumn();
$stats['avg_ranking'] = $db->query("SELECT AVG(current_ranking) FROM seo_tracking WHERE current_ranking > 0")->fetchColumn();
$stats['total_reports'] = $db->query("SELECT COUNT(*) FROM seo_reports")->fetchColumn();
?>
<!DOCTYPE html>
<html lang="zh-TW">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成效分析 - 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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</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-line"></i>
                            <span>SEO報告</span>
                        </a>
                    </li>
                    <li>
                        <a href="content.php">
                            <i class="fas fa-edit"></i>
                            <span>內容管理</span>
                        </a>
                    </li>
                    <li class="active">
                        <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>
                </ul>
            </nav>
        </aside>
        
        <!-- Main Content -->
        <main class="main-content">
            <!-- Header -->
            <header class="header">
                <div class="header-left">
                    <h1>成效分析</h1>
                    <p>監控SEO成效和關鍵字排名變化</p>
                </div>
                <div class="header-right">
                    <button class="btn btn-primary" onclick="showAddTrackingModal()">
                        <i class="fas fa-plus"></i>
                        新增追蹤
                    </button>
                    <div class="user-menu">
                        <div class="user-info">
                            <i class="fas fa-user-circle"></i>
                            <span><?php echo htmlspecialchars($_SESSION['username']); ?></span>
                        </div>
                        <div class="user-dropdown">
                            <a href="profile.php"><i class="fas fa-user"></i> 個人資料</a>
                            <a href="settings.php"><i class="fas fa-cog"></i> 設定</a>
                            <a href="logout.php"><i class="fas fa-sign-out-alt"></i> 登出</a>
                        </div>
                    </div>
                </div>
            </header>
            
            <!-- Analytics Content -->
            <div class="analytics-content">
                <!-- Summary Stats -->
                <div class="stats-overview">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-key"></i>
                        </div>
                        <div class="stat-content">
                            <h3><?php echo $stats['total_keywords'] ?: 0; ?></h3>
                            <p>追蹤關鍵字</p>
                        </div>
                    </div>
                    
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-building"></i>
                        </div>
                        <div class="stat-content">
                            <h3><?php echo $stats['total_brands'] ?: 0; ?></h3>
                            <p>管理品牌</p>
                        </div>
                    </div>
                    
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-trophy"></i>
                        </div>
                        <div class="stat-content">
                            <h3><?php echo $stats['avg_ranking'] ? round($stats['avg_ranking'], 1) : 'N/A'; ?></h3>
                            <p>平均排名</p>
                        </div>
                    </div>
                    
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-chart-line"></i>
                        </div>
                        <div class="stat-content">
                            <h3><?php echo $stats['total_reports'] ?: 0; ?></h3>
                            <p>分析報告</p>
                        </div>
                    </div>
                </div>
                
                <!-- Charts Section -->
                <div class="charts-section">
                    <div class="chart-container">
                        <h3>關鍵字排名趨勢</h3>
                        <canvas id="rankingChart"></canvas>
                    </div>
                    
                    <div class="chart-container">
                        <h3>品牌表現分析</h3>
                        <canvas id="brandChart"></canvas>
                    </div>
                </div>
                
                <!-- Tracking Data Table -->
                <div class="tracking-section">
                    <div class="section-header">
                        <h3>關鍵字追蹤數據</h3>
                        <div class="table-actions">
                            <button class="btn btn-secondary" onclick="exportData()">
                                <i class="fas fa-download"></i>
                                匯出數據
                            </button>
                        </div>
                    </div>
                    
                    <?php if (empty($tracking_data)): ?>
                        <div class="empty-state">
                            <i class="fas fa-chart-line"></i>
                            <h3>尚無追蹤數據</h3>
                            <p>開始追蹤關鍵字排名變化</p>
                            <button class="btn btn-primary" onclick="showAddTrackingModal()">
                                <i class="fas fa-plus"></i>
                                新增追蹤
                            </button>
                        </div>
                    <?php else: ?>
                        <div class="table-container">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>品牌</th>
                                        <th>關鍵字</th>
                                        <th>當前排名</th>
                                        <th>上次排名</th>
                                        <th>變化</th>
                                        <th>搜尋量</th>
                                        <th>難度</th>
                                        <th>追蹤日期</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($tracking_data as $track): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($track['brand_name'] ?: '未指定'); ?></td>
                                            <td><?php echo htmlspecialchars($track['keyword']); ?></td>
                                            <td>
                                                <?php if ($track['current_ranking']): ?>
                                                    <span class="ranking-badge"><?php echo $track['current_ranking']; ?></span>
                                                <?php else: ?>
                                                    <span class="no-ranking">未排名</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($track['previous_ranking']): ?>
                                                    <?php echo $track['previous_ranking']; ?>
                                                <?php else: ?>
                                                    -
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php 
                                                if ($track['current_ranking'] && $track['previous_ranking']) {
                                                    $change = $track['previous_ranking'] - $track['current_ranking'];
                                                    if ($change > 0) {
                                                        echo '<span class="ranking-up"><i class="fas fa-arrow-up"></i> +' . $change . '</span>';
                                                    } elseif ($change < 0) {
                                                        echo '<span class="ranking-down"><i class="fas fa-arrow-down"></i> ' . $change . '</span>';
                                                    } else {
                                                        echo '<span class="ranking-same">-</span>';
                                                    }
                                                } else {
                                                    echo '-';
                                                }
                                                ?>
                                            </td>
                                            <td><?php echo $track['search_volume'] ? number_format($track['search_volume']) : '-'; ?></td>
                                            <td>
                                                <?php if ($track['difficulty_score']): ?>
                                                    <div class="difficulty-bar">
                                                        <div class="difficulty-fill" style="width: <?php echo $track['difficulty_score'] * 10; ?>%"></div>
                                                        <span><?php echo $track['difficulty_score']; ?>/10</span>
                                                    </div>
                                                <?php else: ?>
                                                    -
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo date('Y-m-d', strtotime($track['tracking_date'])); ?></td>
                                            <td>
                                                <button class="btn-icon" onclick="editTracking(<?php echo $track['id']; ?>)" title="編輯">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn-icon" onclick="deleteTracking(<?php echo $track['id']; ?>)" title="刪除">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>
    
    <style>
        .analytics-content {
            padding: 30px;
        }
        
        .stats-overview {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .charts-section {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 30px;
            margin-bottom: 30px;
        }
        
        .chart-container {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        }
        
        .chart-container h3 {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 20px;
        }
        
        .tracking-section {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        }
        
        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .section-header h3 {
            font-size: 1.3rem;
            font-weight: 600;
            color: #333;
        }
        
        .table-container {
            overflow-x: auto;
        }
        
        .ranking-badge {
            background: linear-gradient(135deg, #4ecdc4, #44a08d);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .no-ranking {
            color: #999;
            font-style: italic;
        }
        
        .ranking-up {
            color: #4ecdc4;
            font-weight: 600;
        }
        
        .ranking-down {
            color: #ff6b6b;
            font-weight: 600;
        }
        
        .ranking-same {
            color: #666;
        }
        
        .difficulty-bar {
            position: relative;
            background: #e0e0e0;
            height: 20px;
            border-radius: 10px;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .difficulty-fill {
            position: absolute;
            left: 0;
            top: 0;
            height: 100%;
            background: linear-gradient(135deg, #ff6b6b, #ee5a24);
            transition: width 0.3s ease;
        }
        
        .btn-icon {
            width: 30px;
            height: 30px;
            border: none;
            border-radius: 6px;
            background: #f8f9fa;
            color: #666;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin: 0 2px;
            transition: all 0.3s ease;
        }
        
        .btn-icon:hover {
            background: #e9ecef;
            color: #333;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        
        .empty-state i {
            font-size: 3rem;
            color: #667eea;
            margin-bottom: 15px;
        }
        
        .empty-state h3 {
            font-size: 1.3rem;
            color: #333;
            margin-bottom: 10px;
        }
        
        .empty-state p {
            color: #666;
            margin-bottom: 25px;
        }
    </style>
    
    <script src="../assets/js/admin.js"></script>
    <script>
        // Initialize charts
        document.addEventListener('DOMContentLoaded', function() {
            initRankingChart();
            initBrandChart();
        });
        
        function initRankingChart() {
            const ctx = document.getElementById('rankingChart').getContext('2d');
            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
                    datasets: [{
                        label: '平均排名',
                        data: [15, 12, 8, 6, 4, 3],
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            reverse: true,
                            title: {
                                display: true,
                                text: '排名位置'
                            }
                        }
                    }
                }
            });
        }
        
        function initBrandChart() {
            const ctx = document.getElementById('brandChart').getContext('2d');
            new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: ['品牌A', '品牌B', '品牌C', '其他'],
                    datasets: [{
                        data: [40, 30, 20, 10],
                        backgroundColor: [
                            '#667eea',
                            '#4ecdc4',
                            '#ff6b6b',
                            '#f8f9fa'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: {
                        legend: {
                            position: 'bottom'
                        }
                    }
                }
            });
        }
        
        function showAddTrackingModal() {
            alert('新增追蹤功能開發中...');
        }
        
        function exportData() {
            alert('匯出數據功能開發中...');
        }
        
        function editTracking(trackingId) {
            alert('編輯追蹤功能開發中...');
        }
        
        function deleteTracking(trackingId) {
            if (confirm('確定要刪除此追蹤記錄嗎？')) {
                alert('刪除追蹤功能開發中...');
            }
        }
    </script>
</body>
</html>
