@extends('admin.layouts.app')

@section('title', '新建平台订单')
@section('page_title', '新建平台订单')

@section('content')
<div class="page-header mb-20" data-page="admin.platform_orders.create">
    <div class="page-header-main">
        <div>
            <div class="page-header-title">新建平台订单</div>
            <div class="page-header-subtitle">用于总台运营手工创建一笔平台订单（演示/补单/线下收款录入）。创建后可在「平台订单」列表中继续推进：标记支付并生效 → 同步订阅（形成最小收费闭环）。</div>
        </div>

        <div class="page-header-actions">

    @php
        $leadId = (int) old('lead_id', $defaults['lead_id'] ?? 0);
        $incomingBackForLead = (string) ($defaults['back'] ?? '');
        $leadBack = \App\Support\BackUrl::sanitizeForLinks($incomingBackForLead);

        $viewLeadOrdersQuery = [
            'lead_id' => $leadId,
        ];
        if ($leadBack !== '') {
            $viewLeadOrdersQuery['back'] = $leadBack;
        }

        $viewLeadOrdersUrl = '/admin/platform-orders';
        if ($leadId > 0) {
            $viewLeadOrdersUrl .= '?' . \Illuminate\Support\Arr::query($viewLeadOrdersQuery);
        }
    @endphp

    @if($leadId > 0)
        <span class="badge">来源线索：#{{ $leadId }}</span>
        <a class="btn btn-secondary btn-sm" href="{!! $viewLeadOrdersUrl !!}">查看该线索关联订单</a>
    @endif
        </div>
    </div>
</div>

    @if(($siteSubscription ?? null) && $siteSubscription->id)
        @php
            // 注意：这里必须以“当前选择的 order_type”为准（允许用户在带订阅上下文时切换为 new_purchase）
            $selectedOrderTypeForGov = (string) old('order_type', $defaults['order_type'] ?? 'new_purchase');
            $canRenewForGov = ((int) ($defaults['site_subscription_id'] ?? 0) > 0) && (($siteSubscription ?? null) && ($siteSubscription->id ?? 0));
        @endphp

        <div class="mt-10">
            <div class="muted">本订单将关联订阅：</div>
            <div>
                <a class="link" href="/admin/site-subscriptions/{{ $siteSubscription->id }}">{{ $siteSubscription->subscription_no }}</a>
                <span class="muted">（订阅ID：{{ $siteSubscription->id }}）</span>
            </div>

            @if($canRenewForGov && $selectedOrderTypeForGov === 'renewal')
                <div class="muted muted-xs mt-6">
                    提示：该订单类型为「续费」。在订单完成「标记支付并生效 → 同步订阅」后，将会对该订阅执行续期/延长到期时间（以系统同步结果为准）。
                </div>

                <div class="governance-block mt-10">
                    <h4 class="governance-block-title">续费对象确认</h4>
                    <div class="governance-block-body">
                        <div>订阅号：<strong>{{ $siteSubscription->subscription_no }}</strong>（订阅ID：{{ $siteSubscription->id }}）</div>
                        <div>站点：{{ optional($siteSubscription->merchant)->name ?: ('#' . (int) $siteSubscription->merchant_id) }}</div>
                        <div>套餐：{{ $siteSubscription->plan_name ?: optional($siteSubscription->plan)->name ?: ('#' . (int) $siteSubscription->plan_id) }}</div>
                        <div>到期时间：{{ optional($siteSubscription->ends_at)->format('Y-m-d H:i:s') ?: '-' }}</div>
                    </div>
                    <div class="governance-block-footnote muted muted-xs">
                        建议流程：创建订单 → 在订单详情执行「标记支付并生效」→ 再执行「同步订阅」。请在提交前确认续费对象无误，避免误给其它订阅续期。
                    </div>
                </div>
            @endif
        </div>
    @endif

<form method="post" action="/admin/platform-orders" class="card form-grid">
    @csrf

    <input type="hidden" name="site_subscription_id" value="{{ old('site_subscription_id', $defaults['site_subscription_id'] ?? '') }}">

    @if(($requireSubscription ?? false) || ((string) old('require_subscription', '') === '1'))
        <input type="hidden" name="require_subscription" value="1">
    @endif

    <input type="hidden" name="lead_id" value="{{ old('lead_id', $defaults['lead_id'] ?? '') }}">

    @php
        $backVal = (string) old('back', $defaults['back'] ?? '');
        // back 作为隐藏字段用于 store 后跳转回来源页：同样需要安全护栏（统一口径）
        $backValSafe = \App\Support\BackUrl::sanitizeForLinks($backVal);
    @endphp
    @if($backValSafe !== '')
        <input type="hidden" name="back" value="{{ $backValSafe }}">
    @endif

    @php
        $hasLockedSubscription = (bool) (($siteSubscription ?? null) && ($siteSubscription->id ?? 0));
        $merchantIdVal = (string) old('merchant_id', $defaults['merchant_id'] ?? '');
        $planIdVal = (string) old('plan_id', $defaults['plan_id'] ?? '');
    @endphp

    <label>
        <span>站点</span>
        @if($hasLockedSubscription)
            <input type="hidden" name="merchant_id" value="{{ $merchantIdVal }}">
        @endif
        <select name="merchant_id" required @disabled($hasLockedSubscription)>
            <option value="">请选择站点</option>
            @foreach(($merchants ?? []) as $m)
                <option value="{{ $m->id }}" @selected($merchantIdVal === (string)$m->id)>{{ $m->name }}</option>
            @endforeach
        </select>
        @if($hasLockedSubscription)
            <small class="muted">已从订阅上下文锁定站点（避免误选导致续费串单）。</small>
        @endif
    </label>

    <label>
        <span>套餐</span>
        @if($hasLockedSubscription)
            <input type="hidden" name="plan_id" value="{{ $planIdVal }}">
        @endif
        <select name="plan_id" required @disabled($hasLockedSubscription)>
            <option value="">请选择套餐</option>
            @foreach(($plans ?? []) as $p)
                <option value="{{ $p->id }}" @selected($planIdVal === (string)$p->id)>
                    {{ $p->name }}（{{ $billingCycleLabels[$p->billing_cycle] ?? $p->billing_cycle }} / ¥{{ number_format((float)$p->price, 2) }}）
                </option>
            @endforeach
        </select>
        <small class="muted">订单会写入套餐快照（plan_name / billing_cycle / plan_snapshot），便于后续套餐变更时追溯。</small>
        @if($hasLockedSubscription)
            <small class="muted">已从订阅上下文锁定套餐（当前阶段不支持跨套餐续费；升级/降级后续再建）。</small>
        @endif
    </label>

    <label>
        <span>订单类型</span>
        @php
            $canRenew = ((int) ($defaults['site_subscription_id'] ?? 0) > 0) && (($siteSubscription ?? null) && ($siteSubscription->id ?? 0));
            $selectedOrderType = (string) old('order_type', $defaults['order_type'] ?? 'new_purchase');

            // 治理口径：续费必须绑定订阅。若当前页面未绑定订阅，则不允许选中 renewal（避免提交后才报错）。
            if (! $canRenew && $selectedOrderType === 'renewal') {
                $selectedOrderType = 'new_purchase';
            }

            // 更强治理：
            // - 若存在订阅上下文（锁定订阅）=> 当前阶段仅允许“续费”类型，避免出现“带订阅ID但非续费”导致语义混乱/误同步。
            // - 若来源页声明 require_subscription=1 且未绑定订阅 => 仅允许新购（用于兜底展示/引导去选订阅）。
            $requireSub = (bool) ($requireSubscription ?? false);
            $allowedTypes = array_keys($orderTypeLabels ?? []);
            if ($hasLockedSubscription) {
                $allowedTypes = ['renewal'];
                $selectedOrderType = 'renewal';
            } elseif ($requireSub && ! $canRenew) {
                $allowedTypes = ['new_purchase'];
            }
        @endphp
        <select name="order_type" required>
            @foreach(($orderTypeLabels ?? []) as $value => $label)
                @if(!in_array($value, $allowedTypes, true))
                    @continue
                @endif

                @if($value === 'renewal' && ! $canRenew)
                    <option value="{{ $value }}" disabled>{{ $label }}（需从订阅进入）</option>
                @else
                    <option value="{{ $value }}" @selected($selectedOrderType === $value)>{{ $label }}</option>
                @endif
            @endforeach
        </select>
        @if(! $canRenew)
            <small class="muted">提示：续费单必须绑定订阅。请从「订阅管理」列表/详情进入“续费下单”，系统会自动带入订阅ID。</small>

            @php
                $jumpQuery = [];
                if ((int) ($defaults['merchant_id'] ?? 0) > 0) {
                    $jumpQuery['merchant_id'] = (int) ($defaults['merchant_id'] ?? 0);
                }
                if ((int) ($defaults['plan_id'] ?? 0) > 0) {
                    $jumpQuery['plan_id'] = (int) ($defaults['plan_id'] ?? 0);
                }

                $jumpBase = '/admin/site-subscriptions';
                if (count($jumpQuery) > 0) {
                    $jumpBase .= '?' . \Illuminate\Support\Arr::query($jumpQuery);
                }

                $createSelfForBack = \App\Support\BackUrl::selfWithoutBack();
                // 若 require_subscription 来自 old input（校验失败回填），当前 URL 可能不带 query，
                // 此时也需要把 require_subscription=1 写回到 back，避免“去订阅管理选择订阅”回来后治理口径丢失。
                if (($requireSubscription ?? false) || ((string) old('require_subscription', '') === '1')) {
                    $createSelfForBack = \App\Support\BackUrl::currentPathWithQuery([
                        'require_subscription' => 1,
                    ], '');
                }

                $jumpUrl = \App\Support\BackUrl::withBack($jumpBase, $createSelfForBack);
            @endphp

            @if(($requireSubscription ?? false) && $jumpUrl)
                <div class="mt-6 actions">
                    <a class="btn btn-secondary btn-sm" href="{!! $jumpUrl !!}">去订阅管理选择订阅</a>
                </div>
            @endif
        @endif
    </label>

    <label>
        <span>购买数量（周期数）</span>
        <input type="number" min="1" max="120" name="quantity" value="{{ old('quantity', $defaults['quantity'] ?? 1) }}" required>
        <small class="muted">例如：月付套餐 quantity=3 表示购买 3 个月；年付套餐 quantity=2 表示购买 2 年。</small>
    </label>

    <label>
        <span>优惠金额（可选）</span>
        <input type="number" step="0.01" min="0" name="discount_amount" value="{{ old('discount_amount', $defaults['discount_amount'] ?? 0) }}">
    </label>

    <label>
        <span>支付渠道（可选）</span>
        <input name="payment_channel" value="{{ old('payment_channel', $defaults['payment_channel'] ?? '') }}" placeholder="例如：offline / wechat / alipay">
        <small class="muted">当前阶段仅用于记录口径，支付回执/对账后续再补。</small>
    </label>

    <label class="full">
        <span>备注（可选）</span>
        <textarea name="remark" rows="3" placeholder="可记录线下收款说明、对账备注等">{{ old('remark', $defaults['remark'] ?? '') }}</textarea>
    </label>

    <div class="form-actions actions gap-10">
        @php
            $incomingBack = (string) ($defaults['back'] ?? '');
            // back 安全护栏：
            // - 仅允许站内相对路径（/ 开头）
            // - 拒绝引号/尖括号
            // - 拒绝 nested back=（避免 URL 膨胀/绕过）
            // 说明：此处 href 采用原样输出以避免 &amp; 影响回链/断言。
            $safeBackForLinks = \App\Support\BackUrl::sanitizeForLinks($incomingBack);
        @endphp

        @if($safeBackForLinks !== '')
            <a href="{!! $safeBackForLinks !!}" class="btn btn-secondary btn-sm">返回上一页（保留上下文）</a>
        @else
            <a href="/admin/platform-orders" class="btn btn-secondary btn-sm">返回</a>
        @endif

        <button type="submit" class="btn btn-sm">创建订单</button>
    </div>
</form>
@endsection
