<?php
// flowzoo/api/publish_task.php - 發布餵食任務引擎 (V3.1 修復秒數儲存版)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// 🛡️ 確保資料庫真的有秒數欄位 (防呆)
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN duration INT NOT NULL DEFAULT 15"); } catch (Exception $e) {}

$input = json_decode(file_get_contents("php://input"), true);

$creator_id = $input['creator_id'] ?? 0;
$title = $input['title'] ?? '';
$url = $input['url'] ?? '';
$description = $input['description'] ?? '';
$reward = (int)($input['reward'] ?? 0);
$quantity = (int)($input['quantity'] ?? 0);
$platform = $input['platform'] ?? 'Other';
$action_type = $input['action_type'] ?? 'view';

// ✨ 完美接收並儲存金主設定的秒數
$duration = (int)($input['duration'] ?? 15); 
$task_type = $input['task_type'] ?? 'screenshot';
$cooldown_minutes = ($task_type === 'timer') ? 5 : 0; 

$total_cost = $reward * $quantity;

if (!$creator_id || !$title || !$url || $reward <= 0 || $quantity <= 0) {
    echo json_encode(["status" => "error", "message" => "資料不完整或數值錯誤"]);
    exit;
}

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("SELECT coins FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$creator_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user || $user['coins'] < $total_cost) {
        throw new Exception("您的 ZOO 幣餘額不足！(需要 {$total_cost} ZOO)");
    }

    $stmt = $pdo->prepare("UPDATE users SET coins = coins - ? WHERE id = ?");
    $stmt->execute([$total_cost, $creator_id]);

    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'PUBLISH_TASK', ?, ?)");
    $stmt->execute([$creator_id, -$total_cost, "發布餵食任務：{$title}"]);

    // ✨ 寫入時，將 $duration 精準刻入資料庫
    $stmt = $pdo->prepare("INSERT INTO tasks (creator_id, title, url, description, platform, action_type, reward, budget, is_active, task_type, cooldown_minutes, duration) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)");
    $stmt->execute([$creator_id, $title, $url, $description, $platform, $action_type, $reward, $total_cost, $task_type, $cooldown_minutes, $duration]);

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => "🍎 任務發布成功！已扣除 {$total_cost} ZOO 幣。您的任務已進入雷達大廳！"]);

} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>