@extends('layouts.account', ['title' => 'المحفظة | RaseedNow'])

@php
    $gatewayPayload = $gateways->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,
        'min_amount' => $gateway->min_amount_minor ? $gateway->min_amount_minor / 100 : null,
        'max_amount' => $gateway->max_amount_minor ? $gateway->max_amount_minor / 100 : null,
    ])->values();
@endphp

@section('account_content')
    <div class="kd-page-head has-action">
        <h1>المحفظة</h1>
        <button class="kd-primary" type="button" data-kd-modal-open="topup">+ إضافة رصيد</button>
    </div>

    <div class="kd-wallet-hero">
        <span>رصيدك الحالي</span>
        <strong>{{ number_format(($user->wallet?->balance_minor ?? 0) / 100, 2) }} {{ $user->wallet?->currency_code ?? 'EGP' }}</strong>
        <p>استخدم الرصيد للدفع مباشرة على الطلبات بدون انتظار بوابة دفع.</p>
    </div>

    <section class="kd-card">
        <div class="kd-card-head">
            <h2>آخر الحركات</h2>
            <a href="{{ route('account.wallet') }}">تحديث</a>
        </div>
        <div class="kd-list">
            @forelse($entries ?? collect() as $entry)
                <div class="kd-list-row">
                    <div>
                        <strong>{{ $entry->description ?: $entry->type }}</strong>
                        <span>{{ $entry->created_at->format('Y-m-d H:i') }}</span>
                    </div>
                    <strong @class(['pos' => $entry->amount_minor > 0, 'neg' => $entry->amount_minor < 0])>{{ $entry->amount_minor > 0 ? '+' : '' }}{{ number_format($entry->amount_minor / 100, 2) }}</strong>
                </div>
            @empty
                <div class="kd-empty"><h3>لا توجد حركات بعد</h3><p>طلبات الشحن والدفع ستظهر هنا.</p></div>
            @endforelse
        </div>
        @if($entries)
            {{ $entries->links() }}
        @endif
    </section>

    <section class="kd-card">
        <div class="kd-card-head"><h2>طلبات الشحن اليدوي</h2></div>
        <div class="kd-list">
            @forelse($submissions as $submission)
                <div class="kd-list-row">
                    <div>
                        <strong>{{ $submission->gateway->name_ar }}</strong>
                        <span>{{ $submission->created_at->format('Y-m-d H:i') }}</span>
                    </div>
                    <strong>{{ number_format($submission->amount_minor / 100, 2) }} {{ $submission->currency_code }}</strong>
                    <em>{{ $submission->status }}</em>
                </div>
            @empty
                <div class="kd-empty"><h3>لا توجد طلبات شحن</h3><p>اضغط إضافة رصيد وارسِل إثبات التحويل.</p></div>
            @endforelse
        </div>
    </section>

    <div class="kd-modal" data-kd-modal="topup" hidden>
        <div class="kd-modal-card">
            <button type="button" class="kd-modal-close" data-kd-modal-close>×</button>
            <div class="kd-pay-head">
                <span>شحن يدوي آمن</span>
                <h2>إضافة رصيد</h2>
                <p>اختار الوسيلة، انسخ بيانات التحويل، حوّل نفس المبلغ، ثم ارفع صورة التحويل.</p>
            </div>
            <form method="POST" action="{{ route('account.wallet.manual-payments.store') }}" enctype="multipart/form-data" class="kd-form">
                @csrf
                <label>
                    <span>وسيلة الدفع</span>
                    <select name="manual_payment_gateway_id" data-kd-gateway-select required>
                        @foreach($gateways as $gateway)
                            <option value="{{ $gateway->id }}">{{ $gateway->name_ar }}</option>
                        @endforeach
                    </select>
                </label>
                <p class="kd-help" data-kd-gateway-description>{{ $gateways->first()?->description_ar }}</p>
                <div class="kd-pay-steps">
                    <div><b>1</b><span>انسخ الرقم</span></div>
                    <div><b>2</b><span>حوّل المبلغ</span></div>
                    <div><b>3</b><span>ارفع الصورة</span></div>
                </div>
                <div class="kd-receiver-list" data-kd-receiver-data>
                    <div class="kd-copy-box">
                        <span><b>بيانات التحويل</b><em data-kd-gateway-number>{{ $gateways->first()?->account_number ?? 'لا توجد وسيلة مفعلة' }}</em></span>
                        <button type="button" data-kd-copy>نسخ الرقم</button>
                    </div>
                </div>
                <p class="kd-help" data-kd-gateway-instructions>{{ $gateways->first()?->instructions_ar }}</p>
                <label><span>المبلغ</span><input name="amount" type="number" step="0.01" min="1" required></label>
                <label><span>اسم المحوّل</span><input name="payer_name" value="{{ $user->name }}" required></label>
                <label><span>رقم الهاتف</span><input name="payer_phone" value="{{ $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><span>رقم العملية / المرجع</span><input name="reference_number" placeholder="Transaction ID"></label>
                <div class="grid gap-3" data-kd-dynamic-fields></div>
                <label class="kd-proof-drop" data-kd-proof-wrap>
                    <span>سكرين التحويل</span>
                    <input name="proof" type="file" accept="image/*" data-kd-proof-input>
                    <strong data-kd-proof-label>اضغط هنا وارفع صورة التحويل</strong>
                    <small>PNG / JPG / WEBP</small>
                </label>
                <p class="kd-help" data-kd-proof-instructions>{{ $gateways->first()?->proof_instructions_ar }}</p>
                <label><span>ملاحظات</span><textarea name="notes" rows="3"></textarea></label>
                <button class="kd-primary" type="submit">إرسال طلب الشحن</button>
            </form>
        </div>
    </div>

    <script>
        (() => {
            const gateways = @json($gatewayPayload);
            const select = document.querySelector('[data-kd-gateway-select]');
            const receiver = document.querySelector('[data-kd-receiver-data]');
            const instructions = document.querySelector('[data-kd-gateway-instructions]');
            const description = document.querySelector('[data-kd-gateway-description]');
            const proofWrap = document.querySelector('[data-kd-proof-wrap]');
            const proofInput = proofWrap?.querySelector('input');
            const proofLabel = document.querySelector('[data-kd-proof-label]');
            const proofText = document.querySelector('[data-kd-proof-instructions]');
            const dynamicWrap = document.querySelector('[data-kd-dynamic-fields]');
            const amount = document.querySelector('input[name="amount"]');

            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 || '';
                if (amount) {
                    amount.min = gateway.min_amount || 1;
                    amount.max = gateway.max_amount || '';
                }

                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], [data-kd-copy-value]');
                if (!button) return;
                const value = button.dataset.kdCopyValue || document.querySelector('[data-kd-gateway-number]')?.textContent || '';
                await navigator.clipboard?.writeText(value.trim());
                const old = button.textContent;
                button.textContent = 'تم النسخ';
                button.classList.add('copied');
                setTimeout(() => button.textContent = old, 1200);
                setTimeout(() => button.classList.remove('copied'), 1200);
            });

            proofInput?.addEventListener('change', () => {
                proofLabel.textContent = proofInput.files?.[0]?.name || 'اضغط هنا وارفع صورة التحويل';
            });

            select?.addEventListener('change', render);
            render();
        })();
    </script>
@endsection
