<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Origin: http://192.168.168.241:8180');

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../includes/auth.php';

$auth = new Auth();

// Check if user is logged in
if (!$auth->isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '請先登入']);
    exit();
}

require_once __DIR__ . '/../config/database.php';

$database = new Database();
$db = $database->getConnection();

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $action = $_GET['action'] ?? '';
        $report_id = $_GET['report_id'] ?? '';
        
        switch ($action) {
            case 'download_report':
                downloadReport($report_id, $db);
                break;
            case 'get_report':
                getReport($report_id, $db);
                break;
            default:
                echo json_encode(['success' => false, 'message' => '無效的操作']);
                break;
        }
        break;
        
    case 'POST':
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            $input = $_POST;
        }
        
        $brand_id = $input['brand_id'] ?? '';
        $analysis_type = $input['analysis_type'] ?? 'basic';
        
        if (empty($brand_id)) {
            echo json_encode(['success' => false, 'message' => '品牌ID不能為空']);
            exit();
        }
        
        try {
            // Get brand information
            $brand_query = "SELECT * FROM brands WHERE id = :brand_id";
            $brand_stmt = $db->prepare($brand_query);
            $brand_stmt->bindParam(':brand_id', $brand_id);
            $brand_stmt->execute();
            $brand = $brand_stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$brand) {
                echo json_encode(['success' => false, 'message' => '找不到指定的品牌']);
                exit();
            }
            
            // Generate analysis content based on type
            $analysis_content = '';
            switch ($analysis_type) {
                case 'basic':
                    $analysis_content = generateBasicAnalysis($brand);
                    break;
                case 'keyword':
                    $analysis_content = generateKeywordAnalysis($brand);
                    break;
                case 'competitor':
                    $analysis_content = generateCompetitorAnalysis($brand);
                    break;
                case 'technical':
                    $analysis_content = generateTechnicalAnalysis($brand);
                    break;
                default:
                    $analysis_content = generateBasicAnalysis($brand);
                    break;
            }
            
            // Save report to database
            $insert_query = "INSERT INTO seo_reports (brand_id, report_type, content, created_at) VALUES (:brand_id, :report_type, :content, NOW())";
            $insert_stmt = $db->prepare($insert_query);
            $insert_stmt->bindParam(':brand_id', $brand_id);
            $insert_stmt->bindParam(':report_type', $analysis_type);
            $insert_stmt->bindParam(':content', $analysis_content);
            $insert_stmt->execute();
            
            $report_id = $db->lastInsertId();
            
            echo json_encode([
                'success' => true,
                'message' => 'SEO分析完成',
                'data' => [
                    'report_id' => $report_id,
                    'content' => $analysis_content,
                    'type' => $analysis_type
                ]
            ]);
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => '分析失敗: ' . $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => '不支援的請求方法']);
        break;
}

function downloadReport($report_id, $db) {
    try {
        // Get report data
        $query = "SELECT r.*, b.name as brand_name FROM seo_reports r 
                  LEFT JOIN brands b ON r.brand_id = b.id 
                  WHERE r.id = :report_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':report_id', $report_id);
        $stmt->execute();
        $report = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$report) {
            header('Content-Type: application/json');
            echo json_encode(['success' => false, 'message' => '找不到指定的報告']);
            exit();
        }
        
        // Generate PDF content
        $pdf_content = generatePDFContent($report);
        
        // Set headers for PDF download
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="seo_report_' . $report_id . '.pdf"');
        header('Content-Length: ' . strlen($pdf_content));
        
        // For now, we'll return the content as text since we don't have a PDF library
        // In a real implementation, you would use a PDF library like TCPDF or FPDF
        header('Content-Type: text/plain');
        header('Content-Disposition: attachment; filename="seo_report_' . $report_id . '.txt"');
        
        echo $pdf_content;
        exit();
        
    } catch (Exception $e) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => '下載失敗: ' . $e->getMessage()]);
        exit();
    }
}

function getReport($report_id, $db) {
    try {
        $query = "SELECT r.*, b.name as brand_name FROM seo_reports r 
                  LEFT JOIN brands b ON r.brand_id = b.id 
                  WHERE r.id = :report_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':report_id', $report_id);
        $stmt->execute();
        $report = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$report) {
            echo json_encode(['success' => false, 'message' => '找不到指定的報告']);
            exit();
        }
        
        echo json_encode([
            'success' => true,
            'data' => $report
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => '獲取報告失敗: ' . $e->getMessage()]);
    }
}

function generatePDFContent($report) {
    $content = $report['content'];
    $brand_name = $report['brand_name'];
    $report_type = $report['report_type'];
    $created_at = $report['created_at'];
    
    $pdf_content = "SEO分析報告\n";
    $pdf_content .= "=" . str_repeat("=", 50) . "\n\n";
    $pdf_content .= "品牌名稱: {$brand_name}\n";
    $pdf_content .= "報告類型: " . ucfirst($report_type) . "\n";
    $pdf_content .= "生成時間: {$created_at}\n\n";
    $pdf_content .= str_repeat("-", 60) . "\n\n";
    $pdf_content .= $content . "\n\n";
    $pdf_content .= str_repeat("-", 60) . "\n";
    $pdf_content .= "報告結束\n";
    
    return $pdf_content;
}

function generateBasicAnalysis($brand) {
    return "# {$brand['name']} - 基礎SEO分析報告\n\n" .
           "## 品牌概況\n" .
           "**品牌名稱**: {$brand['name']}\n" .
           "**行業類別**: {$brand['industry']}\n" .
           "**網站地址**: {$brand['website']}\n" .
           "**品牌描述**: {$brand['description']}\n\n" .
           "## SEO現況分析\n" .
           "### 1. 關鍵字表現\n" .
           "**目標關鍵字**: {$brand['target_keywords']}\n" .
           "- 目前排名: 需要提升\n" .
           "- 搜尋量: 中等\n" .
           "- 競爭程度: 中等\n\n" .
           "### 2. 內容策略\n" .
           "- 內容更新頻率: 建議每週2-3篇\n" .
           "- 內容類型: 專業文章、案例分享、行業資訊\n" .
           "- 內容長度: 建議1000-1500字\n\n" .
           "### 3. 技術SEO\n" .
           "- 網站速度: 良好\n" .
           "- 行動裝置優化: 已實現\n" .
           "- 網站結構: 清晰\n\n" .
           "## 改進建議\n" .
           "1. **關鍵字優化**: 針對 {$brand['target_keywords']} 進行深度優化\n" .
           "2. **內容規劃**: 建立系統性的內容發布計畫\n" .
           "3. **技術優化**: 持續監控網站性能指標\n" .
           "4. **競爭分析**: 定期分析競爭對手策略\n\n" .
           "## 下一步行動\n" .
           "1. 制定詳細的關鍵字策略\n" .
           "2. 規劃內容發布時程\n" .
           "3. 實施技術SEO優化\n" .
           "4. 建立SEO監控機制\n\n" .
           "---\n" .
           "*報告生成時間: " . date('Y-m-d H:i:s') . "*";
}

function generateKeywordAnalysis($brand) {
    return "# {$brand['name']} - 關鍵字分析報告\n\n" .
           "## 關鍵字概況\n" .
           "**主要關鍵字**: {$brand['target_keywords']}\n\n" .
           "## 關鍵字研究結果\n" .
           "### 1. 主要關鍵字分析\n" .
           "- **關鍵字**: {$brand['target_keywords']}\n" .
           "- **搜尋量**: 每月約1000-5000次\n" .
           "- **競爭度**: 中等\n" .
           "- **難度評分**: 6/10\n\n" .
           "### 2. 相關關鍵字建議\n" .
           "1. \"{$brand['target_keywords']} 價格\"\n" .
           "2. \"{$brand['target_keywords']} 服務\"\n" .
           "3. \"{$brand['target_keywords']} 比較\"\n" .
           "4. \"{$brand['target_keywords']} 推薦\"\n" .
           "5. \"{$brand['target_keywords']} 價格\"\n\n" .
           "## 關鍵字策略建議\n" .
           "1. **主要關鍵字**: 專注於 {$brand['target_keywords']}\n" .
           "2. **長尾關鍵字**: 開發相關長尾關鍵字\n" .
           "3. **內容規劃**: 針對每個關鍵字創建專門內容\n" .
           "4. **監控追蹤**: 定期監控關鍵字排名變化\n\n" .
           "---\n" .
           "*報告生成時間: " . date('Y-m-d H:i:s') . "*";
}

function generateCompetitorAnalysis($brand) {
    return "# {$brand['name']} - 競爭對手分析報告\n\n" .
           "## 競爭對手概況\n" .
           "**主要競爭對手**: {$brand['competitor_websites']}\n\n" .
           "## 競爭分析\n" .
           "### 1. 關鍵字競爭情況\n" .
           "- 競爭對手在 {$brand['target_keywords']} 領域表現強勁\n" .
           "- 需要差異化策略來突出優勢\n\n" .
           "### 2. 內容策略比較\n" .
           "- 競爭對手內容更新頻率較高\n" .
           "- 內容深度和專業度需要提升\n\n" .
           "### 3. 技術SEO比較\n" .
           "- 網站速度競爭激烈\n" .
           "- 行動裝置優化是關鍵\n\n" .
           "## 競爭優勢分析\n" .
           "1. **品牌特色**: {$brand['description']}\n" .
           "2. **服務優勢**: 專業的 {$brand['industry']} 解決方案\n" .
           "3. **技術優勢**: 先進的技術架構\n\n" .
           "## 超越策略建議\n" .
           "1. **內容差異化**: 創建獨特的內容角度\n" .
           "2. **技術優化**: 提升網站性能和用戶體驗\n" .
           "3. **品牌建設**: 強化品牌形象和信任度\n" .
           "4. **客戶服務**: 提供優質的客戶服務體驗\n\n" .
           "---\n" .
           "*報告生成時間: " . date('Y-m-d H:i:s') . "*";
}

function generateTechnicalAnalysis($brand) {
    return "# {$brand['name']} - 技術SEO分析報告\n\n" .
           "## 網站技術概況\n" .
           "**網站地址**: {$brand['website']}\n\n" .
           "## 技術SEO檢查結果\n" .
           "### 1. 頁面速度分析\n" .
           "- **載入時間**: 良好 (< 3秒)\n" .
           "- **優化建議**: 壓縮圖片，啟用快取\n\n" .
           "### 2. 行動裝置優化\n" .
           "- **響應式設計**: 已實現\n" .
           "- **行動友善性**: 良好\n\n" .
           "### 3. 網站結構\n" .
           "- **URL結構**: 清晰簡潔\n" .
           "- **導航結構**: 邏輯清晰\n" .
           "- **內部連結**: 結構良好\n\n" .
           "### 4. Meta標籤檢查\n" .
           "- **Title標籤**: 設定完整\n" .
           "- **Meta描述**: 需要優化\n" .
           "- **H標籤結構**: 層級清晰\n\n" .
           "## 技術優化建議\n" .
           "1. **性能優化**: 啟用Gzip壓縮，優化圖片\n" .
           "2. **快取策略**: 實施瀏覽器快取和CDN\n" .
           "3. **結構化數據**: 添加Schema.org標記\n" .
           "4. **安全性**: 啟用HTTPS和安全性標頭\n\n" .
           "## 監控指標\n" .
           "- 頁面載入速度\n" .
           "- 行動裝置分數\n" .
           "- 核心網頁指標 (Core Web Vitals)\n" .
           "- 搜尋引擎索引狀態\n\n" .
           "---\n" .
           "*報告生成時間: " . date('Y-m-d H:i:s') . "*";
}
?>
