@extends('layout')

@section('title', __('store.payment_title'))

@section('content')
<div class="container my-5">
    <div class="row">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <h4>{{ __('store.payment_invoice_payment') }}</h4>
                    <small class="text-muted">{{ __('store.payment_invoice_number') }}: {{ $invoice->invoice_number }}</small>
                </div>
                <div class="card-body">
                    
                    @if(($availableCredit ?? 0) > 0)
                        <div class="alert alert-info d-flex flex-column gap-2 mb-4">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-wallet me-2"></i>
                                <span>{{ __('store.credit_available', ['amount' => $invoice->currency->format($availableCredit)]) }}</span>
                            </div>
                            @if($creditCoversFull ?? false)
                                <div class="small">{{ __('store.credit_covers_full') }}</div>
                                <form action="{{ route('store.payment.credit', $invoice->id) }}" method="POST" class="mt-1">
                                    @csrf
                                    <button type="submit" class="btn btn-success btn-sm">
                                        <i class="fas fa-wallet me-2"></i>{{ __('store.pay_with_credit') }}
                                    </button>
                                </form>
                            @else
                                <div class="small text-muted">{{ __('store.credit_remaining_to_pay', ['amount' => $invoice->currency->format($invoice->total_amount - $availableCredit)]) }}</div>
                                <form action="{{ route('store.payment.credit.partial', $invoice->id) }}" method="POST" class="mt-1">
                                    @csrf
                                    <button type="submit" class="btn btn-outline-success btn-sm">
                                        <i class="fas fa-wallet me-2"></i>{{ __('store.use_credit_balance') }}
                                    </button>
                                </form>
                            @endif
                        </div>
                    @endif

                    <!-- Payment Method Selection Based on Gateway Type -->
                    @php $gatewayName = $order?->payment_gateway_name ?? $paymentGateway['name']; @endphp
                    @if($gatewayName === 'banktransfer' || $gatewayName === 'bank_transfer')
                        <!-- Bank Transfer - This should redirect to bank-transfer view instead -->
                        <div class="alert alert-warning">
                            <h5><i class="fas fa-info-circle me-2"></i>{{ __('store.payment_bank_transfer_title') }}</h5>
                            <p>{{ __('store.payment_bank_transfer_info') }}</p>
                            <p class="mb-0">{{ __('store.payment_payment_instructions') }}</p>
                        </div>




                        <!-- Payment Gateway Bank Transfer Details -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="card ">
                                    <div class="card-header">
                                        <h6 class="mb-0">{{ __('store.payment_bank_details') }}</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="bank-info">
                                            <div class="mb-3">
                                                <strong>{{ __('store.payment_bank_name') }}:</strong><br>
                                                <span id="bank-name">{{ $gatewaySettings['bank_name'] ?? 'Bank Name Not Set' }}</span>
                                                <button class="btn btn-sm btn-outline-secondary ms-2" onclick="copyToClipboard('bank-name')">
                                                    <i class="fas fa-copy"></i>
                                                </button>
                                            </div>

                                            <div class="mb-3">
                                                <strong>{{ __('store.payment_account_holder') }}:</strong><br>
                                                <span id="account-holder">{{ $gatewaySettings['account_holder'] ?? 'Account Holder Not Set' }}</span>
                                                <button class="btn btn-sm btn-outline-secondary ms-2" onclick="copyToClipboard('account-holder')">
                                                    <i class="fas fa-copy"></i>
                                                </button>
                                            </div>

                                            @if(!empty($gatewaySettings['account_number']))
                                            <div class="mb-3">
                                                <strong>{{ __('store.payment_account_number') }}:</strong><br>
                                                <span id="account-number">{{ $gatewaySettings['account_number'] }}</span>
                                                <button class="btn btn-sm btn-outline-secondary ms-2" onclick="copyToClipboard('account-number')">
                                                    <i class="fas fa-copy"></i>
                                                </button>
                                            </div>
                                            @endif

                                            <div class="mb-3">
                                                <strong>{{ __('store.payment_iban') }}:</strong><br>
                                                <span id="iban">{{ $gatewaySettings['iban'] ?? 'IBAN Not Set' }}</span>
                                                <button class="btn btn-sm btn-outline-secondary ms-2" onclick="copyToClipboard('iban')">
                                                    <i class="fas fa-copy"></i>
                                                </button>
                                            </div>

                                            @if(!empty($gatewaySettings['swift_code']))
                                            <div class="mb-0">
                                                <strong>{{ __('store.payment_swift_code') }}:</strong><br>
                                                <span id="swift">{{ $gatewaySettings['swift_code'] }}</span>
                                                <button class="btn btn-sm btn-outline-secondary ms-2" onclick="copyToClipboard('swift')">
                                                    <i class="fas fa-copy"></i>
                                                </button>
                                            </div>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <!-- Payment instructions -->
                                <div class="card bg-warning bg-opacity-10">
                                    <div class="card-header">
                                        <h6 class="mb-0">{{ __('store.payment_important_notes') }}</h6>
                                    </div>
                                    <div class="card-body">
                                        @if(!empty($gatewaySettings['payment_instructions']))
                                            <div class="mb-3">
                                                {!! nl2br(e($gatewaySettings['payment_instructions'])) !!}
                                            </div>
                                        @endif

                                        <ul class="list-unstyled mb-0">
                                            <li class="mb-2">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                {{ __('store.payment_transfer_exact_amount') }}
                                            </li>
                                            <li class="mb-2">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                {{ __('store.payment_include_invoice_number') }}
                                            </li>
                                            <li class="mb-0">
                                                <i class="fas fa-check-circle text-success me-2"></i>
                                                {{ __('store.payment_processing_time') }}
                                            </li>
                                        </ul>
                                    </div>
                                </div>

                                <!-- Payment reference -->
                                <div class="card mt-3">
                                    <div class="card-header">
                                        <h6 class="mb-0">{{ __('store.payment_payment_reference') }}</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-0">
                                            <strong>{{ __('store.payment_reference_description') }}:</strong><br>
                                            <span id="reference-text">{{ $invoice->invoice_number }} - {{ $order?->client->first_name ?? $invoice->client->first_name }} {{ $order?->client->last_name ?? $invoice->client->last_name }}</span>
                                            <button class="btn btn-sm btn-outline-secondary ms-2" onclick="copyToClipboard('reference-text')">
                                                <i class="fas fa-copy"></i> {{ __('store.payment_copy') }}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    @elseif(($features['3d_secure'] ?? false) && ($settings['security_type'] ?? '3d') !== '2d')
                        <!-- 3D Secure Credit Card Form -->
                        @include('payment.partials.credit-card-3d', ['invoice' => $invoice, 'features' => $features, 'settings' => $settings, 'savedMethods' => $savedMethods ?? collect()])

                    @elseif($features['3d_secure'] ?? false)
                        <!-- 2D Credit Card Form -->
                        @include('payment.partials.credit-card-2d', ['invoice' => $invoice, 'features' => $features, 'settings' => $settings, 'savedMethods' => $savedMethods ?? collect()])

                    @elseif(in_array($gatewayName, ['paypal', 'payu', 'paytr']))
                        <!-- External Payment -->
                        @if(($settings['integration_type'] ?? 'redirect') === 'iframe')
                            @include('payment.partials.external-iframe', ['invoice' => $invoice])
                        @else
                            @include('payment.partials.redirect-payment', ['invoice' => $invoice])
                        @endif

                    @else
                        <!-- Default External Payment -->
                        @include('payment.partials.redirect-payment', ['invoice' => $invoice])
                    @endif
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- Payment Gateway Selection -->
            @if($canChooseGateway && count($availableGateways) > 1)
                <div class="card mb-3">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="fas fa-exchange-alt me-2"></i>{{ __('store.payment_change_gateway') }}</h6>
                    </div>
                    <div class="card-body">
                        <form action="{{ route('store.payment.change-gateway', $invoice->id) }}" method="POST" id="gateway-change-form">
                            @csrf
                            <div class="mb-3">
                                <label for="gateway_name" class="form-label small">{{ __('store.payment_select_gateway') }}</label>
                                <select name="gateway_name" id="gateway_name" class="form-select form-select-sm" required>
                                    @foreach($availableGateways as $gateway)
                                        <option value="{{ $gateway['name'] }}" {{ $gatewayName === $gateway['name'] ? 'selected' : '' }}>
                                            {{ $gateway['display_name'] ?? $gateway['label'] }}
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary btn-sm w-100">
                                <i class="fas fa-sync me-2"></i>{{ __('store.payment_update_gateway') }}
                            </button>
                        </form>
                    </div>
                </div>
            @endif

            <!-- Invoice & Order Summary (Combined) -->
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">{{ __('store.payment_order_summary') }}</h5>
                </div>
                <div class="card-body">
                    <!-- Invoice Info -->
                    <div class="mb-3">
                        <div class="d-flex justify-content-between mb-1">
                            <span class="small text-muted">{{ __('store.payment_invoice_number') }}:</span>
                            <strong class="small">{{ $invoice->invoice_number }}</strong>
                        </div>
                        <div class="d-flex justify-content-between mb-1">
                            <span class="small text-muted">{{ __('store.payment_due_date') }}:</span>
                            <strong class="small">{{ $invoice->due_date->format($dateFormat) }}</strong>
                        </div>
                        <div class="d-flex justify-content-between mb-0">
                            <span class="small text-muted">{{ __('store.payment_gateway') }}:</span>
                            <strong class="small">{{ $paymentGateway['display_name'] ?? $paymentGateway['label'] }}</strong>
                        </div>
                    </div>

                    <hr class="my-2">

                    <!-- Order / Invoice Items -->
                    @if($order)
                        @foreach($order->items as $item)
                            <div class="d-flex justify-content-between mb-2">
                                <span class="small">{{ $item->name }}</span>
                                <span class="small">{{ $invoice->currency->format($item->total_price) }}</span>
                            </div>
                            @if($item->setup_fee > 0)
                                <div class="d-flex justify-content-between mb-2 text-muted">
                                    <span class="small">&nbsp;&nbsp;{{ __('store.payment_setup_fee') }}</span>
                                    <span class="small">{{ $invoice->currency->format($item->setup_fee) }}</span>
                                </div>
                            @endif
                        @endforeach
                    @else
                        @foreach($invoice->items as $item)
                            <div class="d-flex justify-content-between mb-2">
                                <span class="small">{{ $item->description }}</span>
                                <span class="small">{{ $invoice->currency->format($item->line_total) }}</span>
                            </div>
                        @endforeach
                    @endif

                    <hr class="my-2">

                    <!-- Totals -->
                    <div class="d-flex justify-content-between mb-1">
                        <span class="small">{{ __('store.payment_subtotal') }}</span>
                        <span class="small">{{ $invoice->currency->format($invoice->subtotal) }}</span>
                    </div>

                    @if($invoice->discount_amount > 0)
                        <div class="d-flex justify-content-between mb-1 text-success">
                            <span class="small">{{ __('store.payment_discount') }}</span>
                            <span class="small">-{{ $invoice->currency->format($invoice->discount_amount) }}</span>
                        </div>
                    @endif

                    @if($invoice->tax_amount > 0)
                        <div class="d-flex justify-content-between mb-1">
                            <span class="small">{{ __('store.payment_tax') }}</span>
                            <span class="small">{{ $invoice->currency->format($invoice->tax_amount) }}</span>
                        </div>
                    @endif

                    @if($invoice->gateway_fee > 0)
                        <div class="d-flex justify-content-between mb-1">
                            <span class="small">{{ __('store.payment_gateway_fee') }}</span>
                            <span class="small">{{ $invoice->currency->format($invoice->gateway_fee) }}</span>
                        </div>
                    @endif

                    <hr class="my-2">

                    <div class="d-flex justify-content-between mb-0">
                        <strong>{{ __('store.payment_total') }}</strong>
                        <strong>{{ $invoice->currency->format($invoice->total_amount) }}</strong>
                    </div>

                    
                    @if(($invoice->credit_applied ?? 0) > 0)
                        <div class="d-flex justify-content-between mb-0 mt-1 text-success">
                            <span class="small">{{ __('store.use_credit_balance') }}</span>
                            <span class="small">-{{ $invoice->currency->format($invoice->credit_applied) }}</span>
                        </div>
                        <div class="d-flex justify-content-between mb-0 mt-1">
                            <strong>{{ __('store.amount_to_pay') }}</strong>
                            <strong>{{ $invoice->currency->format($invoice->amountDue()) }}</strong>
                        </div>
                    @endif

                    @if($invoice->billingAddress)
                        <hr class="my-2">
                        <div class="small text-muted">
                            <div class="fw-bold mb-1">{{ __('store.payment_billing_address') }}</div>
                            <div>{{ $invoice->billingAddress->first_name }} {{ $invoice->billingAddress->last_name }}</div>
                            @if($invoice->billingAddress->company_name)
                                <div>{{ $invoice->billingAddress->company_name }}</div>
                            @endif
                            <div>{{ $invoice->billingAddress->address1 }}</div>
                            @if($invoice->billingAddress->address2)
                                <div>{{ $invoice->billingAddress->address2 }}</div>
                            @endif
                            <div>{{ $invoice->billingAddress->city }}, {{ $invoice->billingAddress->postcode }}</div>
                            <div>{{ $invoice->billingAddress->country->name }}</div>
                        </div>
                    @endif
                </div>
            </div>

            <!-- Payment Security Info -->
            <div class="card mt-3">
                <div class="card-body text-center py-3">
                    <i class="fas fa-shield-alt fa-2x text-success mb-2"></i>
                    <p class="small text-muted mb-0">{{ __('store.payment_security_notice') }}</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
window.apiEndpoint = '{{ route("store.payment.process", ":id") }}';
window.csrfToken = '{{ csrf_token() }}';
window.translations = window.translations || {};
window.translations.processingPayment = '{{ __("store.payment_processing") }}';
window.translations.errorOccurred = '{{ __("store.messages_error_occurred") }}';
window.translations.copyFailed = '{{ __("store.payment_copy_failed") }}';
window.translations.copied = '{{ __("store.payment_copy") }}';

// Copy to clipboard function
function copyToClipboard(elementId) {
    const element = document.getElementById(elementId);
    if (!element) return;

    const text = element.textContent;

    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(text).then(function() {
            showCopySuccess(elementId);
        }, function() {
            alert(window.translations?.copyFailed || 'Copy failed');
        });
    } else {
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            document.execCommand('copy');
            showCopySuccess(elementId);
        } catch (err) {
            alert(window.translations?.copyFailed || 'Copy failed');
        }

        document.body.removeChild(textArea);
    }
}

function showCopySuccess(elementId) {
    const button = document.querySelector(`#${elementId} + button`);
    if (button) {
        const originalHTML = button.innerHTML;
        button.innerHTML = '<i class="fas fa-check"></i>';
        button.classList.add('btn-success');
        button.classList.remove('btn-outline-secondary');

        setTimeout(() => {
            button.innerHTML = originalHTML;
            button.classList.remove('btn-success');
            button.classList.add('btn-outline-secondary');
        }, 2000);
    }
}
</script>
@endsection

@push('scripts')
<script>
// Payment processing scripts will be added here based on gateway type
document.addEventListener('DOMContentLoaded', function() {
    // Common payment form handling
    const paymentForms = document.querySelectorAll('form[data-payment-form]');

    paymentForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();

            const submitBtn = form.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;

            submitBtn.disabled = true;
            submitBtn.textContent = window.translations?.processingPayment || 'Processing...';

            // Submit form after a brief delay to show loading state
            setTimeout(() => {
                form.submit();
            }, 500);
        });
    });
});
</script>
@endpush
