@extends('layouts.store', ['title' => $order->order_number.' | RaseedNow'])

@php
    $manualGatewayPayload = ($manualPaymentGateways ?? collect())->map(fn ($gateway) => [
        'id' => $gateway->id,
        'name' => $gateway->name_ar,
        'description' => $gateway->description_ar,
        'account_number' => $gateway->account_number,
        'instructions' => $gateway->instructions_ar,
        'proof_instructions' => $gateway->proof_instructions_ar,
        'receiver_data' => $gateway->receiver_data ?: [[
            'label' => $gateway->account_label_ar ?: 'بيانات التحويل',
            'value' => $gateway->account_number,
            'type' => 'text',
            'copyable' => true,
        ]],
        'required_fields' => $gateway->required_fields ?: [],
        'requires_proof' => $gateway->requires_proof,
        'proof_is_required' => $gateway->proof_is_required,
        'proof_max_mb' => $gateway->proof_max_mb ?: 6,
    ])->values();
    $pendingManualSubmission = $order->manualPaymentSubmissions->first(fn ($submission) => in_array($submission->status, ['pending', 'info_requested', 'approved'], true));
@endphp

@section('content')
    <section class="lc-page-shell">
        <div class="surface p-6">
            @if(session('status'))
                <div class="mb-4 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">{{ session('status') }}</div>
            @endif
            @if($errors->any())
                <div class="mb-4 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">{{ $errors->first() }}</div>
            @endif
            <div class="section-heading">
                <div>
                    <span>تفاصيل الطلب</span>
                    <h1>{{ $order->order_number }}</h1>
                </div>
                <a class="secondary-button" href="{{ route('home') }}">العودة للمتجر</a>
            </div>
            @if($order->payment_method === 'mock_gateway' && $order->payment_status !== 'paid')
                <div class="mt-5 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
                    الدفع التجريبي لم يكتمل بعد.
                    <a class="underline" href="{{ route('payments.mock.show', $order) }}">افتح بوابة الدفع</a>
                </div>
            @endif
            @if($order->payment_method === 'online_gateway' && $order->payment_status !== 'paid')
                <div class="mt-5 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800">
                    الدفع الإلكتروني لم يكتمل بعد.
                    <a class="underline" href="{{ route('payments.online.show', $order) }}">متابعة الدفع</a>
                </div>
            @endif
            @if($order->payment_method === 'manual' && $order->payment_status !== 'paid')
                <div class="kd-order-manual-pay">
                    <div class="kd-pay-head">
                        <span>دفع يدوي للطلب</span>
                        <h2>إرسال إثبات التحويل</h2>
                        <p>انسخ بيانات التحويل، حوّل إجمالي الطلب، ثم ارفع صورة التحويل هنا. الطلب لن يتم تنفيذه إلا بعد مراجعة الإدارة.</p>
                    </div>

                    @if($pendingManualSubmission)
                        <div class="kd-payment-status">
                            <strong>تم إرسال إثبات لهذا الطلب</strong>
                            <span>الحالة الحالية: {{ $pendingManualSubmission->status }} — رقم المرجع: {{ $pendingManualSubmission->reference_number ?: 'غير مسجل' }}</span>
                        </div>
                    @elseif(($manualPaymentGateways ?? collect())->isEmpty())
                        <div class="kd-payment-status warning">
                            <strong>لا توجد وسائل دفع يدوية مفعلة الآن</strong>
                            <span>تواصل مع الإدارة لتفعيل وسيلة تحويل.</span>
                        </div>
                    @else
                        <form method="POST" action="{{ route('account.wallet.manual-payments.store') }}" enctype="multipart/form-data" class="kd-form kd-order-pay-form">
                            @csrf
                            <input type="hidden" name="order_id" value="{{ $order->id }}">
                            <input type="hidden" name="amount" value="{{ number_format($order->total_minor / 100, 2, '.', '') }}">

                            <label>
                                <span>وسيلة الدفع</span>
                                <select name="manual_payment_gateway_id" data-kd-order-gateway-select required>
                                    @foreach($manualPaymentGateways as $gateway)
                                        <option value="{{ $gateway->id }}">{{ $gateway->name_ar }}</option>
                                    @endforeach
                                </select>
                            </label>

                            <div class="kd-pay-amount">
                                <span>المبلغ المطلوب تحويله</span>
                                <strong>{{ number_format($order->total_minor / 100, 2) }} {{ $order->currency_code }}</strong>
                            </div>

                            <p class="kd-help" data-kd-order-gateway-description>{{ $manualPaymentGateways->first()?->description_ar }}</p>
                            <div class="kd-receiver-list" data-kd-order-receiver-data></div>
                            <p class="kd-help" data-kd-order-gateway-instructions>{{ $manualPaymentGateways->first()?->instructions_ar }}</p>

                            <div class="grid gap-4 md:grid-cols-2">
                                <label><span>اسم المحوّل</span><input name="payer_name" value="{{ auth()->user()?->name ?: $order->customer_name }}" required></label>
                                <label><span>رقم الهاتف</span><input name="payer_phone" value="{{ auth()->user()?->phone }}" required></label>
                                <label>
                                    <span>نوع معرف المحوّل</span>
                                    <select name="payer_identifier_type">
                                        <option value="phone">رقم هاتف</option>
                                        <option value="username">يوزر</option>
                                        <option value="email">بريد إلكتروني</option>
                                        <option value="reference">رقم مرجعي</option>
                                        <option value="other">أخرى</option>
                                    </select>
                                </label>
                                <label><span>معرف المحوّل</span><input name="payer_identifier" placeholder="الرقم/اليوزر/البريد الذي حولت منه"></label>
                                <label class="md:col-span-2"><span>رقم العملية / المرجع</span><input name="reference_number" placeholder="Transaction ID"></label>
                            </div>
                            <div class="grid gap-3" data-kd-order-dynamic-fields></div>
                            <label class="kd-proof-drop" data-kd-order-proof-wrap>
                                <span>سكرين التحويل</span>
                                <input name="proof" type="file" accept="image/*" data-kd-order-proof-input>
                                <strong data-kd-order-proof-label>اضغط هنا وارفع صورة التحويل</strong>
                                <small>PNG / JPG / WEBP</small>
                            </label>
                            <p class="kd-help" data-kd-order-proof-instructions>{{ $manualPaymentGateways->first()?->proof_instructions_ar }}</p>
                            <label><span>ملاحظات</span><textarea name="notes" rows="3" placeholder="أي تفاصيل تساعدنا نطابق التحويل"></textarea></label>
                            <button class="primary-button" type="submit">إرسال إثبات الدفع</button>
                        </form>
                    @endif
                </div>
            @endif
            <div class="mt-6 grid gap-4 md:grid-cols-4">
                <div class="metric-card"><span>الدفع</span><strong>{{ $order->payment_status }}</strong></div>
                <div class="metric-card"><span>التنفيذ</span><strong>{{ $order->fulfillment_status }}</strong></div>
                <div class="metric-card"><span>الإجمالي</span><strong>{{ number_format($order->total_minor / 100, 2) }} {{ $order->currency_code }}</strong></div>
                <div class="metric-card"><span>طريقة الدفع</span><strong>{{ $order->payment_method }}</strong></div>
            </div>
            @if($order->discount_minor > 0 || $order->cashback_minor > 0 || $order->loyalty_points_earned > 0)
                <div class="mt-6 grid gap-4 md:grid-cols-3">
                    <div class="metric-card"><span>خصم</span><strong>{{ number_format($order->discount_minor / 100, 2) }}</strong></div>
                    <div class="metric-card"><span>Cashback</span><strong>{{ number_format($order->cashback_minor / 100, 2) }}</strong></div>
                    <div class="metric-card"><span>نقاط مكتسبة</span><strong>{{ $order->loyalty_points_earned }}</strong></div>
                </div>
            @endif
            @if($order->latestPaymentAttempt)
                <div class="mt-6 rounded-2xl border border-[#e0e8e3] bg-[#f7f8fb] p-4 text-sm text-[#596174]">
                    آخر محاولة دفع: <strong>{{ $order->latestPaymentAttempt->reference }}</strong> / {{ $order->latestPaymentAttempt->status }}
                </div>
            @endif
            <div class="mt-6 overflow-hidden rounded border border-[#e7e9ef]">
                @foreach($order->items as $item)
                    <div class="admin-row">
                        <span>
                            {{ $item->name_snapshot }}
                            @if($canRevealCodes && $item->stockCodes->isNotEmpty())
                                <small class="mt-2 block rounded-xl border border-green-200 bg-green-50 p-3 text-sm leading-7 text-green-800">
                                    @foreach($item->stockCodes as $code)
                                        <span class="block">
                                            كود التسليم:
                                            <code class="select-all break-all font-black">{{ $code->decryptedCode() }}</code>
                                        </span>
                                    @endforeach
                                </small>
                            @elseif($item->delivery_method_snapshot === 'stored_code')
                                <small class="block text-xs text-[#6e7488]">سيظهر الكود هنا بعد تأكيد الدفع وإكمال التنفيذ.</small>
                            @endif
                        </span>
                        <strong>{{ number_format($item->total_minor / 100, 2) }}</strong>
                        <em>{{ $item->fulfillment_status }}</em>
                    </div>
                @endforeach
            </div>
            @if($canRevealCodes)
                <div class="mt-5 rounded-2xl border border-[#e0e8e3] bg-[#f7f8fb] p-4 text-sm leading-7 text-[#596174]">
                    احتفظ بالأكواد في مكان آمن. هذه الأكواد تخص هذا الطلب فقط ولا تظهر إلا لصاحب الطلب أو الأدمن.
                </div>
            @endif
        </div>
    </section>
    @if($order->payment_method === 'manual' && $order->payment_status !== 'paid' && ! $pendingManualSubmission)
        <script>
            (() => {
                const gateways = @json($manualGatewayPayload);
                const select = document.querySelector('[data-kd-order-gateway-select]');
                const receiver = document.querySelector('[data-kd-order-receiver-data]');
                const instructions = document.querySelector('[data-kd-order-gateway-instructions]');
                const description = document.querySelector('[data-kd-order-gateway-description]');
                const proofWrap = document.querySelector('[data-kd-order-proof-wrap]');
                const proofInput = document.querySelector('[data-kd-order-proof-input]');
                const proofLabel = document.querySelector('[data-kd-order-proof-label]');
                const proofText = document.querySelector('[data-kd-order-proof-instructions]');
                const dynamicWrap = document.querySelector('[data-kd-order-dynamic-fields]');
                const escapeHtml = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ({
                    '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;'
                }[char]));
                const render = () => {
                    const gateway = gateways.find((item) => String(item.id) === String(select?.value)) || gateways[0];
                    if (!gateway) return;
                    description.textContent = gateway.description || '';
                    instructions.textContent = gateway.instructions || '';
                    proofText.textContent = gateway.proof_instructions || '';
                    receiver.innerHTML = (gateway.receiver_data || []).map((row) => `
                        <div class="kd-copy-box">
                            <span><b>${escapeHtml(row.label || 'بيانات التحويل')}</b><em>${escapeHtml(row.value || '')}</em></span>
                            ${row.copyable === false ? '' : `<button type="button" data-kd-copy-value="${escapeHtml(row.value || '')}">نسخ</button>`}
                        </div>
                    `).join('');
                    dynamicWrap.innerHTML = (gateway.required_fields || []).map((field) => `
                        <label>
                            <span>${escapeHtml(field.label || field.key)} ${field.required ? '*' : ''}</span>
                            <input name="dynamic_fields[${escapeHtml(field.key)}]" type="${field.type === 'email' ? 'email' : 'text'}" placeholder="${escapeHtml(field.placeholder || '')}" ${field.required ? 'required' : ''}>
                        </label>
                    `).join('');
                    if (proofWrap) proofWrap.hidden = !gateway.requires_proof;
                    if (proofInput) proofInput.required = Boolean(gateway.requires_proof && gateway.proof_is_required);
                };
                document.addEventListener('click', async (event) => {
                    const button = event.target.closest('[data-kd-copy-value]');
                    if (!button) return;
                    await navigator.clipboard?.writeText((button.dataset.kdCopyValue || '').trim());
                    const old = button.textContent;
                    button.textContent = 'تم النسخ';
                    button.classList.add('copied');
                    setTimeout(() => {
                        button.textContent = old;
                        button.classList.remove('copied');
                    }, 1200);
                });
                proofInput?.addEventListener('change', () => {
                    proofLabel.textContent = proofInput.files?.[0]?.name || 'اضغط هنا وارفع صورة التحويل';
                });
                select?.addEventListener('change', render);
                render();
            })();
        </script>
    @endif
@endsection
