<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../includes/auth.php';
require_once '../includes/gpt_api.php';
require_once '../config/database.php';

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

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

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'generate_content':
            generateContent($db, $input);
            break;
        case 'generate_outline':
            generateOutline($db, $input);
            break;
        case 'expand_section':
            expandSection($db, $input);
            break;
        case 'optimize_content':
            optimizeContent($db, $input);
            break;
        case 'generate_intro':
            generateIntro($db, $input);
            break;
        case 'generate_conclusion':
            generateConclusion($db, $input);
            break;
        default:
            throw new Exception('無效的操作');
    }
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

function generateContent($db, $input) {
    $plan_id = $input['plan_id'] ?? '';
    $title = $input['title'] ?? '';
    $keywords = $input['keywords'] ?? '';
    $content_type = $input['content_type'] ?? 'blog';
    $tone = $input['tone'] ?? 'professional';
    $length = $input['length'] ?? 'medium';
    $target_audience = $input['target_audience'] ?? '';
    
    if (empty($plan_id) && empty($title)) {
        throw new Exception('缺少計畫ID或標題');
    }
    
    // Get plan details if plan_id provided
    $plan = null;
    if (!empty($plan_id)) {
        $query = "SELECT cp.*, b.name as brand_name 
                  FROM content_plans cp 
                  LEFT JOIN brands b ON cp.brand_id = b.id 
                  WHERE cp.id = :plan_id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':plan_id', $plan_id);
        $stmt->execute();
        $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    
    // Prepare context for AI
    $context = [
        'title' => $title ?: $plan['title'] ?? '',
        'brand_name' => $plan['brand_name'] ?? '',
        'target_keywords' => $keywords ?: $plan['target_keywords'] ?? '',
        'content_type' => $content_type,
        'tone' => $tone,
        'length' => $length,
        'target_audience' => $target_audience,
        'plan_description' => $plan['description'] ?? ''
    ];
    
    // Generate content using GPT API
    $gpt = new GPTAPI();
    $content = $gpt->generateContent($context);
    
    // Save generation history
    saveGenerationHistory($db, $plan_id, 'content_generation', $context, $content);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'content' => $content,
            'context' => $context,
            'generated_at' => date('Y-m-d H:i:s')
        ]
    ]);
}

function generateOutline($db, $input) {
    $title = $input['title'] ?? '';
    $keywords = $input['keywords'] ?? '';
    $content_type = $input['content_type'] ?? 'blog';
    $length = $input['length'] ?? 'medium';
    
    if (empty($title)) {
        throw new Exception('缺少標題');
    }
    
    $gpt = new GPTAPI();
    $outline = $gpt->generateOutline($title, $keywords, $content_type, $length);
    
    echo json_encode([
        'success' => true,
        'data' => $outline
    ]);
}

function expandSection($db, $input) {
    $section_title = $input['section_title'] ?? '';
    $section_content = $input['section_content'] ?? '';
    $keywords = $input['keywords'] ?? '';
    $tone = $input['tone'] ?? 'professional';
    $length = $input['length'] ?? 'medium';
    
    if (empty($section_title)) {
        throw new Exception('缺少章節標題');
    }
    
    $gpt = new GPTAPI();
    $expanded = $gpt->expandSection($section_title, $section_content, $keywords, $tone, $length);
    
    echo json_encode([
        'success' => true,
        'data' => $expanded
    ]);
}

function optimizeContent($db, $input) {
    $content = $input['content'] ?? '';
    $keywords = $input['keywords'] ?? '';
    $target_audience = $input['target_audience'] ?? '';
    $seo_focus = $input['seo_focus'] ?? true;
    
    if (empty($content)) {
        throw new Exception('缺少內容');
    }
    
    $gpt = new GPTAPI();
    $optimized = $gpt->optimizeContent($content, $keywords, $target_audience, $seo_focus);
    
    echo json_encode([
        'success' => true,
        'data' => $optimized
    ]);
}

function generateIntro($db, $input) {
    $title = $input['title'] ?? '';
    $keywords = $input['keywords'] ?? '';
    $tone = $input['tone'] ?? 'professional';
    $hook_type = $input['hook_type'] ?? 'question';
    
    if (empty($title)) {
        throw new Exception('缺少標題');
    }
    
    $gpt = new GPTAPI();
    $intro = $gpt->generateIntro($title, $keywords, $tone, $hook_type);
    
    echo json_encode([
        'success' => true,
        'data' => $intro
    ]);
}

function generateConclusion($db, $input) {
    $title = $input['title'] ?? '';
    $content_summary = $input['content_summary'] ?? '';
    $keywords = $input['keywords'] ?? '';
    $tone = $input['tone'] ?? 'professional';
    $call_to_action = $input['call_to_action'] ?? '';
    
    if (empty($title)) {
        throw new Exception('缺少標題');
    }
    
    $gpt = new GPTAPI();
    $conclusion = $gpt->generateConclusion($title, $content_summary, $keywords, $tone, $call_to_action);
    
    echo json_encode([
        'success' => true,
        'data' => $conclusion
    ]);
}

function saveGenerationHistory($db, $plan_id, $generation_type, $context, $result) {
    $query = "INSERT INTO ai_generation_history (plan_id, generation_type, context, result, created_at) 
              VALUES (:plan_id, :generation_type, :context, :result, NOW())";
    $stmt = $db->prepare($query);
    $stmt->bindParam(':plan_id', $plan_id);
    $stmt->bindParam(':generation_type', $generation_type);
    $stmt->bindParam(':context', json_encode($context));
    $stmt->bindParam(':result', json_encode($result));
    $stmt->execute();
}
?>
