<?php
// mission.php - SDK 指揮中心 (V2.2 百變怪隨機版)
// --------------------------------------------------
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// 1. 引入資料庫 (為了寫日記)
require_once 'db.php';

// 2. 定義情境池 (這是兔子的劇本)
// 格式：[圖片ID, 對話內容]
$scenarios = [
    // --- 30% 機率：賣萌待機 ---
    ['id' => 'zoo_idle',        'msg' => 'ZOO 團隊待命狀態... (搖尾巴)'],
    ['id' => 'zoo_ask',         'msg' => '天啟者，下一步指令是什麼？'],
    ['id' => 'zoo_hi',          'msg' => '吾乃伏羲，很高興為您服務。'],
    
    // --- 50% 機率：派發任務 ---
    ['id' => 'zoo_new_task',    'msg' => '注意！新的流量任務已抵達！'],
    ['id' => 'zoo_action_like', 'msg' => '立刻按讚，累積您的數位福報！'],
    ['id' => 'zoo_action_video','msg' => '請看 VCR，見證奇蹟的時刻。'],
    ['id' => 'zoo_start',       'msg' => '遊戲開始！流量引擎已啟動。'],
    
    // --- 20% 機率：心靈雞湯 ---
    ['id' => 'zoo_rich',        'msg' => '百萬期望值！堅持就是勝利。'],
    ['id' => 'zoo_morale',      'msg' => '團隊士氣大增！我們是最強的。'],
    ['id' => 'zoo_success',     'msg' => '恭喜！您今天看起來運氣不錯。']
];

// 3. 隨機抽選 (RNG)
// array_rand 回傳的是 key (索引)
$key = array_rand($scenarios);
$chosen_one = $scenarios[$key];

// 4. 捕捉數據
$visitor_ip = $_SERVER['REMOTE_ADDR'];
$mission_id = $chosen_one['id']; // 這次抽到的 ID

// 5. 寫入黑盒子 (記錄這次兔子變成了什麼)
try {
    $sql = "INSERT INTO mission_logs (ip, mission) VALUES (:ip, :mission)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':ip' => $visitor_ip,
        ':mission' => $mission_id
    ]);
} catch (Exception $e) {
    // 保持沉默，不影響前端顯示
}

// 6. 輸出指令 (回傳給 SDK)
$response_data = [
    "status" => "active",
    "mascot_id" => $mission_id,
    "message" => $chosen_one['msg'], // 這是隨機選出的話
    "link" => "https://flowzoo.com.tw/flowzoo/index.html",
    // 自動組合成完整的圖片網址
    "image_url" => "https://flowzoo.com.tw/flowzoo/images/" . $mission_id . ".jpg"
];

echo json_encode($response_data);
?>