<?php
// api/admin_exchange_action.php - 天啟者發貨中心
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$method = $_SERVER['REQUEST_METHOD'];
$input = json_decode(file_get_contents("php://input"), true);

function checkAdmin($pdo, $admin_id) {
    $stmt = $pdo->prepare("SELECT level FROM users WHERE id = ?");
    $stmt->execute([$admin_id]);
    if ($stmt->fetchColumn() < 99) { echo json_encode(["status" => "error", "message" => "權限不足"]); exit; }
}

// 🟢 GET: 列出待處理訂單
if ($method === 'GET') {
    // 撈出 status = 'pending' 的訂單，並關聯使用者名稱
    $sql = "SELECT e.*, u.username FROM exchange_requests e 
            LEFT JOIN users u ON e.user_id = u.id 
            WHERE e.status = 'pending' 
            ORDER BY e.created_at ASC";
    $stmt = $pdo->query($sql);
    echo json_encode(["status" => "success", "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

// 🔴 POST: 執行發貨 (Approve) 或 退單 (Reject)
if ($method === 'POST') {
    $admin_id = $input['admin_id'] ?? 0;
    $order_id = $input['order_id'] ?? 0;
    $action = $input['action'] ?? ''; 
    $note = $input['note'] ?? ''; // 發貨時必填：序號或單號

    checkAdmin($pdo, $admin_id);

    try {
        $pdo->beginTransaction();

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

        if (!$order) throw new Exception("訂單不存在");

        if ($action === 'approve') {
            // 發貨：更新狀態，寫入序號
            if (empty($note)) throw new Exception("發貨必須填寫序號或物流單號！");
            
            $stmt = $pdo->prepare("UPDATE exchange_requests SET status = 'approved', admin_note = ? WHERE id = ?");
            $stmt->execute([$note, $order_id]);
            $msg = "✅ 訂單 #{$order_id} 發貨成功！";

        } else if ($action === 'reject') {
            // 退單：更新狀態，退錢給使用者
            $stmt = $pdo->prepare("UPDATE exchange_requests SET status = 'rejected' WHERE id = ?");
            $stmt->execute([$order_id]);

            // 退款
            $stmt = $pdo->prepare("UPDATE users SET coins = coins + ? WHERE id = ?");
            $stmt->execute([$order['cost'], $order['user_id']]);

            // 寫入退款帳本
            $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'REFUND', ?, ?)");
            $stmt->execute([$order['user_id'], $order['cost'], "禮品退單退款: " . $order['item_name']]);

            $msg = "🛑 訂單 #{$order_id} 已退回並退款。";
        }

        $pdo->commit();
        echo json_encode(["status" => "success", "message" => $msg]);

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