<?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);

// Get brands for report generation
$brands_query = "SELECT * FROM brands ORDER BY name";
$brands_stmt = $db->prepare($brands_query);
$brands_stmt->execute();
$brands = $brands_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">
    <style>
        .reports-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
            gap: 25px;
            margin-top: 20px;
        }
        
        .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-header h3 {
            font-size: 1.2rem;
            color: #333;
            margin: 0;
        }
        
        .report-type {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
            background: #e3f2fd;
            color: #1976d2;
        }
        
        .report-info {
            margin-bottom: 20px;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 10px;
            color: #666;
            font-size: 0.9rem;
        }
        
        .info-item i {
            width: 16px;
            color: #667eea;
        }
        
        .report-actions {
            display: flex;
            gap: 10px;
        }
        
        .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;
        }
        
        .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;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-info {
            background: #17a2b8;
            color: white;
        }
        
        .btn-info:hover {
            background: #138496;
        }
        
        .btn-warning {
            background: #ffc107;
            color: #212529;
        }
        
        .btn-warning:hover {
            background: #e0a800;
        }
        
        .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-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;
        }
    </style>
</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-bar"></i>
                            <span>SEO報告</span>
                        </a>
                    </li>
                    <li>
                        <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>查看和管理SEO分析報告</p>
                </div>
                <div class="header-right">
                    <button class="btn btn-primary" onclick="showGenerateReportModal()">
                        <i class="fas fa-plus"></i>
                        生成報告
                    </button>
                </div>
            </header>
            
            <div class="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-plus"></i>
                            生成報告
                        </button>
                    </div>
                <?php else: ?>
                    <div class="reports-grid">
                        <?php foreach ($reports as $report): ?>
                            <div class="report-card">
                                <div class="report-header">
                                    <h3><?php echo htmlspecialchars($report['brand_name']); ?></h3>
                                    <span class="report-type"><?php echo ucfirst($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-chart-bar"></i>
                                        <span>報告類型: <?php echo ucfirst($report['report_type']); ?></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>
                                
                                <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>
                                    <button class="btn btn-warning" 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">
                <div 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 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="analysis_type" class="form-control" required>
                            <option value="basic">基礎分析</option>
                            <option value="keyword">關鍵字分析</option>
                            <option value="competitor">競爭對手分析</option>
                            <option value="technical">技術SEO分析</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" onclick="closeModal('generateReportModal')">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-magic"></i>
                        生成報告
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Handle generate report form submission
            const generateReportForm = document.getElementById('generateReportForm');
            if (generateReportForm) {
                generateReportForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    generateReport();
                });
            }
        });
        
        function showGenerateReportModal() {
            document.getElementById('generateReportModal').style.display = 'block';
        }
        
        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }
        
        function viewReport(reportId) {
            // Open report in new window
            window.open(`seo_analysis.php?report_id=${reportId}`, '_blank');
        }
        
        function downloadReport(reportId) {
            // Create a temporary link to download the report
            const link = document.createElement('a');
            link.href = `/api/seo_analysis.php?action=download_report&report_id=${reportId}`;
            link.download = `seo_report_${reportId}.txt`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            showNotification('報告下載已開始！', 'success');
        }
        
        function deleteReport(reportId) {
            if (confirm('確定要刪除此報告嗎？')) {
                deleteReportConfirm(reportId);
            }
        }
        
        function deleteReportConfirm(reportId) {
            fetch('/api/reports.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) {
                    showNotification('報告刪除成功！', 'success');
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    showNotification('刪除失敗: ' + result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('網路錯誤，請稍後再試', 'error');
            });
        }
        
        function generateReport() {
            const form = document.getElementById('generateReportForm');
            const formData = new FormData(form);
            const data = Object.fromEntries(formData);
            
            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 生成中...';
            submitBtn.disabled = true;
            
            fetch('/api/seo_analysis.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                credentials: 'same-origin',
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showNotification('報告生成成功！', 'success');
                    closeModal('generateReportModal');
                    form.reset();
                    setTimeout(() => {
                        location.reload();
                    }, 1000);
                } else {
                    showNotification('生成失敗: ' + result.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('網路錯誤，請稍後再試', 'error');
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
        }
        
        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' : 'exclamation-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);
        }
        
        // 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>
