<!-- 3D Secure Credit Card Payment Form -->
<form method="POST" action="{{ route('store.payment.process', $invoice->id) }}" data-payment-form="credit-card-3d" id="paymentForm3d">
    @csrf

    @if(isset($savedMethods) && $savedMethods->count() > 0)
    {{-- Payment Method Selection Tabs --}}
    <div class="btn-group w-100 mb-4" role="group">
        <input type="radio" class="btn-check" name="payment_source" id="ps_saved" value="saved" checked>
        <label class="btn btn-outline-primary" for="ps_saved">
            <i class="fas fa-wallet me-2"></i>{{ __('store.payment_saved_cards') }}
        </label>
        <input type="radio" class="btn-check" name="payment_source" id="ps_new" value="new">
        <label class="btn btn-outline-primary" for="ps_new">
            <i class="fas fa-credit-card me-2"></i>{{ __('store.payment_new_card') }}
        </label>
    </div>

    {{-- Saved Cards Panel --}}
    <div id="savedCardsPanel">
        <input type="hidden" name="saved_method_id" id="saved_method_id" value="{{ $savedMethods->first()->id }}">
        @foreach($savedMethods as $method)
        <div class="form-check border rounded p-3 mb-2 saved-card-option {{ $loop->first ? 'border-primary' : '' }}" style="cursor: pointer;">
            <input class="form-check-input" type="radio" name="_saved_card_radio" id="card_{{ $method->id }}"
                   value="{{ $method->id }}" {{ $loop->first ? 'checked' : '' }}>
            <label class="form-check-label d-flex align-items-center justify-content-between w-100" for="card_{{ $method->id }}" style="cursor: pointer;">
                <span>
                    <i class="fab fa-cc-{{ strtolower($method->card_brand ?: 'card') }} fa-lg me-2"></i>
                    <strong>{{ strtoupper($method->card_brand ?: 'Card') }}</strong>
                    •••• {{ $method->last_four }}
                    @if($method->expiry_month && $method->expiry_year)
                        <span class="text-muted ms-2">{{ str_pad($method->expiry_month, 2, '0', STR_PAD_LEFT) }}/{{ $method->expiry_year }}</span>
                    @endif
                    @if($method->label)
                        <span class="text-muted ms-1">({{ $method->label }})</span>
                    @endif
                </span>
                @if($method->is_default)
                    <span class="badge bg-success">{{ __('store/auto-pay.default') }}</span>
                @endif
            </label>
        </div>
        @endforeach
    </div>
    @endif

    {{-- New Card Panel --}}
    <div id="newCardPanel" @if(isset($savedMethods) && $savedMethods->count() > 0) style="display:none;" @endif>
        <div class="row mb-3">
            <div class="col-md-12">
                <label class="form-label">{{ __('store.payment_card_number') }}</label>
                <input type="text" class="form-control" name="card_number" id="card_number_3d"
                       placeholder="1234 5678 9012 3456" maxlength="19"
                       pattern="[0-9\s]{13,19}" autocomplete="cc-number">
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-12">
                <label class="form-label">{{ __('store.payment_card_holder') }}</label>
                <input type="text" class="form-control" name="card_holder" id="card_holder_3d"
                       placeholder="{{ __('store.payment_card_holder_placeholder') }}" autocomplete="cc-name">
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-6">
                <label class="form-label">{{ __('store.payment_expiry_month') }}</label>
                <select class="form-control" name="expiry_month" id="expiry_month_3d" autocomplete="cc-exp-month">
                    <option value="">{{ __('store.payment_select_month') }}</option>
                    @for($i = 1; $i <= 12; $i++)
                        <option value="{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}">{{ str_pad($i, 2, '0', STR_PAD_LEFT) }}</option>
                    @endfor
                </select>
            </div>
            <div class="col-md-6">
                <label class="form-label">{{ __('store.payment_expiry_year') }}</label>
                <select class="form-control" name="expiry_year" id="expiry_year_3d" autocomplete="cc-exp-year">
                    <option value="">{{ __('store.payment_select_year') }}</option>
                    @for($i = date('Y'); $i <= date('Y') + 10; $i++)
                        <option value="{{ $i }}">{{ $i }}</option>
                    @endfor
                </select>
            </div>
        </div>

        <div class="row mb-3">
            <div class="col-md-6">
                <label class="form-label">{{ __('store.payment_cvv') }}</label>
                <input type="text" class="form-control" name="cvv" id="cvv_3d"
                       placeholder="123" maxlength="4" pattern="[0-9]{3,4}" autocomplete="cc-csc">
            </div>
            @if($features['save_card'] ?? false)
            <div class="col-md-6 d-flex align-items-end">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" name="save_card" value="1" id="save_card_3d">
                    <label class="form-check-label" for="save_card_3d">
                        {{ __('store.payment_save_card') }}
                    </label>
                </div>
            </div>
            @endif
        </div>
    </div>

    <div class="alert alert-warning">
        <i class="fas fa-shield-alt"></i>
        {{ __('store.payment_3d_payment_info') }}
    </div>

    <button type="submit" class="btn btn-primary btn-lg w-100" id="payBtn3d">
        <i class="fas fa-shield-alt me-2"></i>
        {{ __('store.payment_pay_with_3d') }} - {{ $invoice->currency->format($invoice->total_amount) }}
    </button>
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
    var form = document.getElementById('paymentForm3d');
    var savedPanel = document.getElementById('savedCardsPanel');
    var newPanel = document.getElementById('newCardPanel');
    var savedMethodInput = document.getElementById('saved_method_id');
    var newCardFields = ['card_number_3d', 'card_holder_3d', 'expiry_month_3d', 'expiry_year_3d', 'cvv_3d'];

    // Tab switching — listen on both change and click for Bootstrap btn-check compatibility
    var radios = document.querySelectorAll('input[name="payment_source"]');
    function handleSourceSwitch(radio) {
        if (radio.value === 'saved') {
            savedPanel.style.display = '';
            newPanel.style.display = 'none';
            // Restore saved_method_id from selected radio
            var selectedCard = document.querySelector('input[name="_saved_card_radio"]:checked');
            if (savedMethodInput && selectedCard) savedMethodInput.value = selectedCard.value;
            newCardFields.forEach(function(id) {
                var el = document.getElementById(id);
                if (el) { el.removeAttribute('required'); }
            });
        } else {
            savedPanel.style.display = 'none';
            newPanel.style.display = '';
            newCardFields.forEach(function(id) {
                var el = document.getElementById(id);
                if (el) { el.setAttribute('required', ''); }
            });
            if (savedMethodInput) savedMethodInput.value = '';
        }
    }
    radios.forEach(function(radio) {
        radio.addEventListener('change', function() { handleSourceSwitch(this); });
    });
    // Also listen on label clicks for Bootstrap btn-check
    document.querySelectorAll('label[for="ps_saved"], label[for="ps_new"]').forEach(function(label) {
        label.addEventListener('click', function() {
            var radio = document.getElementById(this.getAttribute('for'));
            if (radio) { radio.checked = true; handleSourceSwitch(radio); }
        });
    });

    // Saved card radio selection → update hidden input + highlight
    var cardRadios = document.querySelectorAll('input[name="_saved_card_radio"]');
    cardRadios.forEach(function(radio) {
        radio.addEventListener('change', function() {
            if (savedMethodInput) savedMethodInput.value = this.value;
            document.querySelectorAll('.saved-card-option').forEach(function(el) {
                el.classList.remove('border-primary');
            });
            this.closest('.saved-card-option').classList.add('border-primary');
        });
    });

    // Form validation before submit
    if (form) {
        form.addEventListener('submit', function(e) {
            var source = document.querySelector('input[name="payment_source"]:checked');
            if (source && source.value === 'saved') {
                // Remove required from new card fields
                newCardFields.forEach(function(id) {
                    var el = document.getElementById(id);
                    if (el) { el.removeAttribute('required'); el.value = ''; }
                });
            }
        });
    }

    // Card number formatting
    var cardNumberInput = document.getElementById('card_number_3d');
    if (cardNumberInput) {
        cardNumberInput.addEventListener('input', function(e) {
            var value = e.target.value.replace(/\s/g, '').replace(/[^0-9]/gi, '');
            var formatted = value.match(/.{1,4}/g);
            e.target.value = formatted ? formatted.join(' ') : value;
        });
    }

    // CVV numeric only
    var cvvInput = document.getElementById('cvv_3d');
    if (cvvInput) {
        cvvInput.addEventListener('input', function(e) {
            e.target.value = e.target.value.replace(/[^0-9]/g, '');
        });
    }
});
</script>
