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

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

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

// Simple session management for chat
$input = json_decode(file_get_contents('php://input'), true);
$message = $input['message'] ?? '';
$session_id = $input['session_id'] ?? '';

if (empty($message)) {
    echo json_encode(['error' => 'No message provided']);
    exit();
}

// Initialize GPT API
$gpt = new GPTAPI();

// Create SEO-focused prompt
$seo_prompt = "你是一個專業的SEO顧問和數位行銷專家。請回答以下問題，並提供實用的建議：\n\n";
$seo_prompt .= "用戶問題：" . $message . "\n\n";
$seo_prompt .= "請提供專業、詳細且實用的回答，包括：\n";
$seo_prompt .= "1. 直接回答問題\n";
$seo_prompt .= "2. 提供具體的實施建議\n";
$seo_prompt .= "3. 如果適用，提供相關的工具或資源\n";
$seo_prompt .= "4. 保持回答簡潔但完整\n\n";
$seo_prompt .= "請用繁體中文回答。";

// Get AI response
$response = $gpt->generateContent($seo_prompt, 1000);

if (isset($response['success']) && $response['success']) {
    // Save chat message to database
    try {
        require_once __DIR__ . '/../config/database.php';
        $database = new Database();
        $db = $database->getConnection();
        
        // Save user message
        $query = "INSERT INTO chat_messages (session_id, role, content) VALUES (:session_id, 'user', :content)";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':session_id', $session_id);
        $stmt->bindParam(':content', $message);
        $stmt->execute();
        
        // Save AI response
        $query = "INSERT INTO chat_messages (session_id, role, content) VALUES (:session_id, 'assistant', :content)";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':session_id', $session_id);
        $stmt->bindParam(':content', $response['content']);
        $stmt->execute();
        
    } catch (Exception $e) {
        // Continue even if database save fails
        error_log('Chat save error: ' . $e->getMessage());
    }
    
    echo json_encode([
        'success' => true,
        'response' => $response['content']
    ]);
} else {
    // Fallback responses for common SEO questions
    $fallback_responses = [
        'seo' => 'SEO（搜尋引擎優化）是提升網站在搜尋引擎中排名的技術。主要包含技術SEO、內容優化、關鍵字研究、連結建設等策略。',
        '關鍵字' => '關鍵字研究是SEO的基礎。建議使用Google Keyword Planner、Ahrefs、SEMrush等工具來找到相關且競爭度適中的關鍵字。',
        '內容' => '優質內容是SEO成功的關鍵。內容應該原創、有價值、符合用戶需求，並適當融入目標關鍵字。',
        '排名' => '提升搜尋排名需要時間和持續努力。通常需要3-6個月才能看到明顯效果。建議專注於技術優化、內容品質和用戶體驗。',
        '分析' => 'SEO分析工具包括Google Analytics、Google Search Console、Ahrefs、SEMrush等。定期監控流量、排名和轉換率變化。'
    ];
    
    $response_text = '我是一個SEO AI助手，可以幫助您解答SEO相關問題。請告訴我您想了解什麼？';
    
    foreach ($fallback_responses as $keyword => $response) {
        if (strpos(strtolower($message), $keyword) !== false) {
            $response_text = $response;
            break;
        }
    }
    
    echo json_encode([
        'success' => true,
        'response' => $response_text
    ]);
}
?>
