<?php
// mflowzoo/api/publish_task.php - 手機版發布任務引擎 (獨立修復版)
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 task_type VARCHAR(20) NOT NULL DEFAULT 'screenshot'"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN cooldown_minutes INT NOT NULL DEFAULT 0"); } catch (Exception $e) {}
try { $pdo->exec("ALTER TABLE tasks ADD COLUMN is_active TINYINT(1) NOT NULL DEFAULT 1"); } catch (Exception $e) {}
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);

// ✨ 抓取手機前端傳來的分類與秒數
$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("餘額不足！");

    $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}"]);

    // ✨ 完美寫入所有新欄位
    $stmt = $pdo->prepare("INSERT INTO tasks (creator_id, title, url, description, reward, budget, is_active, task_type, cooldown_minutes, duration) VALUES (?, ?, ?, ?, ?, ?, 1, ?, ?, ?)");
    $stmt->execute([$creator_id, $title, $url, $description, $reward, $total_cost, $task_type, $cooldown_minutes, $duration]);

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => "🍎 任務發布成功！"]);
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>