<?php
// mflowzoo/api/exchange_action.php - 行動宇宙：兌換扣款與防詐驗證
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

// 自動建立兌換訂單資料表
$pdo->exec("CREATE TABLE IF NOT EXISTS exchange_orders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    item_name VARCHAR(100) NOT NULL,
    item_type VARCHAR(20) NOT NULL,
    item_cost INT NOT NULL,
    delivery_method VARCHAR(20) NOT NULL DEFAULT 'virtual',
    shipping_fee INT NOT NULL DEFAULT 0,
    total_cost INT NOT NULL,
    contact_info TEXT NOT NULL,
    status VARCHAR(20) DEFAULT 'pending',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$input = json_decode(file_get_contents("php://input"), true);
$user_id = $input['user_id'] ?? 0;
$item_name = $input['item_name'] ?? '';
$delivery_method = $input['delivery_method'] ?? 'virtual'; 
$contact_info = $input['contact_info'] ?? '';

if (!$user_id || !$item_name || !$contact_info) {
    echo json_encode(["status" => "error", "message" => "資料不完整"]);
    exit;
}

try {
    $pdo->beginTransaction();

    // 從資料庫查詢該商品的真實售價與運費
    $stmt = $pdo->prepare("SELECT type, cost, shipping_fee FROM gifts WHERE name = ? LIMIT 1");
    $stmt->execute([$item_name]);
    $gift = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$gift) throw new Exception("查無此商品，或商品已下架！");

    $item_cost = (int)$gift['cost'];
    $item_type = $gift['type'];
    
    // 計算真實運費
    $real_shipping_fee = 0;
    if ($delivery_method === 'shipping' && $item_type === 'physical') {
        $real_shipping_fee = (int)$gift['shipping_fee'];
    }
    
    $total_cost = $item_cost + $real_shipping_fee;

    // 檢查餘額並鎖定
    $stmt = $pdo->prepare("SELECT coins FROM users WHERE id = ? FOR UPDATE");
    $stmt->execute([$user_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, $user_id]);

    // 寫入總帳明細 (商品與運費分開)
    $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'EXCHANGE', ?, ?)");
    $stmt->execute([$user_id, -$item_cost, "兌換禮品：{$item_name}"]);
    
    if ($real_shipping_fee > 0) {
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'SHIPPING_FEE', ?, ?)");
        $stmt->execute([$user_id, -$real_shipping_fee, "扣除物流寄送運費"]);
    }

    // 寫入兌換訂單
    $stmt = $pdo->prepare("INSERT INTO exchange_orders (user_id, item_name, item_type, item_cost, delivery_method, shipping_fee, total_cost, contact_info) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$user_id, $item_name, $item_type, $item_cost, $delivery_method, $real_shipping_fee, $total_cost, $contact_info]);

    $pdo->commit();
    echo json_encode(["status" => "success", "message" => "兌換申請成功！已扣除 {$total_cost} ZOO 幣，請等待天啟者審核發貨。"]);

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