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

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

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

$reports = [];
$query = "SELECT r.*, b.name as brand_name FROM seo_reports r 
          LEFT JOIN brands b ON r.brand_id = b.id 
          ORDER BY r.created_at DESC";
$stmt = $db->prepare($query);
$stmt->execute();
$reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!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 class="active">
                        <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>
                        <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>SEO報告</h1>
                    <p>管理SEO分析報告和診斷結果</p>
                </div>
                <div class="header-right">
                    <button class="btn btn-primary" onclick="showGenerateReportModal()">
                        <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>
            
            <!-- Reports Content -->
            <div class="reports-content">
                <?php if (empty($reports)): ?>
                    <div class="empty-state">
                        <i class="fas fa-chart-line"></i>
                        <h3>尚無SEO報告</h3>
                        <p>開始生成您的第一個SEO分析報告</p>
                        <button class="btn btn-primary" onclick="showGenerateReportModal()">
                            <i class="fas fa-magic"></i>
                            生成SEO報告
                        </button>
                    </div>
                <?php else: ?>
                    <div class="reports-grid">
                        <?php foreach ($reports as $report): ?>
                            <div class="report-card">
                                <div class="report-header">
                                    <div class="report-type">
                                        <i class="fas fa-<?php echo $report['report_type'] === 'health_check' ? 'heartbeat' : ($report['report_type'] === 'competitor_analysis' ? 'users' : ($report['report_type'] === 'keyword_analysis' ? 'key' : 'file-alt')); ?>"></i>
                                        <span><?php 
                                            $types = [
                                                'health_check' => '健康檢查',
                                                'competitor_analysis' => '競業分析',
                                                'keyword_analysis' => '關鍵字分析',
                                                'content_audit' => '內容審計'
                                            ];
                                            echo $types[$report['report_type']] ?? $report['report_type'];
                                        ?></span>
                                    </div>
                                    <div class="report-status">
                                        <span class="status-badge status-<?php echo $report['status']; ?>">
                                            <?php 
                                                $statuses = [
                                                    'pending' => '等待中',
                                                    'processing' => '處理中',
                                                    'completed' => '已完成',
                                                    'failed' => '失敗'
                                                ];
                                                echo $statuses[$report['status']] ?? $report['status'];
                                            ?>
                                        </span>
                                    </div>
                                </div>
                                
                                <div class="report-info">
                                    <h3><?php echo htmlspecialchars($report['title']); ?></h3>
                                    <p class="report-brand">
                                        <i class="fas fa-building"></i>
                                        <?php echo htmlspecialchars($report['brand_name'] ?: '未指定品牌'); ?>
                                    </p>
                                    <p class="report-date">
                                        <i class="fas fa-calendar"></i>
                                        <?php echo date('Y-m-d H:i', strtotime($report['created_at'])); ?>
                                    </p>
                                </div>
                                
                                <div class="report-actions">
                                    <button class="btn btn-secondary" onclick="viewReport(<?php echo $report['id']; ?>)">
                                        <i class="fas fa-eye"></i>
                                        查看
                                    </button>
                                    <?php if ($report['status'] === 'completed'): ?>
                                        <button class="btn btn-primary" onclick="downloadReport(<?php echo $report['id']; ?>)">
                                            <i class="fas fa-download"></i>
                                            下載
                                        </button>
                                    <?php endif; ?>
                                    <button class="btn btn-danger" onclick="deleteReport(<?php echo $report['id']; ?>)">
                                        <i class="fas fa-trash"></i>
                                        刪除
                                    </button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>
    
    <!-- Generate Report Modal -->
    <div id="generateReportModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>生成SEO報告</h2>
                <button class="modal-close" onclick="closeModal('generateReportModal')">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form id="generateReportForm" class="modal-body">
                <div class="form-group">
                    <label for="reportBrand">選擇品牌 *</label>
                    <select id="reportBrand" name="brand_id" class="form-control" required>
                        <option value="">請選擇品牌</option>
                        <?php
                        $brands_query = "SELECT id, name FROM brands ORDER BY name";
                        $brands_stmt = $db->prepare($brands_query);
                        $brands_stmt->execute();
                        $brands = $brands_stmt->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($brands as $brand): ?>
                            <option value="<?php echo $brand['id']; ?>"><?php echo htmlspecialchars($brand['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="reportType">報告類型 *</label>
                    <select id="reportType" name="report_type" class="form-control" required>
                        <option value="">請選擇報告類型</option>
                        <option value="health_check">SEO健康檢查</option>
                        <option value="competitor_analysis">競業分析</option>
                        <option value="keyword_analysis">關鍵字分析</option>
                        <option value="content_audit">內容審計</option>
                    </select>
                </div>
                
                <div class="form-group">
                    <label for="reportTitle">報告標題 *</label>
                    <input type="text" id="reportTitle" name="title" class="form-control" required placeholder="請輸入報告標題">
                </div>
                
                <div class="form-group">
                    <label for="reportDescription">報告描述</label>
                    <textarea id="reportDescription" name="description" class="form-control" rows="3" placeholder="請描述報告的目的和重點..."></textarea>
                </div>
            </form>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('generateReportModal')">取消</button>
                <button type="submit" form="generateReportForm" class="btn btn-primary">
                    <i class="fas fa-magic"></i>
                    生成報告
                </button>
            </div>
        </div>
    </div>
    
    <style>
        .reports-content {
            padding: 30px;
        }
        
        .empty-state {
            text-align: center;
            padding: 80px 20px;
            background: white;
            border-radius: 15px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
        }
        
        .empty-state i {
            font-size: 4rem;
            color: #667eea;
            margin-bottom: 20px;
        }
        
        .empty-state h3 {
            font-size: 1.5rem;
            color: #333;
            margin-bottom: 10px;
        }
        
        .empty-state p {
            color: #666;
            margin-bottom: 30px;
        }
        
        .reports-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 25px;
        }
        
        .report-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.08);
            transition: transform 0.3s ease;
        }
        
        .report-card:hover {
            transform: translateY(-5px);
        }
        
        .report-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .report-type {
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 600;
            color: #667eea;
        }
        
        .report-type i {
            font-size: 1.2rem;
        }
        
        .report-info h3 {
            font-size: 1.3rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 15px;
        }
        
        .report-brand, .report-date {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 8px;
        }
        
        .report-brand i, .report-date i {
            width: 16px;
            color: #667eea;
        }
        
        .report-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }
        
        .report-actions .btn {
            flex: 1;
            padding: 8px 12px;
            font-size: 0.85rem;
        }
        
        /* 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);
            backdrop-filter: blur(5px);
        }
        
        .modal-content {
            background-color: white;
            margin: 5% auto;
            border-radius: 15px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
        }
        
        .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;
        }
    </style>
    
    <script src="../assets/js/admin.js"></script>
    <script>
        function showGenerateReportModal() {
            document.getElementById('generateReportModal').style.display = 'block';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function viewReport(reportId) {
            // TODO: Implement view functionality
            viewReportDetails(reportId);
        }
        
        function downloadReport(reportId) {
            // TODO: Implement download functionality
            downloadReportFile(reportId);
        }
        
        function deleteReport(reportId) {
            if (confirm('確定要刪除此報告嗎？')) {
                // TODO: Implement delete functionality
                deleteReportConfirm(reportId);
            }
        }
        
        // Handle form submission
        document.getElementById('generateReportForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const data = Object.fromEntries(formData);
            
            // TODO: Send to API
            console.log('Report data:', data);
            generateReport(data);
            closeModal('generateReportModal');
        
        function viewReportDetails(reportId) {
            window.location.href = `seo_analysis.php?report_id=${reportId}`;
        }
        
        function downloadReportFile(reportId) {
            fetch(`/api/seo_analysis.php?action=download_report&report_id=${reportId}`, {
                method: 'GET',
                credentials: 'same-origin'
            })
            .then(response => {
                if (response.ok) {
                    return response.blob();
                }
                throw new Error('下載失敗');
            })
            .then(blob => {
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `seo_report_${reportId}.pdf`;
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                alert('報告下載成功！');
            })
            .catch(error => {
                console.error('Error:', error);
                alert('下載失敗: ' + error.message);
            });
        }
        
        function deleteReportConfirm(reportId) {
            fetch('/api/seo_analysis.php', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    action: 'delete_report',
                    report_id: reportId
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('報告刪除成功！');
                    location.reload();
                } else {
                    alert('刪除失敗: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('網路錯誤，請稍後再試');
            });
        }
        
        function generateReport(data) {
            fetch('/api/seo_analysis.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify({
                    action: 'generate_report',
                    ...data
                })
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('報告生成成功！');
                    location.reload();
                } else {
                    alert('生成失敗: ' + result.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('網路錯誤，請稍後再試');
            });
        }
        });
        
        // Close modal when clicking outside
        window.addEventListener('click', function(e) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                if (e.target === modal) {
                    modal.style.display = 'none';
                }
            });
        });
    </script>
</body>
</html>
