<?php
header('Content-Type: application/json');

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 '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();
            }
            
            // Perform SEO analysis based on type
            $analysis_result = performSEOAnalysis($brand, $analysis_type);
            
            // Save analysis result to database
            $save_query = "INSERT INTO seo_reports (brand_id, report_type, title, content, status, created_at) 
                          VALUES (:brand_id, :report_type, :title, :content, :status, NOW())";
            $save_stmt = $db->prepare($save_query);
            $save_stmt->bindParam(':brand_id', $brand_id);
            $save_stmt->bindParam(':report_type', $analysis_type);
            $save_stmt->bindParam(':title', $analysis_result['title']);
            $save_stmt->bindParam(':content', $analysis_result['content']);
            $save_stmt->bindParam(':status', $analysis_result['status']);
            $save_stmt->execute();
            
            $report_id = $db->lastInsertId();
            
            echo json_encode([
                'success' => true,
                'message' => 'SEO分析完成！',
                'data' => [
                    'report_id' => $report_id,
                    'analysis' => $analysis_result
                ]
            ]);
            
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => '分析失敗: ' . $e->getMessage()]);
        }
        break;
        
    case 'GET':
        $brand_id = $_GET['brand_id'] ?? '';
        $report_id = $_GET['report_id'] ?? '';
        
        try {
            if (!empty($report_id)) {
                // Get specific report
                $query = "SELECT * FROM seo_reports WHERE 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' => true, 'data' => $report]);
                } else {
                    echo json_encode(['success' => false, 'message' => '找不到報告']);
                }
            } else if (!empty($brand_id)) {
                // Get all reports for a brand
                $query = "SELECT * FROM seo_reports WHERE brand_id = :brand_id ORDER BY created_at DESC";
                $stmt = $db->prepare($query);
                $stmt->bindParam(':brand_id', $brand_id);
                $stmt->execute();
                $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode(['success' => true, 'data' => $reports]);
            } else {
                // Get all 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";
                $stmt = $db->prepare($query);
                $stmt->execute();
                $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode(['success' => true, 'data' => $reports]);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => '資料庫錯誤: ' . $e->getMessage()]);
        }
        break;
        
    default:
        echo json_encode(['success' => false, 'message' => '不支援的請求方法']);
        break;
}

function performSEOAnalysis($brand, $analysis_type) {
    // Try to use GPT API first, fallback to template if fails
    try {
        require_once __DIR__ . '/../includes/gpt_api.php';
        $gpt_api = new GPTAPI();
        
        $prompt = generatePrompt($brand, $analysis_type);
        $response = $gpt_api->generateContent($prompt, 2000);
        
        if (isset($response['success']) && $response['success']) {
            return [
                'title' => $brand['name'] . ' - ' . getAnalysisTypeName($analysis_type),
                'content' => $response['content'],
                'status' => 'completed'
            ];
        } else {
            // Fallback to template
            return generateTemplateAnalysis($brand, $analysis_type);
        }
    } catch (Exception $e) {
        // Fallback to template
        return generateTemplateAnalysis($brand, $analysis_type);
    }
}

function generatePrompt($brand, $analysis_type) {
    $base_prompt = "請為以下品牌進行SEO分析：\n\n";
    $base_prompt .= "品牌名稱：{$brand['name']}\n";
    $base_prompt .= "官方網站：{$brand['website']}\n";
    $base_prompt .= "行業類別：{$brand['industry']}\n";
    $base_prompt .= "品牌描述：{$brand['description']}\n";
    $base_prompt .= "目標關鍵字：{$brand['target_keywords']}\n";
    $base_prompt .= "競爭對手：{$brand['competitor_websites']}\n\n";
    
    switch ($analysis_type) {
        case 'basic':
            $base_prompt .= "請提供基礎SEO分析，包括：\n";
            $base_prompt .= "1. 品牌SEO現況評估\n";
            $base_prompt .= "2. 主要問題分析\n";
            $base_prompt .= "3. 優化建議\n";
            $base_prompt .= "4. 優先級排序\n";
            $base_prompt .= "5. 預期效果\n\n";
            $base_prompt .= "請以專業的SEO分析師角度，提供詳細且實用的建議。";
            break;
            
        case 'keyword':
            $base_prompt .= "請提供關鍵字分析，包括：\n";
            $base_prompt .= "1. 關鍵字競爭度分析\n";
            $base_prompt .= "2. 長尾關鍵字建議\n";
            $base_prompt .= "3. 關鍵字難度評估\n";
            $base_prompt .= "4. 搜尋量預估\n";
            $base_prompt .= "5. 關鍵字策略建議\n";
            $base_prompt .= "6. 內容規劃建議\n\n";
            $base_prompt .= "請提供具體的關鍵字列表和策略建議。";
            break;
            
        case 'competitor':
            $base_prompt .= "請提供競爭對手分析，包括：\n";
            $base_prompt .= "1. 競爭對手SEO策略分析\n";
            $base_prompt .= "2. 關鍵字競爭情況\n";
            $base_prompt .= "3. 內容策略比較\n";
            $base_prompt .= "4. 技術SEO比較\n";
            $base_prompt .= "5. 競爭優勢分析\n";
            $base_prompt .= "6. 超越策略建議\n\n";
            $base_prompt .= "請提供詳細的競爭分析和具體的超越建議。";
            break;
            
        case 'technical':
            $base_prompt .= "請提供技術SEO分析，包括：\n";
            $base_prompt .= "1. 網站技術SEO檢查\n";
            $base_prompt .= "2. 頁面速度優化建議\n";
            $base_prompt .= "3. 移動端優化建議\n";
            $base_prompt .= "4. 結構化數據建議\n";
            $base_prompt .= "5. 內部連結優化\n";
            $base_prompt .= "6. 技術問題修復建議\n\n";
            $base_prompt .= "請提供具體的技術優化建議和實施步驟。";
            break;
    }
    
    return $base_prompt;
}

function generateTemplateAnalysis($brand, $analysis_type) {
    $templates = [
        'basic' => [
            'title' => $brand['name'] . ' - SEO基礎分析報告',
            'content' => generateBasicTemplate($brand),
            'status' => 'completed'
        ],
        'keyword' => [
            'title' => $brand['name'] . ' - 關鍵字分析報告',
            'content' => generateKeywordTemplate($brand),
            'status' => 'completed'
        ],
        'competitor' => [
            'title' => $brand['name'] . ' - 競爭對手分析報告',
            'content' => generateCompetitorTemplate($brand),
            'status' => 'completed'
        ],
        'technical' => [
            'title' => $brand['name'] . ' - 技術SEO分析報告',
            'content' => generateTechnicalTemplate($brand),
            'status' => 'completed'
        ]
    ];
    
    return $templates[$analysis_type] ?? $templates['basic'];
}

function generateBasicTemplate($brand) {
    return "=== {$brand['name']} SEO基礎分析報告 ===

一、品牌現況評估
品牌名稱：{$brand['name']}
行業類別：{$brand['industry']}
官方網站：{$brand['website']}

二、主要問題分析
1. 網站結構需要優化
2. 關鍵字密度不足
3. 內容質量有待提升
4. 技術SEO基礎薄弱

三、優化建議
1. 改善網站結構和導航
2. 優化關鍵字策略
3. 提升內容質量
4. 加強技術SEO基礎

四、優先級排序
1. 高優先級：技術SEO基礎建設
2. 中優先級：關鍵字優化
3. 低優先級：內容擴充

五、預期效果
- 3個月內：技術問題修復完成
- 6個月內：關鍵字排名提升
- 12個月內：整體SEO表現顯著改善

注意：此為基礎模板分析，建議使用AI分析獲得更詳細的專業建議。";
}

function generateKeywordTemplate($brand) {
    return "=== {$brand['name']} 關鍵字分析報告 ===

一、目標關鍵字分析
主要關鍵字：{$brand['target_keywords']}

二、關鍵字競爭度評估
- 高競爭度關鍵字：需要長期投入
- 中競爭度關鍵字：建議重點關注
- 低競爭度關鍵字：快速見效機會

三、長尾關鍵字建議
1. 品牌相關長尾詞
2. 行業相關長尾詞
3. 產品/服務相關長尾詞

四、關鍵字策略建議
1. 主關鍵字：專注於品牌核心業務
2. 次關鍵字：覆蓋相關服務
3. 長尾關鍵字：提升整體覆蓋面

五、內容規劃建議
1. 針對主關鍵字創建核心頁面
2. 針對次關鍵字創建支援頁面
3. 針對長尾關鍵字創建內容文章

注意：此為基礎模板分析，建議使用AI分析獲得更詳細的關鍵字策略。";
}

function generateCompetitorTemplate($brand) {
    return "=== {$brand['name']} 競爭對手分析報告 ===

一、競爭對手識別
競爭對手網站：{$brand['competitor_websites']}

二、競爭對手SEO策略分析
1. 關鍵字策略分析
2. 內容策略分析
3. 技術SEO實現
4. 外部連結策略

三、競爭優勢分析
1. 我們的優勢
2. 競爭對手的優勢
3. 市場機會點

四、超越策略建議
1. 關鍵字策略優化
2. 內容差異化
3. 技術SEO提升
4. 用戶體驗改善

五、實施計劃
1. 短期目標（1-3個月）
2. 中期目標（3-6個月）
3. 長期目標（6-12個月）

注意：此為基礎模板分析，建議使用AI分析獲得更詳細的競爭策略。";
}

function generateTechnicalTemplate($brand) {
    return "=== {$brand['name']} 技術SEO分析報告 ===

一、網站技術檢查
網站地址：{$brand['website']}

二、技術SEO問題識別
1. 頁面速度問題
2. 移動端優化問題
3. 結構化數據缺失
4. 內部連結結構問題

三、優化建議
1. 頁面速度優化
   - 圖片壓縮
   - CSS/JS優化
   - 快取設置

2. 移動端優化
   - 響應式設計檢查
   - 移動端用戶體驗優化

3. 結構化數據
   - 添加Schema標記
   - 豐富摘要優化

4. 內部連結優化
   - 連結結構改善
   - 錨文字優化

四、實施優先級
1. 高優先級：頁面速度優化
2. 中優先級：移動端優化
3. 低優先級：結構化數據

五、預期效果
- 頁面載入速度提升50%
- 移動端用戶體驗改善
- 搜尋引擎理解度提升

注意：此為基礎模板分析，建議使用AI分析獲得更詳細的技術優化建議。";
}

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