<div class="accordion bg-body-tertiary rounded-5 p-4">
    <div class="accordion-item border-0">
        <h3 class="accordion-header" id="promoCodeHeading">
            <button type="button"
                class="accordion-button animate-underline collapsed py-0 ps-sm-2 ps-lg-0 ps-xl-2"
                data-bs-toggle="collapse"
                data-bs-target="#promoCode"
                aria-expanded="false"
                aria-controls="promoCode">
                <i class="ci-percent fs-xl me-2"></i>
                <span class="animate-target me-2">
                    {{ __('checkout.apply_promo_code') }}
                </span>
            </button>
        </h3>

        <div class="accordion-collapse collapse"
             id="promoCode"
             aria-labelledby="promoCodeHeading">

            <div class="accordion-body pt-3 pb-2 ps-sm-2 px-lg-0 px-xl-2">

                {{-- Promo Code Form --}}
                <form class="needs-validation d-flex gap-2" novalidate>
                    <div class="position-relative w-100">
                        <input type="text"
                               class="form-control"
                               placeholder="{{ __('checkout.enter_promo_code') }}"
                               required>

                        <div class="invalid-tooltip bg-transparent py-0">
                            {{ __('checkout.enter_valid_promo_code') }}
                        </div>
                    </div>

                    <button type="submit" class="btn btn-dark">
                        {{ __('checkout.apply') }}
                    </button>
                </form>


                {{-- List Voucher --}}
                @if($vouchers && count($vouchers) > 0)
                    <div class="mt-3">
                        <h6 class="mb-2">
                            {{ __('checkout.available_vouchers') }}
                        </h6>

                        <div class="d-flex flex-wrap gap-2">
                            @foreach($vouchers as $voucher)
                                <span class="badge bg-light text-dark px-3 py-2">
                                    {{ $voucher->code }}
                                </span>
                            @endforeach
                        </div>
                    </div>
                @endif


                {{-- List Voucher Events --}}
                @if($voucher_events && count($voucher_events) > 0)
                    <div class="mt-3">
                        <h6 class="mb-2">
                            {{ __('checkout.available_voucher_events') }}
                        </h6>

                        <div class="d-flex flex-wrap gap-2">
                            @foreach($voucher_events as $voucher_event)
                                <span class="badge bg-primary text-white px-3 py-2"
                                      style="cursor:pointer"
                                      data-id="{{ $voucher_event->id }}"
                                      data-name="{{ $voucher_event->name }}"
                                      data-description="{{ $voucher_event->description }}"
                                      data-point="{{ $voucher_event->redeem_point }}"
                                      data-start="{{ $voucher_event->start_date }}"
                                      data-end="{{ $voucher_event->end_date }}"
                                      data-terms="{{ $voucher_event->terms_and_conditions }}"
                                      data-bs-toggle="modal"
                                      data-bs-target="#voucherEventModal">
                                    {{ $voucher_event->name ?? '-' }}
                                </span>
                            @endforeach
                        </div>
                    </div>
                @endif

            </div>
        </div>
    </div>
</div>



{{-- SINGLE REUSABLE MODAL --}}
<div class="modal fade" id="voucherEventModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content rounded-4">
            <div class="modal-header border-0">
                <h5 class="modal-title fw-semibold">
                    Voucher Event
                </h5>
                <button type="button"
                        class="btn-close"
                        data-bs-dismiss="modal">
                </button>
            </div>

            <div class="modal-body pt-0">
                <div id="voucherEventContent"></div>
            </div>

            <div class="modal-footer border-0">
                <button type="button"
                        class="btn btn-secondary"
                        data-bs-dismiss="modal">
                    {{ __('checkout.close') }}
                </button>

                <button type="button"
                        class="btn btn-primary"
                        id="redeemVoucherBtn"
                        data-voucher-event-id="">
                    {{ __('checkout.redeem') }}
                </button>
            </div>
        </div>
    </div>
</div>



<script>
document.addEventListener('DOMContentLoaded', function () {

    const modal = document.getElementById('voucherEventModal');

    modal.addEventListener('show.bs.modal', function (event) {

        const button = event.relatedTarget;

        const name = button.getAttribute('data-name');
        const description = button.getAttribute('data-description');
        const point = button.getAttribute('data-point');
        const start = button.getAttribute('data-start');
        const end = button.getAttribute('data-end');
        const terms = button.getAttribute('data-terms');

        let content = '';

        if (description) {
            content += `<p>${description}</p>`;
        }

        if (point) {
            content += `
                <div class="mb-2">
                    <strong>{{ __('checkout.points_required') }}:</strong>
                    ${point}
                </div>
            `;
        }

        if (start && end) {
            content += `
                <div class="mb-2">
                    <strong>{{ __('checkout.valid_period') }}:</strong><br>
                    ${start} - ${end}
                </div>
            `;
        }

        if (terms) {
            content += `
                <div class="mt-3 small text-muted">
                    <strong>{{ __('checkout.terms_and_conditions') }}:</strong>
                    <p>${terms}</p>
                </div>
            `;
        }

        modal.querySelector('.modal-title').textContent = name;
        document.getElementById('voucherEventContent').innerHTML = content;
        
        // Set voucher event ID for redeem button
        const redeemBtn = document.getElementById('redeemVoucherBtn');
        redeemBtn.setAttribute('data-voucher-event-id', button.getAttribute('data-id'));

    });

    // Handle redeem button click
    document.getElementById('redeemVoucherBtn').addEventListener('click', function() {
        const voucherEventId = this.getAttribute('data-voucher-event-id');
        
        if (!voucherEventId) {
            console.error('No voucher event ID found');
            return;
        }
        
        // Disable button during processing
        this.disabled = true;
        this.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';
        
        // Make AJAX call to redeem voucher
        fetch(`/voucher-events/${voucherEventId}/redeem`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
            },
            body: JSON.stringify({})
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // Show success message
                alert('Voucher redeemed successfully!');
                
                // Close modal
                const modal = bootstrap.Modal.getInstance(document.getElementById('voucherEventModal'));
                modal.hide();
                
                // Reload page to update cart
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                // Show error message
                alert(data.message || 'Failed to redeem voucher');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while redeeming the voucher');
        })
        .finally(() => {
            // Re-enable button
            this.disabled = false;
            this.innerHTML = '{{ __('checkout.redeem') }}';
        });
    });

    // Custom modal handler to prevent backdrop issues
    const voucherBadges = document.querySelectorAll('[data-bs-toggle="modal"][data-bs-target="#voucherEventModal"]');
    voucherBadges.forEach(function(badge) {
        badge.addEventListener('click', function(e) {
            e.preventDefault();
            
            // Remove any existing backdrop
            const existingBackdrop = document.querySelector('.modal-backdrop');
            if (existingBackdrop) {
                existingBackdrop.remove();
            }
            
            // Show modal without backdrop
            const modalInstance = new bootstrap.Modal(modal, {
                backdrop: false
            });
            modalInstance.show();
        });
    });

});

</script>