<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$input = json_decode(file_get_contents("php://input"), true);
$admin_id = $input['admin_id'] ?? 0;
$order_id = $input['order_id'] ?? 0;
$action = $input['action'] ?? '';

try {
    $pdo->beginTransaction();
    
    // 驗證天啟者
    $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
    $stmt->execute([$admin_id]);
    if ($stmt->fetchColumn() < 99) throw new Exception("天啟禁區");

    // 鎖定該筆訂單
    $stmt = $pdo->prepare("SELECT * FROM exchange_orders WHERE id = ? FOR UPDATE");
    $stmt->execute([$order_id]);
    $order = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$order || $order['status'] !== 'pending') throw new Exception("訂單不存在或已處理");

    if ($action === 'approve') {
        // 核准：標記完成
        $stmt = $pdo->prepare("UPDATE exchange_orders SET status = 'completed' WHERE id = ?");
        $stmt->execute([$order_id]);
        $msg = "已標記為完成發貨/面交！";
    } else if ($action === 'reject') {
        // 詐欺退回：狀態改為 rejected，並將 ZOO 幣全額退還給使用者
        $stmt = $pdo->prepare("UPDATE exchange_orders SET status = 'rejected' WHERE id = ?");
        $stmt->execute([$order_id]);
        
        $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
        $stmt->execute([$order['total_cost'], $order['user_id']]);
        
        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'REFUND', ?, ?)");
        $stmt->execute([$order['user_id'], $order['total_cost'], "⚠️ 天啟退回詐欺/資料不符訂單：{$order['item_name']}"]);
        
        $msg = "已標記詐欺！全額 ZOO 幣已退還並作廢訂單。";
    }

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