<?php
// api/create_task.php - 發布櫃台 (V3.8 精準報錯版)
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

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

// 🛡️ 精準報錯機制
if (!$data) {
    echo json_encode(["status" => "error", "message" => "資料格式錯誤 (JSON解析失敗)"]); exit;
}
if (!isset($data['user_id'])) {
    echo json_encode(["status" => "error", "message" => "缺少統帥 ID (user_id)"]); exit;
}
if (!isset($data['target_url']) || empty(trim($data['target_url']))) {
    echo json_encode(["status" => "error", "message" => "目標網址不能為空"]); exit;
}

$user_id = intval($data['user_id']);
$platform = $data['platform'];
$action = $data['action_type'];
$url = trim($data['target_url']);
$duration = isset($data['duration']) ? intval($data['duration']) : 20; 
$frontend_custom_cost = isset($data['custom_cost']) ? intval($data['custom_cost']) : 0;

// 計價與審核判定
$base_cost = ($duration == 600) ? 900 : $duration;
$FINAL_COST = max($base_cost, $frontend_custom_cost);
$REWARD = floor($FINAL_COST * 0.75);

$auto_platforms = ['WEB', 'YT_VIDEO', 'PODCAST'];
$proof = in_array($platform, $auto_platforms) ? 'AUTO' : 'SCREENSHOT';

try {
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("SELECT coins FROM users WHERE id = :id FOR UPDATE");
    $stmt->execute([':id' => $user_id]);
    $balance = $stmt->fetchColumn();

    if ($balance === false) {
        throw new Exception("找不到該統帥帳號 (ID: $user_id)");
    }
    if ($balance < $FINAL_COST) {
        throw new Exception("餘額不足！任務需 $FINAL_COST Z幣，您只有 $balance Z幣。");
    }

    $stmt = $pdo->prepare("UPDATE users SET coins = coins - :cost WHERE id = :id");
    $stmt->execute([':cost' => $FINAL_COST, ':id' => $user_id]);

    $sql = "INSERT INTO tasks (user_id, platform, action_type, target_url, duration, proof_req, cost, reward) 
            VALUES (:uid, :plat, :act, :url, :dur, :proof, :cost, :rew)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':uid' => $user_id,
        ':plat' => $platform,
        ':act' => $action,
        ':url' => $url,
        ':dur' => $duration,
        ':proof' => $proof,
        ':cost' => $FINAL_COST,
        ':rew' => $REWARD
    ]);

    $pdo->commit();
    echo json_encode(["status" => "success", "cost" => $FINAL_COST, "proof_type" => $proof]);

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