<?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_titles':
            generateTitles($db, $input);
            break;
        case 'analyze_title':
            analyzeTitle($db, $input);
            break;
        case 'optimize_title':
            optimizeTitle($db, $input);
            break;
        default:
            throw new Exception('無效的操作');
    }
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

function generateTitles($db, $input) {
    $plan_id = $input['plan_id'] ?? '';
    $keywords = $input['keywords'] ?? '';
    $brand_name = $input['brand_name'] ?? '';
    $content_type = $input['content_type'] ?? 'blog';
    $tone = $input['tone'] ?? 'professional';
    $count = $input['count'] ?? 5;
    
    if (empty($plan_id)) {
        throw new Exception('缺少計畫ID');
    }
    
    // Get plan details
    $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);
    
    if (!$plan) {
        throw new Exception('找不到內容計畫');
    }
    
    // Prepare context for AI
    $context = [
        'plan_title' => $plan['title'],
        'brand_name' => $plan['brand_name'] ?: $brand_name,
        'target_keywords' => $plan['target_keywords'] ?: $keywords,
        'content_type' => $content_type,
        'tone' => $tone,
        'count' => $count
    ];
    
    // Generate titles using GPT API
    $gpt = new GPTAPI();
    $titles = $gpt->generateTitles($context);
    
    // Save generation history
    saveGenerationHistory($db, $plan_id, $context, $titles);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'titles' => $titles,
            'context' => $context,
            'generated_at' => date('Y-m-d H:i:s')
        ]
    ]);
}

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

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

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