@extends('admin.layouts.app')

@section('title', '平台订单详情')
@section('page_title', '平台订单详情')

@section('content')
@php
    // 用于构建“保留当前上下文”的平台订单列表跳转链接（从详情跳回列表后可一键返回本订单详情）
    $orderShowSelf = '/' . ltrim(request()->path(), '/');
    $orderShowQuery = request()->query();
    unset($orderShowQuery['back']);
    if (count($orderShowQuery) > 0) {
        $orderShowSelf .= '?' . \Illuminate\Support\Arr::query($orderShowQuery);
    }

    $makePlatformOrderIndexUrl = function (array $query) use ($orderShowSelf) {
        // 统一：用 BackUrl::withBack 追加 back，避免手写拼接导致口径漂移
        return \App\Support\BackUrl::withBack('/admin/platform-orders?' . \Illuminate\Support\Arr::query($query), $orderShowSelf);
    };

    // 常用治理列表链接：统一口径（携带 back 回到当前订单详情自身，且不嵌套 back）
    $reconcileMismatchListUrl = \App\Support\BackUrl::withBack('/admin/platform-orders?' . \Illuminate\Support\Arr::query([
        'reconcile_mismatch' => 1,
    ]), $orderShowSelf);

    $refundInconsistentListUrl = \App\Support\BackUrl::withBack('/admin/platform-orders?' . \Illuminate\Support\Arr::query([
        'refund_inconsistent' => 1,
    ]), $orderShowSelf);
@endphp
@php
    $incomingBack = (string) request()->query('back', '');
    // back 安全护栏：
    // - 仅允许站内相对路径（/ 开头）
    // - 拒绝引号/尖括号
    // - 拒绝 nested back=（避免 URL 膨胀/绕过）
    // 说明：下方 href 采用原样输出以避免 &amp; 影响断言。
    $safeBackForLinks = \App\Support\BackUrl::sanitizeForLinks($incomingBack);

    // 若 back 指向的平台订单列表带 lead_id，则在详情页也提示当前来源线索（更不迷路）。
    $leadIdFromBack = 0;
    if ($safeBackForLinks !== '') {
        $parts = parse_url($safeBackForLinks);
        parse_str((string) ($parts['query'] ?? ''), $q);
        $leadIdFromBack = (int) ($q['lead_id'] ?? 0);
    }
@endphp
<div class="page-header mb-20" data-page="admin.platform_orders.show">
    <div class="page-header-main">
        <div>
            <div class="page-header-title">平台订单详情</div>
            <div class="page-header-subtitle">这里用于运营排查：订单核心字段、关联订阅、以及订阅同步元数据（meta）。</div>
        </div>

        <div class="page-header-actions">
            @if($safeBackForLinks !== '')
                <a href="{!! $safeBackForLinks !!}" class="btn btn-secondary btn-sm">← 返回上一页（保留上下文）</a>
            @endif

            @php
                $platformLeadId = (int) (data_get($order->meta, 'platform_lead_id') ?? 0);
                $leadIndexUrl = '';
                if ($platformLeadId > 0) {
                    $leadIndexUrl = \App\Support\BackUrl::withBack('/admin/platform-leads?' . \Illuminate\Support\Arr::query([
                        'lead_id' => $platformLeadId,
                    ]), $orderShowSelf);
                }
            @endphp
            @if($platformLeadId > 0)
                <span class="badge">来源线索：#{{ $platformLeadId }}</span>
                <a class="btn btn-secondary btn-sm" href="{!! $leadIndexUrl !!}">查看线索</a>
            @elseif($leadIdFromBack > 0)
                <span class="badge">来源线索：#{{ $leadIdFromBack }}</span>
            @endif

            @if($safeBackForLinks === '')
                <a href="{!! $makePlatformOrderIndexUrl([]) !!}" class="btn btn-secondary btn-sm">返回平台订单列表（保留上下文）</a>
            @endif
        </div>
    </div>
</div>

<div class="card mb-20" data-role="platform-order-show-quick-nav">
    <div class="actions gap-10">
        <span class="muted muted-xs">快速定位：</span>
        <a class="btn btn-secondary btn-sm" href="#payment-receipts">支付回执</a>
        <a class="btn btn-secondary btn-sm" href="#refund-receipts">退款记录</a>
        <a class="btn btn-secondary btn-sm" href="#subscription-sync">订阅同步</a>
        <a class="btn btn-secondary btn-sm" href="#order-governance-actions">治理动作</a>
    </div>
</div>

<div class="card mb-20">
    <h3>订单信息</h3>
    <table>
        <tbody>
        <tr><th class="w-160">ID</th><td>{{ $order->id }}</td></tr>
        <tr><th>订单号</th><td>{{ $order->order_no }}</td></tr>
        @php
            $platformLeadId = (int) (data_get($order->meta, 'platform_lead_id') ?? 0);
            $platformLeadUrl = '';
            if ($platformLeadId > 0) {
                $platformLeadUrl = \App\Support\BackUrl::withBack('/admin/platform-leads?' . \Illuminate\Support\Arr::query([
                    'lead_id' => $platformLeadId,
                ]), $orderShowSelf);
            }
        @endphp
        @if($platformLeadId > 0)
            <tr>
                <th>来源线索</th>
                <td>
                    <a class="link" href="{!! $platformLeadUrl !!}">#{{ $platformLeadId }}</a>
                    <span class="muted">（从线索链路创建/关联的订单）</span>
                </td>
            </tr>
        @endif
        <tr>
            <th>站点</th>
            <td>
                @if($order->merchant)
                    <a class="link" href="{!! $makePlatformOrderIndexUrl(['merchant_id' => $order->merchant->id]) !!}">{{ $order->merchant->name }}</a>
                @else
                    未关联站点
                @endif
            </td>
        </tr>
        <tr>
            <th>套餐</th>
            <td>
                @php $planName = $order->plan_name ?: ($order->plan?->name ?? '-'); @endphp
                @if($order->plan)
                    <a class="link" href="{!! $makePlatformOrderIndexUrl(['plan_id' => $order->plan->id]) !!}">{{ $planName }}</a>
                @else
                    {{ $planName }}
                @endif
            </td>
        </tr>
        <tr>
            <th>订单类型</th>
            <td>{{ $order->orderTypeLabel() }} <span class="muted">({{ $order->order_type }})</span></td>
        </tr>
        <tr><th>订单状态</th><td>{{ $statusLabels[$order->status] ?? $order->status }} <span class="muted">({{ $order->status }})</span></td></tr>
        <tr><th>支付状态</th><td>{{ $paymentStatusLabels[$order->payment_status] ?? $order->payment_status }} <span class="muted">({{ $order->payment_status }})</span></td></tr>
        <tr><th>应付/已付</th><td>¥{{ number_format((float) $order->payable_amount, 2) }} / ¥{{ number_format((float) $order->paid_amount, 2) }}</td></tr>
        <tr><th>下单时间</th><td>{{ optional($order->placed_at)->format('Y-m-d H:i:s') ?: '-' }}</td></tr>
        <tr><th>支付时间</th><td>{{ optional($order->paid_at)->format('Y-m-d H:i:s') ?: '-' }}</td></tr>
        <tr><th>生效时间</th><td>{{ optional($order->activated_at)->format('Y-m-d H:i:s') ?: '-' }}</td></tr>
        <tr><th>退款时间</th><td>{{ optional($order->refunded_at)->format('Y-m-d H:i:s') ?: '-' }}</td></tr>
        @php
            // 统一口径：优先读扁平字段 payment_summary/refund_summary（与列表/导出口径一致）；缺省回退遍历 receipts
            $paymentReceiptsRaw = (array) (data_get($order->meta, 'payment_receipts', []) ?? []);
            $refundReceiptsRaw = (array) (data_get($order->meta, 'refund_receipts', []) ?? []);

            $receiptCount = (int) (data_get($order->meta, 'payment_summary.count') ?? 0);
            $receiptTotal = (float) $order->receiptTotal();
            if ($receiptCount <= 0) {
                $receiptCount = count($paymentReceiptsRaw);
            }

            $refundCount = (int) (data_get($order->meta, 'refund_summary.count') ?? 0);
            $refundTotal = (float) $order->refundTotal();
            if ($refundCount <= 0) {
                $refundCount = count($refundReceiptsRaw);
            }
        
            $amountTol = (float) config('saasshop.amounts.tolerance', 0.01);
        @endphp
        <tr><th>回执数 / 回执总额</th><td>{{ $receiptCount }} / ¥{{ number_format($receiptTotal, 2) }}</td></tr>
        <tr><th>退款笔数 / 退款总额</th><td>{{ $refundCount }} / ¥{{ number_format($refundTotal, 2) }}</td></tr>
        <tr><th>金额容差</th><td>¥{{ number_format($amountTol, 2) }}</td></tr>
        @php
            $basRunId = (string) (data_get($order->meta, 'batch_activation.run_id') ?? '');
            $bmpaRunId = (string) (data_get($order->meta, 'batch_mark_paid_and_activate.run_id') ?? '');

            $basBatchUrl = $basRunId !== ''
                ? \App\Support\BackUrl::withBack('/admin/platform-batches/show?' . \Illuminate\Support\Arr::query([
                    'type' => 'bas',
                    'run_id' => $basRunId,
                ]), $orderShowSelf)
                : '';

            $bmpaBatchUrl = $bmpaRunId !== ''
                ? \App\Support\BackUrl::withBack('/admin/platform-batches/show?' . \Illuminate\Support\Arr::query([
                    'type' => 'bmpa',
                    'run_id' => $bmpaRunId,
                ]), $orderShowSelf)
                : '';
        @endphp
        <tr>
            <th>BAS 批次 run_id</th>
            <td>
                @if($basBatchUrl !== '')
                    <a class="link" href="{!! $basBatchUrl !!}">{{ $basRunId }}</a>
                    <span class="muted">（批次复盘）</span>
                @else
                    -
                @endif
            </td>
        </tr>
        <tr>
            <th>BMPA 批次 run_id</th>
            <td>
                @if($bmpaBatchUrl !== '')
                    <a class="link" href="{!! $bmpaBatchUrl !!}">{{ $bmpaRunId }}</a>
                    <span class="muted">（批次复盘）</span>
                @else
                    -
                @endif
            </td>
        </tr>
        </tbody>
    </table>

    @php
        $paidAmountFloat = (float) ($order->paid_amount ?? 0);

        $tol = (float) config('saasshop.amounts.tolerance', 0.01);
        $tolCents = (int) round($tol * 100);
        $tolCents = max(1, $tolCents);

        // 若订单疑似退款不一致：
        // - 非 refunded 但退款总额已达/超已付 + 容差 => 给出“可一键标记为已退款”的治理动作（不自动写回执）
        $canMarkRefunded = $paidAmountFloat > 0
            && $order->payment_status !== 'refunded'
            && round($refundTotal * 100) >= (round($paidAmountFloat * 100) + $tolCents);

        // - refunded 但退款总额 + 容差 < 已付 => 提供降级动作：标记为部分退款/已支付（仍不自动写回执）
        $canFixRefundedButNotEnough = $paidAmountFloat > 0
            && $order->payment_status === 'refunded'
            && (round($refundTotal * 100) + $tolCents) < round($paidAmountFloat * 100);

        // 统一口径：与 refund_inconsistent 筛选一致（模型方法）
        $isRefundInconsistent = (bool) $order->isRefundInconsistent();
    @endphp
    @if($canMarkRefunded || $canFixRefundedButNotEnough)
        <div class="card refund-governance-block">
            <div class="muted refund-governance-title"><strong>退款状态治理</strong>（高风险：仅修正状态，不自动写回执/退款回执）</div>
            <div class="muted muted-xs refund-governance-meta">已付：¥{{ number_format($paidAmountFloat, 2) }}｜退款总额：¥{{ number_format($refundTotal, 2) }}</div>
            <div class="muted muted-xs refund-governance-meta">操作说明：该区块仅用于修正支付状态展示口径，不会改金额、不生成退款记录；请先核对退款轨迹。</div>
            <div class="muted muted-xs refund-governance-meta">
                <a class="link" href="{!! $refundInconsistentListUrl !!}">查看全部退款不一致订单</a>
            </div>

            @if($canMarkRefunded)
                <div class="muted">
                    当前支付状态不是「已退款」，但退款总额已达到/超过已付金额。
                    <form method="post" action="/admin/platform-orders/{{ $order->id }}/mark-refunded" class="inline-form" data-action="disable-on-submit" onsubmit="return confirm('确认将该订单支付状态标记为已退款？该操作不会自动写入退款回执，仅修正状态');">
                        @csrf
                        <button class="btn btn-danger btn-sm" type="submit">标记为已退款</button>
                    </form>
                </div>
            @else
                <div class="muted">
                    当前支付状态为「已退款」，但退款总额不足。
                    <form method="post" action="/admin/platform-orders/{{ $order->id }}/mark-partially-refunded" class="inline-form" data-action="disable-on-submit" onsubmit="return confirm('确认将该订单支付状态标记为部分退款？该操作不会自动写入退款回执，仅修正状态');">
                        @csrf
                        <button class="btn btn-danger btn-sm" type="submit">标记为部分退款</button>
                    </form>
                    <form method="post" action="/admin/platform-orders/{{ $order->id }}/mark-paid-status" class="inline-form" data-action="disable-on-submit" onsubmit="return confirm('确认将该订单支付状态标记为已支付？该操作不会自动写入回执/退款回执，仅修正状态');">
                        @csrf
                        <button class="btn btn-danger btn-sm" type="submit">标记为已支付</button>
                    </form>
                </div>
            @endif
        </div>
    @endif

    @if($isRefundInconsistent)
        @if($order->payment_status === 'refunded')
            <div class="muted text-danger mt-10">提示：当前订单状态为「已退款」，但退款总额小于已付金额，可能存在数据不一致，请核对退款轨迹与订单金额。</div>
        @else
            <div class="muted text-danger mt-10">提示：退款总额已达到/超过已付金额，建议核对是否应将支付状态调整为「已退款」。</div>
        @endif
    @endif

    @php
        $canActivate = ($order->payment_status === 'paid') && ($order->status === 'activated');
        $alreadySynced = (int) data_get($order->meta, 'subscription_activation.subscription_id', 0) > 0;
        $canMarkPaid = ($order->payment_status !== 'paid') || ($order->status !== 'activated');
        $syncError = data_get($order->meta, 'subscription_activation_error.message');
        $syncErrorAt = data_get($order->meta, 'subscription_activation_error.at');

        // 治理提示：标记支付并生效的安全阀（后端也会阻断）
        $refundTotal = (float) $order->refundTotal();
        $receiptTotal = (float) $order->receiptTotal();
        $expectedPaid = (float) (((float) ($order->paid_amount ?? 0)) > 0 ? (float) $order->paid_amount : (float) ($order->payable_amount ?? 0));
        $receiptCents = (int) round($receiptTotal * 100);
        $expectedCents = (int) round($expectedPaid * 100);
        $markPaidBlockedByRefund = $refundTotal > 0;

        // 安全阀：续费单必须绑定订阅（后端已阻断，这里做前端提示/禁用）
        $markPaidBlockedByMissingSubscriptionOnRenewal = ((string) ($order->order_type ?? '') === 'renewal')
            && ((int) ($order->site_subscription_id ?? 0) <= 0);

        // 治理引导：续费缺订阅时提供“去订阅管理查找订阅”入口（回到当前订单详情自身）
        $missingSubscriptionHelpUrl = '';
        if ($markPaidBlockedByMissingSubscriptionOnRenewal) {
            $missingSubscriptionHelpUrl = \App\Support\BackUrl::withBack('/admin/site-subscriptions?' . \Illuminate\Support\Arr::query([
                'merchant_id' => (int) ($order->merchant_id ?? 0) ?: null,
                'plan_id' => (int) ($order->plan_id ?? 0) ?: null,
                // 从订单详情跳过去挑订阅：在订阅列表行内提供“一键绑定到该订单”按钮
                'attach_order_id' => (int) ($order->id ?? 0) ?: null,
                'attach_back' => $orderShowSelf,
                'page' => null,
            ]), $orderShowSelf);
        }

        $tol = (float) config('saasshop.amounts.tolerance', 0.01);
        $tolCents = (int) round($tol * 100);
        $tolCents = max(1, $tolCents);

        $markPaidBlockedByReceiptMismatch = $receiptCents > 0 && abs($receiptCents - $expectedCents) >= $tolCents;
    @endphp

    <div class="actions mt-16 gap-12" id="order-governance-actions">
        <form method="post" action="/admin/platform-orders/{{ $order->id }}/mark-paid-and-activate" data-action="disable-on-submit" onsubmit="return confirm('确认将该订单标记为已支付并生效？此操作会推进状态并尝试同步订阅');">
            @csrf
            <button class="btn btn-sm" type="submit" @disabled(! $canMarkPaid || $markPaidBlockedByRefund || $markPaidBlockedByReceiptMismatch || $markPaidBlockedByMissingSubscriptionOnRenewal)>标记支付并生效</button>
        </form>

        @if($markPaidBlockedByRefund || $markPaidBlockedByReceiptMismatch || $markPaidBlockedByMissingSubscriptionOnRenewal)
            <div class="card governance-block">
                <div class="muted text-danger governance-block-title"><strong>BMPA 治理提示</strong>（当前不建议/不可直接标记支付并生效）</div>
                <div class="muted governance-block-body">
                    @if($markPaidBlockedByRefund)
                        <div>
                            原因：当前订单已存在退款记录/退款汇总。
                            <span class="muted">｜</span>
                            <a class="btn btn-secondary btn-sm" href="#add-refund-receipt">去核对退款</a>
                        </div>
                    @endif
                    @if($markPaidBlockedByMissingSubscriptionOnRenewal)
                        <div>
                            原因：当前订单类型为「续费」，但未绑定订阅（site_subscription_id 为空）。
                            <span class="muted">｜</span>
                            <span class="muted">请先补齐订阅关联后再处理。</span>
                            @if($missingSubscriptionHelpUrl !== '')
                                <span class="muted">｜</span>
                                <a class="btn btn-secondary btn-sm" href="{!! $missingSubscriptionHelpUrl !!}">去订阅管理查找订阅</a>
                            @endif
                        </div>
                    @endif
                    @if($markPaidBlockedByReceiptMismatch)
                        <div>
                            原因：当前订单已存在支付回执，但回执总额与订单金额不一致。
                            <span class="muted">｜</span>
                            <a class="btn btn-secondary btn-sm" href="#add-payment-receipt">去补回执</a>
                        </div>
                    @endif
                    <div class="mt-6">
                        建议：先补齐/修正回执与退款轨迹（使金额与状态口径一致），再执行 BMPA。
                    </div>
                </div>
            </div>
        @endif

        @php
            $syncBlockedByGovernance = $order->isReconcileMismatch() || $order->isRefundInconsistent();
            // 安全阀：续费单必须绑定订阅（后端 activateSubscription 也会阻断，这里做前端提示/禁用）
            $syncBlockedByMissingSubscriptionOnRenewal = ((string) ($order->order_type ?? '') === 'renewal')
                && ((int) ($order->site_subscription_id ?? 0) <= 0);

            $missingSubscriptionHelpUrl = '';
            if ($syncBlockedByMissingSubscriptionOnRenewal) {
                $missingSubscriptionHelpUrl = \App\Support\BackUrl::withBack('/admin/site-subscriptions?' . \Illuminate\Support\Arr::query([
                    'merchant_id' => (int) ($order->merchant_id ?? 0) ?: null,
                    'plan_id' => (int) ($order->plan_id ?? 0) ?: null,
                    // 从订单详情跳过去挑订阅：在订阅列表行内提供“一键绑定到该订单”按钮
                    'attach_order_id' => (int) ($order->id ?? 0) ?: null,
                    'attach_back' => $orderShowSelf,
                    'page' => null,
                ]), $orderShowSelf);
            }
        @endphp
        <form method="post" action="/admin/platform-orders/{{ $order->id }}/activate-subscription" data-action="disable-on-submit" onsubmit="return confirm('确认同步订阅？将根据该订单创建/续期订阅');">
            @csrf
            @php
                $hasSyncErrorMeta = (bool) ($syncError ?? false);
                $activateBtnLabel = $alreadySynced
                    ? '已同步'
                    : ($hasSyncErrorMeta ? '重试同步订阅' : '同步订阅');
            @endphp
            <button class="btn btn-secondary btn-sm" type="submit" @disabled(! $canActivate || $alreadySynced || $syncBlockedByGovernance || $syncBlockedByMissingSubscriptionOnRenewal)>{{ $activateBtnLabel }}</button>
        </form>

        @if($syncBlockedByGovernance || $syncBlockedByMissingSubscriptionOnRenewal)
            <div class="card governance-block">
                <div class="muted text-danger governance-block-title"><strong>同步订阅治理提示</strong>（当前不建议/不可直接同步）</div>
                <div class="muted governance-block-body">
                    <div>当前订单命中「对账不一致/退款不一致」。为避免把“带病订单”同步到订阅，请先完成金额/状态治理。</div>
                    @if($syncBlockedByMissingSubscriptionOnRenewal)
                        <div class="mt-6">
                            当前订单类型为「续费」，但未绑定订阅（site_subscription_id 为空）。
                            <span class="muted">｜</span>
                            <span class="muted">请先补齐订阅关联后再重试同步。</span>
                            @if($missingSubscriptionHelpUrl !== '')
                                <span class="muted">｜</span>
                                <a class="btn btn-secondary btn-sm" href="{!! $missingSubscriptionHelpUrl !!}">去订阅管理查找订阅</a>
                            @endif
                        </div>
                    @endif
                    <div class="mt-6">
                        @if($order->isReconcileMismatch())
                            @php
                                $fixReceiptUrl = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $orderShowSelf, 'add-payment-receipt');
                            @endphp
                            <a class="btn btn-secondary btn-sm" href="{!! $fixReceiptUrl !!}">去补回执</a>
                        @endif
                        @if($order->isReconcileMismatch() && $order->isRefundInconsistent())
                            <span class="muted">｜</span>
                        @endif
                        @if($order->isRefundInconsistent())
                            @php
                                $fixRefundUrl = \App\Support\BackUrl::withBackAndFragment('/admin/platform-orders/' . $order->id, $orderShowSelf, 'add-refund-receipt');
                            @endphp
                            <a class="btn btn-secondary btn-sm" href="{!! $fixRefundUrl !!}">去核对退款</a>
                        @endif
                    </div>
                </div>
            </div>
        @endif

        @if($order->siteSubscription)
            @php
                // 与“关联订阅”区块口径一致：back 回到当前订单详情自身（剔除 back query，避免嵌套）
                $subBack = $orderShowSelf;
                $openSubUrl2 = \App\Support\BackUrl::withBack('/admin/site-subscriptions/' . $order->siteSubscription->id, $subBack);
            @endphp
            <a class="btn btn-secondary btn-sm" href="{!! $openSubUrl2 !!}">查看已同步订阅</a>
        @endif

        @php
            $canMarkActivatedOnly = ($order->payment_status === 'paid') && ($order->status !== 'activated');
            // 安全阀：续费单未绑定订阅时，不允许“仅标记为已生效”（后端 markActivated 也会阻断）
            $markActivatedBlockedByMissingSubscriptionOnRenewal = ((string) ($order->order_type ?? '') === 'renewal')
                && ((int) ($order->site_subscription_id ?? 0) <= 0);
        @endphp
        <form method="post" action="/admin/platform-orders/{{ $order->id }}/mark-activated" data-action="disable-on-submit" onsubmit="return confirm('确认将该订单标记为已生效？（不修改支付状态，不自动同步订阅）');">
            @csrf
            <button class="btn btn-secondary btn-sm" type="submit" @disabled(! $canMarkActivatedOnly || $markActivatedBlockedByMissingSubscriptionOnRenewal)>仅标记为已生效</button>
        </form>

        @if($markActivatedBlockedByMissingSubscriptionOnRenewal)
            <div class="card governance-block">
                <div class="muted text-danger governance-block-title"><strong>生效治理提示</strong>（当前不可直接标记为已生效）</div>
                <div class="muted governance-block-body">
                    <div>
                        原因：当前订单类型为「续费」，但未绑定订阅（site_subscription_id 为空）。
                        <span class="muted">｜</span>
                        <span class="muted">请先补齐订阅关联后再处理。</span>
                        @if($missingSubscriptionHelpUrl !== '')
                            <span class="muted">｜</span>
                            <a class="btn btn-secondary btn-sm" href="{!! $missingSubscriptionHelpUrl !!}">去订阅管理查找订阅</a>
                        @endif
                    </div>
                </div>
            </div>
        @endif
    </div>

    @if(! $canActivate)
        <div class="muted mt-10">同步订阅需满足：已支付 + 订单状态已生效</div>
    @elseif($alreadySynced)
        <div class="muted mt-10">该订单已完成同步（幂等保护）</div>
    @endif

    @if($syncError)
        <div class="muted mt-10 text-danger">最近同步失败：{{ $syncError }}{{ $syncErrorAt ? '（' . $syncErrorAt . '）' : '' }}</div>
    @endif
</div>

<div class="card mb-20">
    <h3>关联订阅</h3>
    @if($order->siteSubscription)
        <table>
            <tbody>
            <tr><th class="w-160">订阅ID</th><td>{{ $order->siteSubscription->id }}</td></tr>
            <tr><th>订阅号</th><td>{{ $order->siteSubscription->subscription_no }}</td></tr>
            <tr>
                <th>订阅管理</th>
                <td>
                    @php
                        // 用 orderShowSelf 作为 back（已剔除 back query，避免嵌套膨胀）
                        $subBack = $orderShowSelf;
                        $openSubUrl = \App\Support\BackUrl::withBack('/admin/site-subscriptions/' . $order->siteSubscription->id, $subBack);
                    @endphp
                    <a class="link" href="{!! $openSubUrl !!}">打开订阅详情</a>
                    <span class="muted">｜</span>
                    @php
                        $openSubSyncableUrl = \App\Support\BackUrl::withBackFirstAndFragment(
                            '/admin/site-subscriptions/' . $order->siteSubscription->id . '?' . \Illuminate\Support\Arr::query([
                                'order_sync_status' => 'syncable',
                            ]),
                            $subBack,
                            'syncable-batch'
                        );
                    @endphp
                    <a class="muted" href="{!! $openSubSyncableUrl !!}">查看可同步订单</a>
                    <span class="muted">｜</span>
                    @php
                        $sameMerchantSubsUrl = \App\Support\BackUrl::withBack('/admin/site-subscriptions?' . \Illuminate\Support\Arr::query([
                            'merchant_id' => $order->siteSubscription->merchant_id,
                        ]), $orderShowSelf);
                    @endphp
                    <a class="muted" href="{!! $sameMerchantSubsUrl !!}">同站点订阅</a>
                    <span class="muted">｜</span>
                    @php
                        $samePlanSubsUrl = \App\Support\BackUrl::withBack('/admin/site-subscriptions?' . \Illuminate\Support\Arr::query([
                            'plan_id' => $order->siteSubscription->plan_id,
                        ]), $orderShowSelf);
                    @endphp
                    <a class="muted" href="{!! $samePlanSubsUrl !!}">同套餐订阅</a>
                </td>
            </tr>
            <tr><th>状态</th><td>{{ $order->siteSubscription->status }}</td></tr>
            <tr><th>开始/到期</th><td>{{ optional($order->siteSubscription->starts_at)->format('Y-m-d H:i:s') ?: '-' }} / {{ optional($order->siteSubscription->ends_at)->format('Y-m-d H:i:s') ?: '-' }}</td></tr>
            </tbody>
        </table>
    @else
        <p class="muted">该订单尚未关联订阅（site_subscription_id 为空）。</p>

        @php
            $isRenewalMissingSubscription = ((string) ($order->order_type ?? '') === 'renewal')
                && ((int) ($order->site_subscription_id ?? 0) <= 0);

            $missingSubHelpUrlForRelationBlock = '';
            if ($isRenewalMissingSubscription) {
                $missingSubHelpUrlForRelationBlock = \App\Support\BackUrl::withBack('/admin/site-subscriptions?' . \Illuminate\Support\Arr::query([
                    'merchant_id' => (int) ($order->merchant_id ?? 0) ?: null,
                    'plan_id' => (int) ($order->plan_id ?? 0) ?: null,
                    // 从订单详情跳过去挑订阅：在订阅列表行内提供“一键绑定到该订单”按钮
                    'attach_order_id' => (int) ($order->id ?? 0) ?: null,
                    'attach_back' => $orderShowSelf,
                    'page' => null,
                ]), $orderShowSelf);
            }
        @endphp

        @if($isRenewalMissingSubscription)
            <div class="card governance-block mt-10" id="relation-subscription">
                <div class="muted text-danger governance-block-title"><strong>订阅关联治理提示</strong></div>
                <div class="muted governance-block-body">
                    <div>
                        当前订单类型为「续费」，但未绑定订阅（site_subscription_id 为空）。
                        <span class="muted">｜</span>
                        <span class="muted">建议先找到正确订阅并补齐关联，再进行 BMPA/同步/标记生效等动作。</span>
                        @if($missingSubHelpUrlForRelationBlock !== '')
                            <span class="muted">｜</span>
                            <a class="btn btn-secondary btn-sm" href="{!! $missingSubHelpUrlForRelationBlock !!}">去订阅管理查找订阅</a>
                        @endif
                    </div>

                    <div class="mt-10">
                        <form method="post" action="/admin/platform-orders/{{ $order->id }}/attach-subscription" class="inline-form" data-action="disable-on-submit" onsubmit="return confirm('确认将该订单绑定到所选订阅？该操作会写入审计留痕（meta.audit）');">
                            @csrf
                            <label class="muted" for="attach_site_subscription_id">绑定订阅ID</label>
                            <input id="attach_site_subscription_id" name="site_subscription_id" type="number" min="1" class="input input-sm" placeholder="输入订阅ID" required>
                            <button class="btn btn-primary btn-sm" type="submit">绑定订阅</button>
                        </form>
                        <div class="muted muted-xs mt-6">口径：仅用于“续费缺订阅”治理；系统将校验订阅的站点/套餐必须与当前订单一致，避免串单。</div>
                    </div>
                </div>
            </div>
        @endif
    @endif
</div>

@php
    $activation = data_get($order->meta, 'subscription_activation');
    $activationError = data_get($order->meta, 'subscription_activation_error');
    $bmpaError = data_get($order->meta, 'batch_mark_paid_and_activate_error');
    $audit = (array) (data_get($order->meta, 'audit', []) ?? []);
    $paymentReceipts = (array) (data_get($order->meta, 'payment_receipts', []) ?? []);
    $refundReceipts = (array) (data_get($order->meta, 'refund_receipts', []) ?? []);
@endphp

@php
    $batchMarkActivated = (array) (data_get($order->meta, 'batch_mark_activated', []) ?? []);
@endphp

<div class="card mb-20">
    <h3>最近批量生效记录</h3>
    @if((string) data_get($batchMarkActivated, 'at') !== '')
        <table>
            <tbody>
            <tr><th class="w-160">生效时间</th><td>{{ data_get($batchMarkActivated, 'at') }}</td></tr>
            <tr><th>操作管理员</th><td>{{ data_get($batchMarkActivated, 'admin_id') ?: '-' }}</td></tr>
            <tr><th>范围</th><td>{{ data_get($batchMarkActivated, 'scope') ?: '-' }}</td></tr>
            </tbody>
        </table>
    @else
        <p class="muted">暂无批量生效记录。</p>
    @endif
</div>

<div class="card mb-20" id="payment-receipts">
    <div class="flex-between items-center">
        <h3 class="mb-0">支付回执（对账留痕）</h3>
        <div class="actions gap-10">
            <a class="btn btn-secondary btn-sm" href="{!! $order->exportLedgerUrl() !!}" target="_blank" rel="noopener">导出对账明细（CSV）</a>
            <a class="btn btn-secondary btn-sm" href="{!! $order->exportLedgerUrl(['include_order_snapshot' => 1]) !!}" target="_blank" rel="noopener">导出含订单摘要（CSV）</a>
        </div>
    </div>
    <p class="muted muted-tight">用于“线下收款/转账/人工核对”的留痕记录（当前阶段先落 meta，不引入独立表）。</p>

    @php
        $isReconcileMismatch = (bool) $order->isReconcileMismatch();
    @endphp

    @if($isReconcileMismatch)
        @php
            $receiptTotalAmount = (float) (data_get($order->meta, 'payment_summary.total_amount') ?? 0);
            $receiptCount = (int) (data_get($order->meta, 'payment_summary.count') ?? 0);
            $paidAmount = (float) ($order->paid_amount ?? 0);
            $receiptDiff = $receiptTotalAmount - $paidAmount;
        @endphp
        <div class="card governance-block mt-10 mb-10">
            <div class="muted text-danger governance-block-title"><strong>对账不一致治理提示</strong></div>
            <div class="muted governance-block-body">
                <div>
                    该订单「支付回执合计 vs 已付金额」存在差异，建议先补齐回执轨迹再继续进行 BMPA/同步等动作。
                </div>
                <div class="muted muted-xs mt-6">
                    回执：{{ $receiptCount }} 条，合计 ¥{{ number_format($receiptTotalAmount, 2) }}；已付：¥{{ number_format($paidAmount, 2) }}；差额：¥{{ number_format($receiptDiff, 2) }}
                </div>
                <div class="mt-10">
                    <a class="btn btn-secondary btn-sm" href="#add-payment-receipt">去补回执</a>
                    <a class="link ml-10" href="{!! $reconcileMismatchListUrl !!}">查看全部对账不一致订单</a>
                </div>
            </div>
        </div>
    @endif

    @if(count($paymentReceipts) > 0)
        @php $items = array_slice(array_reverse($paymentReceipts), 0, 20); @endphp
        <table>
            <thead>
            <tr>
                <th class="w-140">类型</th>
                <th class="w-120">渠道</th>
                <th class="w-120">金额</th>
                <th class="w-200">支付时间</th>
                <th class="w-160">记录时间</th>
                <th class="w-100">管理员</th>
                <th>备注</th>
            </tr>
            </thead>
            <tbody>
            @foreach($items as $r)
                <tr>
                    <td>{{ data_get($r, 'type') ?: '-' }}</td>
                    <td>{{ data_get($r, 'channel') ?: '-' }}</td>
                    <td>¥{{ number_format((float) (data_get($r, 'amount') ?? 0), 2) }}</td>
                    <td>{{ data_get($r, 'paid_at') ?: '-' }}</td>
                    <td>{{ data_get($r, 'created_at') ?: '-' }}</td>
                    <td>{{ data_get($r, 'admin_id') ?: '-' }}</td>
                    <td class="muted">{{ data_get($r, 'note') ?: '' }}</td>
                </tr>
            @endforeach
            </tbody>
        </table>
    @else
        <p class="muted">暂无支付回执记录。</p>
    @endif

    <details class="mt-12 collapsible" id="add-payment-receipt" data-storage-key="admin.platform_orders.add_payment_receipt">
        <summary class="collapsible-summary muted">追加一条支付回执（不自动改状态）</summary>
        <form method="post" action="/admin/platform-orders/{{ $order->id }}/add-payment-receipt" class="mt-10 collapsible-body" data-action="disable-on-submit">
            <input type="hidden" name="back" value="{{ $safeBackForLinks }}">
            @csrf
            <div class="grid-3">
                <input type="text" name="type" placeholder="类型：bank_transfer/现金/支付宝等" value="bank_transfer">
                <input type="text" name="channel" placeholder="渠道（可选）" value="{{ (string) ($order->payment_channel ?? '') }}">
                <input type="number" step="0.01" name="amount" placeholder="金额" value="{{ number_format((float) ($order->paid_amount > 0 ? $order->paid_amount : $order->payable_amount), 2, '.', '') }}">
            </div>
            <div class="mt-10">
                <input type="text" name="paid_at" placeholder="支付时间：YYYY-mm-dd HH:ii:ss（可选）" value="{{ optional($order->paid_at)->format('Y-m-d H:i:s') }}" class="w-full">
            </div>
            <div class="mt-10">
                <textarea name="note" placeholder="备注（可选，用于对账说明）" rows="3" class="w-full"></textarea>
            </div>
            <div class="mt-10">
                <button type="submit" class="btn btn-sm">追加回执记录</button>
            </div>
        </form>
    </details>
</div>

<div class="card mb-20" id="refund-receipts">
    <h3>退款记录（退款轨迹留痕）</h3>
    <p class="muted muted-tight">用于记录退款动作与对账轨迹（先落 meta，不引入独立表）。追加退款后，系统会自动把支付状态推进为“部分退款/已退款”（仅在订单当前为已支付时）。</p>

    @php
        // 退款不一致（统一口径：模型方法）
        $isRefundInconsistent3 = (bool) $order->isRefundInconsistent();
    @endphp

    @if($isRefundInconsistent3)
        <div class="card governance-block mt-10">
            <div class="muted text-danger governance-block-title"><strong>退款不一致治理提示</strong></div>
            <div class="muted governance-block-body">
                <div>
                    该订单疑似存在「退款状态 vs 退款总额」不一致（按容差口径），建议先补齐退款轨迹，再修正退款状态口径。
                </div>
                <div class="mt-10 actions gap-10">
                    <a class="btn btn-secondary btn-sm" href="#add-refund-receipt">去追加退款记录</a>
                    <a class="link" href="{!! $refundInconsistentListUrl !!}">查看全部退款不一致订单</a>
                </div>
            </div>
        </div>
    @endif

    @if(count($refundReceipts) > 0)
        @php $items = array_slice(array_reverse($refundReceipts), 0, 20); @endphp
        <table>
            <thead>
            <tr>
                <th class="w-140">类型</th>
                <th class="w-120">渠道</th>
                <th class="w-120">金额</th>
                <th class="w-200">退款时间</th>
                <th class="w-160">记录时间</th>
                <th class="w-100">管理员</th>
                <th>备注</th>
            </tr>
            </thead>
            <tbody>
            @foreach($items as $r)
                <tr>
                    <td>{{ data_get($r, 'type') ?: '-' }}</td>
                    <td>{{ data_get($r, 'channel') ?: '-' }}</td>
                    <td>¥{{ number_format((float) (data_get($r, 'amount') ?? 0), 2) }}</td>
                    <td>{{ data_get($r, 'refunded_at') ?: '-' }}</td>
                    <td>{{ data_get($r, 'created_at') ?: '-' }}</td>
                    <td>{{ data_get($r, 'admin_id') ?: '-' }}</td>
                    <td class="muted">{{ data_get($r, 'note') ?: '' }}</td>
                </tr>
            @endforeach
            </tbody>
        </table>
    @else
        <p class="muted">暂无退款记录。</p>
    @endif

    <details class="mt-12 collapsible" id="add-refund-receipt" data-storage-key="admin.platform_orders.add_refund_receipt">
        <summary class="collapsible-summary muted">追加一条退款记录（会自动推进支付状态）</summary>
        <form method="post" action="/admin/platform-orders/{{ $order->id }}/add-refund-receipt" class="mt-10 collapsible-body" data-action="disable-on-submit" onsubmit="return confirm('确认追加退款记录？该操作会写入退款轨迹，并可能推进支付状态为部分退款/已退款');">
            <input type="hidden" name="back" value="{{ $safeBackForLinks }}">
            @csrf
            <div class="grid-3">
                <input type="text" name="type" placeholder="类型：refund/chargeback/手工退款等" value="refund">
                <input type="text" name="channel" placeholder="渠道（可选）" value="{{ (string) ($order->payment_channel ?? '') }}">
                <input type="number" step="0.01" name="amount" placeholder="金额" value="0.00">
            </div>
            <div class="mt-10">
                <input type="text" name="refunded_at" placeholder="退款时间：YYYY-mm-dd HH:ii:ss（可选）" value="{{ optional($order->refunded_at)->format('Y-m-d H:i:s') }}" class="w-full">
            </div>
            <div class="mt-10">
                <textarea name="note" placeholder="备注（可选，用于退款说明/对账）" rows="3" class="w-full"></textarea>
            </div>
            <div class="mt-10">
                <button type="submit" class="btn btn-sm">追加退款记录</button>
            </div>
        </form>
    </details>
</div>

<div class="card mb-20" id="subscription-sync">
    <h3>订阅同步记录</h3>
    @if($activation)
        <table>
            <tbody>
            <tr><th class="w-160">订阅ID</th><td>{{ data_get($activation, 'subscription_id') }}</td></tr>
            <tr><th>同步时间</th><td>{{ data_get($activation, 'synced_at') ?: '-' }}</td></tr>
            <tr><th>操作管理员</th><td>{{ data_get($activation, 'admin_id') ?: '-' }}</td></tr>
            </tbody>
        </table>
    @else
        <p class="muted">暂无同步记录。</p>
    @endif
</div>

<div class="card mb-20" id="sync-failed">
    <div class="flex-between">
        <h3>最近一次同步失败</h3>
        @if($activationError)
            <form method="post" action="/admin/platform-orders/{{ $order->id }}/clear-sync-error" data-action="disable-on-submit" onsubmit="return confirm('确认清除该订单的同步失败标记？该操作仅清理 meta 标记，不会改变订阅/订单状态。');">
                @csrf
                <button class="btn btn-danger btn-sm" type="submit">清除失败标记</button>
            </form>
        @endif
    </div>
    @if($activationError)
        @php
            $syncMsg = (string) (data_get($activationError, 'message') ?? '');
            $syncFailedListUrl = $makePlatformOrderIndexUrl(['sync_status' => 'failed']);

            // 避免 URL 过长/特殊字符破坏 query：失败原因过长时不生成 keyword 链接
            // 与列表页/仪表盘保持一致：由 config 统一控制阈值。
            $SYNC_REASON_KEYWORD_MAX_LEN = (int) config('saasshop.platform_orders.sync_error_keyword_link_max_len', 100);
            $syncReasonUrl = '';
            if ($syncMsg !== '' && mb_strlen($syncMsg) <= $SYNC_REASON_KEYWORD_MAX_LEN) {
                $syncReasonUrl = $makePlatformOrderIndexUrl([
                    'sync_status' => 'failed',
                    'sync_error_keyword' => $syncMsg,
                ]);
            }
        @endphp

        <table>
            <tbody>
            <tr><th class="w-160">失败原因</th><td>{{ data_get($activationError, 'message') }}</td></tr>
            <tr><th>失败时间</th><td>{{ data_get($activationError, 'at') ?: '-' }}</td></tr>
            <tr><th>操作管理员</th><td>{{ data_get($activationError, 'admin_id') ?: '-' }}</td></tr>
            </tbody>
        </table>

        <div class="mt-10 actions gap-10">
            <a class="btn btn-secondary btn-sm" href="{!! $syncFailedListUrl !!}">查看同步失败订单</a>
            @if($syncReasonUrl)
                <a class="btn btn-secondary btn-sm" href="{!! $syncReasonUrl !!}">查看同原因失败订单</a>
            @else
                <span class="muted muted-xs">原因过长，请复制到列表页筛选框</span>
            @endif
        </div>

        <div class="muted muted-xs mt-6">提示：当你已确认问题已解决，但历史失败标记仍残留时，可先清理标记，再点击上方「重试同步订阅」。</div>
    @else
        <p class="muted">暂无失败记录。</p>
    @endif
</div>

<div class="card mb-20" id="bmpa-failed">
    <div class="flex-between">
        <h3>最近一次 BMPA 失败</h3>
        @if($bmpaError)
            <form method="post" action="/admin/platform-orders/{{ $order->id }}/clear-bmpa-error" data-action="disable-on-submit" onsubmit="return confirm('确认清除该订单的 BMPA 失败标记？该操作仅清理 meta 标记，不会改变订阅/订单状态。');">
                @csrf
                <button class="btn btn-danger btn-sm" type="submit">清除 BMPA 失败标记</button>
            </form>
        @endif
    </div>

    @if($bmpaError)
        @php
            $bmpaMsg = (string) (data_get($bmpaError, 'message') ?? '');
            $bmpaListUrl = $makePlatformOrderIndexUrl(['bmpa_failed_only' => '1']);

            // 避免 URL 过长/特殊字符破坏 query：失败原因过长时不生成 keyword 链接
            // 与列表页/仪表盘保持一致：由 config 统一控制阈值。
            $BMPA_REASON_KEYWORD_MAX_LEN = (int) config('saasshop.platform_orders.sync_error_keyword_link_max_len', 100);
            $bmpaReasonUrl = '';
            if ($bmpaMsg !== '' && mb_strlen($bmpaMsg) <= $BMPA_REASON_KEYWORD_MAX_LEN) {
                $bmpaReasonUrl = $makePlatformOrderIndexUrl([
                    'bmpa_failed_only' => '1',
                    'bmpa_error_keyword' => $bmpaMsg,
                ]);
            }
        @endphp

        <table>
            <tbody>
            <tr><th class="w-160">失败原因</th><td>{{ data_get($bmpaError, 'message') }}</td></tr>
            <tr><th>失败时间</th><td>{{ data_get($bmpaError, 'at') ?: '-' }}</td></tr>
            <tr><th>操作管理员</th><td>{{ data_get($bmpaError, 'admin_id') ?: '-' }}</td></tr>
            </tbody>
        </table>

        <div class="mt-10 actions gap-10">
            <a class="btn btn-secondary btn-sm" href="{!! $bmpaListUrl !!}">查看 BMPA 失败订单</a>
            @if($bmpaReasonUrl)
                <a class="btn btn-secondary btn-sm" href="{!! $bmpaReasonUrl !!}">查看同原因失败订单</a>
            @else
                <span class="muted muted-xs">原因过长，请复制到列表页筛选框</span>
            @endif
        </div>

        <div class="muted muted-xs mt-6">提示：当你已修复导致 BMPA 失败的原因（回执/退款/权限/幂等等），但历史失败标记仍残留时，可先清理标记，再重新执行 BMPA。</div>
    @else
        <p class="muted">暂无失败记录。</p>
    @endif
</div>

<div class="card mb-20">
    <h3>审计记录（最近 20 条）</h3>
    @if(count($audit) > 0)
        @php
            $auditItems = array_slice(array_reverse($audit), 0, 20);
            $auditActionLabels = [
                'clear_sync_error' => '清除同步失败标记',
                'clear_bmpa_error' => '清除 BMPA 失败标记',
                'batch_activate_subscription' => '批量同步订阅',
                'mark_activated' => '仅标记为已生效',
                'batch_mark_activated' => '批量仅标记为已生效',
                'batch_mark_paid_and_activate' => '批量标记支付并生效（BMPA）',
                'activate_subscription' => '同步订阅',
                'attach_subscription' => '绑定订阅（续费缺订阅治理）',
                'mark_refunded' => '手动标记为已退款',
                'mark_partially_refunded' => '手动标记为部分退款',
                'mark_paid_status' => '手动标记为已支付',
                'mark_paid_and_activate' => '标记支付并生效（BMPA）',
                'add_payment_receipt' => '追加支付回执',
                'add_refund_receipt' => '追加退款回执',
            ];
        @endphp
        <table>
            <thead>
            <tr>
                <th class="w-200">动作</th>
                <th class="w-120">范围</th>
                <th class="w-200">时间</th>
                <th class="w-120">管理员</th>
                <th class="w-200">快照</th>
                <th>备注</th>
            </tr>
            </thead>
            <tbody>
            @foreach($auditItems as $item)
                @php
                    $snap = (array) (data_get($item, 'snapshot', []) ?? []);

                    // 统一快照展示：
                    // 1) 若存在 paid/refund 快照字段：优先格式化成 money（保持历史口径与测试稳定）
                    // 2) 否则若 snapshot 非空：展示 key=value（用于回执审计等）
                    // 3) 否则降级展示 subscription_id/filters。
                    $pairs = [];

                    $snapPaid = data_get($snap, 'paid_amount');
                    $snapRefund = data_get($snap, 'refund_total');
                    if ($snapPaid !== null || $snapRefund !== null) {
                        if ($snapPaid !== null) {
                            $pairs[] = 'paid=¥' . number_format((float) $snapPaid, 2);
                        }
                        if ($snapRefund !== null) {
                            $pairs[] = 'refund=¥' . number_format((float) $snapRefund, 2);
                        }

                        // 剩余字段：key=value
                        foreach ($snap as $k => $v) {
                            if (in_array((string) $k, ['paid_amount', 'refund_total'], true)) {
                                continue;
                            }

                            if (is_array($v)) {
                                $v = json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                            } elseif (is_bool($v)) {
                                $v = $v ? 'true' : 'false';
                            }

                            $v = (string) $v;
                            $v = mb_substr($v, 0, 80);
                            $pairs[] = (string) $k . '=' . $v;
                        }
                    } elseif (count($snap) > 0) {
                        foreach ($snap as $k => $v) {
                            if (is_array($v)) {
                                $v = json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
                            } elseif (is_bool($v)) {
                                $v = $v ? 'true' : 'false';
                            }

                            $v = (string) $v;
                            $v = mb_substr($v, 0, 80);
                            $pairs[] = (string) $k . '=' . $v;
                        }
                    } else {
                        $subId = data_get($item, 'subscription_id');
                        $filtersText = (string) (data_get($item, 'filters') ?? '');
                        $filtersText = $filtersText !== '' ? mb_substr($filtersText, 0, 80) : '';

                        if ($subId) {
                            $pairs[] = 'subscription_id=' . (string) $subId;
                        }
                        if ($filtersText !== '') {
                            $pairs[] = 'filters=' . $filtersText;
                        }
                    }

                    $snapshotText = count($pairs) > 0 ? implode('；', $pairs) : '-';
                @endphp
                <tr>
                    <td>{{ $auditActionLabels[data_get($item, 'action')] ?? (data_get($item, 'action') ?: '-') }}</td>
                    <td>{{ data_get($item, 'scope') ?: '-' }}</td>
                    <td>{{ data_get($item, 'at') ?: '-' }}</td>
                    <td>{{ data_get($item, 'admin_id') ?: '-' }}</td>
                    <td class="muted">{{ $snapshotText }}</td>
                    <td class="muted">{{ data_get($item, 'note') ?: '' }}</td>
                </tr>
            @endforeach
            </tbody>
        </table>
    @else
        <p class="muted">暂无审计记录。</p>
    @endif
</div>

<div class="card">
    <h3>原始 meta（JSON）</h3>
    <pre class="pre-wrap">{{ json_encode($order->meta, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) }}</pre>
</div>

{{-- 返回入口已收敛到 PageHeader actions（避免页面底部重复出现“返回上一页/返回列表”链接） --}}
@endsection
