@extends('layouts.app')
@section('title', 'Wallet Transactions')

@section('content')
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.20/dist/sweetalert2.min.css">

    <style>
        body {
            background-color: #f8f9fc;
        }

        /* Minimal custom styles for consistency with Bootstrap */
        .content {
            padding: 1.5rem;
        }

        section.waiting-section {
            text-align: center;
            background-color: rgba(255, 255, 255, 0.74);
            position: absolute;
            width: 100%;
            height: 100%;
            top: 0;
            z-index: 2;
        }

        section.waiting-section div.payment-processing {
            padding-top: 20%;
        }

        section.waiting-section p {
            font-size: 1rem;
        }

        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        input[type=number] {
            -moz-appearance: textfield;
        }

        .border {
            border: 1px solid #c9cdd0 !important;
        }

        /* Custom shadow for saved cards */
        .card-shadow {
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            transition: box-shadow 0.2s ease-in-out;
        }

        .card-shadow:hover {
            box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
        }

        /* Highlight default card */
        .default-card {
            border-left: 4px solid #28a745;
            background-color: rgba(40, 167, 69, 0.05);
        }
    </style>

    <div class="row">
        <div class="col-md-12">
            <div class="container-fluid">
                <div class="row">
                    <div class="col-md-12 content">
                        <!-- Page Header -->
                        <div class="d-flex align-items-center justify-content-between mb-4">
                            <div class="d-flex align-items-center gap-2">
                                <a href="{{ url()->previous() }}" class="btn btn-light d-flex align-items-center px-2 py-1">
                                    <i class="fa fa-arrow-left me-1"></i>
                                </a>
                                <h4 class="mb-0">Manage Payments</h4>
                            </div>
                            <div class="d-flex gap-2">
                                <a href="javascript:void(0);" data-bs-toggle="tooltip" data-bs-placement="top"
                                    data-bs-original-title="Refresh" class="btn btn-light">
                                    <i class="fa fa-refresh"></i>
                                </a>
                                <a href="javascript:void(0);" data-bs-toggle="tooltip" data-bs-placement="top"
                                    data-bs-original-title="Collapse" id="collapse-header" class="btn btn-light">
                                    <i class="fa fa-chevron-up"></i>
                                </a>
                            </div>
                        </div>

                        <!-- Payment Methods List -->
                        @if(count($paymentMethods) > 0)
                            <div class="card mb-3">
                                <div class="card-body">
                                    <h6 class="card-title mb-3">All Cards</h6>
                                    @foreach($paymentMethods as $paymentMethod)
                                        <div
                                            class="card border mb-2 p-3 bg-white card-shadow d-flex flex-column flex-md-row justify-content-between align-items-md-center {{ isset($paymentMethod->is_default) ? $paymentMethod->is_default ? 'default-card' : '' : '' }}">
                                            <div class="mb-2 mb-md-0">
                                                <strong>
                                                    <span
                                                        class="fs-5 fw-bold text-uppercase me-2">{{ ucwords($paymentMethod->card->brand ?? '') }}</span>
                                                    <span class="font-monospace text-muted">XXXX XXXX XXXX
                                                        {{ $paymentMethod->card->last4 ?? '' }}</span>
                                                </strong>
                                                <div class="mt-2">
                                                    <small class="d-block">Expires:
                                                        {{ $paymentMethod->card->exp_month ?? '' }}/{{ $paymentMethod->card->exp_year ?? '' }}</small>
                                                    <small class="d-block text-muted">
                                                        Added on
                                                        {{ \App\Helper\Helper::getFormattedDateTimeWithTimezone($paymentMethod->created, auth()->user()?->time_zone ?? 'UTC') }}
                                                    </small>
                                                </div>
                                            </div>
                                            <div class="d-flex gap-2 align-items-center">
                                                @if(isset($defaultPaymentMethod) && ($defaultPaymentMethod == $paymentMethod->id))
                                                    <span class="badge bg-success">Default</span>
                                                @else
                                                    <a href="javascript:void(0);"
                                                        class="btn btn-outline-success  btn-sm set-default-btn"
                                                        data-id="{{ $paymentMethod->id }}" title="Set as Default">
                                                        <i class="fa fa-star me-1"></i>Set as Default
                                                    </a>
                                                @endif
                                                <a type="button" class="btn btn-danger btn-sm delete-btn"
                                                    data-id="{{ $paymentMethod->id }}" title="Delete">Remove</a>
                                            </div>
                                        </div>
                                    @endforeach
                                </div>
                            </div>
                        @else
                            <div class="card mb-3">
                                <div class="card-body">
                                    <p class="mb-0">No payment methods found. <a href="#add-card-section">Add a card</a> to get
                                        started.</p>
                                </div>
                            </div>
                        @endif

                        <!-- Add New Card Form -->
                        <div class="card" id="add-card-section">
                            <div class="card-header border-bottom">
                                <h5 class="card-title mb-0">Add New Card</h5>
                            </div>
                            <div class="card-body">
                                <form id="stripeForm" method="post">
                                    @csrf
                                    <div class="row g-3">
                                        <div class="col-md-3">
                                            <label class="form-label">Cardholder Name <span
                                                    class="text-danger">*</span></label>
                                            <input type="text" class="form-control" placeholder="John Doe"
                                                id="cardholder-name" required>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Card Details <span
                                                    class="text-danger">*</span></label>
                                            <div id="card-element" class="form-control p-2"></div>
                                            <div id="card-errors" class="text-danger mt-1"></div>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Billing Address</label>
                                            <input type="text" class="form-control" placeholder="Enter Billing Address"
                                                id="line1" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">City</label>
                                            <input type="text" class="form-control" placeholder="City" id="city" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">State</label>
                                            <input type="text" class="form-control" placeholder="State" id="state" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Zip</label>
                                            <input type="text" class="form-control" placeholder="Zip" id="postal_code"
                                                maxlength="6" required>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Country</label>
                                            <select class="form-select" id="country" required>
                                                <option value="CA">🇨🇦 Canada</option>
                                                <option value="US">🇺🇸 United States</option>
                                                <option value="GB">🇬🇧 United Kingdom</option>
                                            </select>
                                        </div>
                                        <div class="col-md-12">
                                            <div class="form-check px-0">
                                                <input class="form-check-input" type="checkbox" id="set-default-card"
                                                    name="set_default">
                                                <label class="form-check-label" for="set-default-card">
                                                    Set as default payment method
                                                </label>
                                            </div>
                                        </div>
                                        <div class="col-md-12 d-flex justify-content-end mt-3">
                                            <button type="submit" id="submitBtn" class="btn btn-success">Add New
                                                Card</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <section class="waiting-section" style="display: none">
        <div class="payment-processing">
            <img src="{{ asset('assets/images/loader-30px.gif') }}" alt="Loading">
            <p>Your Card is being Saved!</p>
        </div>
    </section>

    <script src="https://js.stripe.com/v3/"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.js" integrity="sha256-JlqSTELeR4TLqP0OG9dxM7yDPqX1ox/HfgiSLBj8+kM="
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.20/dist/sweetalert2.all.min.js"></script>
    <script src="https://unpkg.com/imask"></script>
    <script src="{{ asset('assets/js/country-states.js') }}"></script>

    <script>
        const stripe = Stripe("{{ env('STRIPE_KEY') }}");
        const elements = stripe.elements();

        const cardElement = elements.create('card', {
            style: {
                base: {
                    fontSize: '16px',
                    color: '#32325d',
                }
            }
        });
        cardElement.mount('#card-element');

        const waitingSection = document.querySelector('.waiting-section');
        const submitBtn = document.getElementById('submitBtn');
        const form = document.getElementById('stripeForm');

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            waitingSection.style.display = 'block';
            submitBtn.disabled = true;
            document.getElementById('card-errors').textContent = '';

            // Show loading alert
            Swal.fire({
                title: 'Processing',
                text: 'Adding your card, please wait...',
                icon: 'info',
                allowOutsideClick: false,
                allowEscapeKey: false,
                showConfirmButton: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            const cardholderName = document.getElementById('cardholder-name').value;
            const setDefault = document.getElementById('set-default-card').checked;
            const billingDetails = {
                name: cardholderName,
                address: {
                    line1: document.getElementById('line1').value,
                    city: document.getElementById('city').value,
                    state: document.getElementById('state').value,
                    postal_code: document.getElementById('postal_code').value,
                    country: document.getElementById('country').value,
                }
            };

            const { paymentMethod, error } = await stripe.createPaymentMethod({
                type: 'card',
                card: cardElement,
                billing_details: billingDetails
            });

            if (error) {
                waitingSection.style.display = 'none';
                submitBtn.disabled = false;
                Swal.fire({
                    title: 'Error!',
                    text: error.message,
                    icon: 'error',
                    confirmButtonText: 'OK'
                });
                return;
            }

            fetch("{{ url('stripe/save-card') }}", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": "{{ csrf_token() }}"
                },
                body: JSON.stringify({
                    payment_method: paymentMethod.id,
                    set_default: setDefault
                })
            })
                .then(res => res.json())
                .then(data => {
                    waitingSection.style.display = 'none';
                    submitBtn.disabled = false;
                    if (data.success) {
                        // Show success alert with countdown
                        let timerInterval;
                        Swal.fire({
                            title: 'Success!',
                            html: 'Card added successfully! Refreshing in <b>5</b> seconds.',
                            icon: 'success',
                            timer: 5000,
                            timerProgressBar: true,
                            showConfirmButton: false,
                            didOpen: () => {
                                const b = Swal.getHtmlContainer().querySelector('b');
                                timerInterval = setInterval(() => {
                                    b.textContent = Math.ceil(Swal.getTimerLeft() / 1000);
                                }, 100);
                            },
                            willClose: () => {
                                clearInterval(timerInterval);
                            }
                        }).then(() => {
                            window.location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: data.message || 'Failed to add card.',
                            icon: 'error',
                            confirmButtonText: 'OK'
                        });
                    }
                })
                .catch(error => {
                    waitingSection.style.display = 'none';
                    submitBtn.disabled = false;
                    Swal.fire({
                        title: 'Error!',
                        text: 'An unexpected error occurred.',
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                });
        });

        // Set Default Card Functionality
        $(document).on('click', '.set-default-btn', function () {
            const methodId = $(this).data('id');
            Swal.fire({
                title: 'Confirm Default Card',
                text: 'Are you sure you want to make this card your default payment method?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#28a745',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, Set as Default',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading alert for setting default
                    Swal.fire({
                        title: 'Processing',
                        text: 'Setting your default card, please wait...',
                        icon: 'info',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    fetch("{{ url('set-default-payment-method') }}", {
                        method: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': "{{ csrf_token() }}",
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            payment_method_id: methodId
                        })
                    })
                        .then(res => res.json())
                        .then(data => {
                            if (data.success) {
                                // Show success alert with countdown
                                let timerInterval;
                                Swal.fire({
                                    title: 'Success!',
                                    html: 'Default card set successfully! Refreshing in <b>5</b> seconds.',
                                    icon: 'success',
                                    timer: 5000,
                                    timerProgressBar: true,
                                    showConfirmButton: false,
                                    didOpen: () => {
                                        const b = Swal.getHtmlContainer().querySelector('b');
                                        timerInterval = setInterval(() => {
                                            b.textContent = Math.ceil(Swal.getTimerLeft() / 1000);
                                        }, 100);
                                    },
                                    willClose: () => {
                                        clearInterval(timerInterval);
                                    }
                                }).then(() => {
                                    window.location.reload();
                                });
                            } else {
                                Swal.fire({
                                    title: 'Error!',
                                    text: data.message || 'Failed to set default card.',
                                    icon: 'error',
                                    confirmButtonText: 'OK'
                                });
                            }
                        })
                        .catch(error => {
                            Swal.fire({
                                title: 'Error!',
                                text: 'An unexpected error occurred. Please try again.',
                                icon: 'error',
                                confirmButtonText: 'OK'
                            });
                            console.error('Error:', error);
                        });
                }
            });
        });

        $('.delete-btn').on('click', function () {
            const methodId = $(this).data('id');
            Swal.fire({
                title: 'Confirm Deletion',
                text: 'Are you sure you want to remove this card? This action cannot be undone.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, Remove Card',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading alert for deletion
                    Swal.fire({
                        title: 'Processing',
                        text: 'Removing your card, please wait...',
                        icon: 'info',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });

                    fetch("{{ url('delete-payment-method') }}/" + methodId, {
                        method: 'GET', // Using GET as per route definition
                        headers: {
                            'X-CSRF-TOKEN': "{{ csrf_token() }}",
                            'Content-Type': 'application/json'
                        }
                    })
                        .then(res => res.json())
                        .then(data => {
                            if (data.success) {
                                // Show success alert with countdown
                                let timerInterval;
                                Swal.fire({
                                    title: 'Success!',
                                    html: 'Card removed successfully! Refreshing in <b>5</b> seconds.',
                                    icon: 'success',
                                    timer: 5000,
                                    timerProgressBar: true,
                                    showConfirmButton: false,
                                    didOpen: () => {
                                        const b = Swal.getHtmlContainer().querySelector('b');
                                        timerInterval = setInterval(() => {
                                            b.textContent = Math.ceil(Swal.getTimerLeft() / 1000);
                                        }, 100);
                                    },
                                    willClose: () => {
                                        clearInterval(timerInterval);
                                    }
                                }).then(() => {
                                    window.location.reload();
                                });
                            } else {
                                Swal.fire({
                                    title: 'Error!',
                                    text: data.message || 'Failed to remove card.',
                                    icon: 'error',
                                    confirmButtonText: 'OK'
                                });
                            }
                        })
                        .catch(error => {
                            Swal.fire({
                                title: 'Error!',
                                text: 'An unexpected error occurred. Please try again.',
                                icon: 'error',
                                confirmButtonText: 'OK'
                            });
                            console.error('Error:', error);
                        });
                }
            });
        });

        (function () {
            let country_list = country_and_states['country'];
            let states_list = country_and_states['states'];

            let option = '<option value="">Select country</option>';
            for (let country_code in country_list) {
                option += '<option value="' + country_code + '">' + country_list[country_code] + '</option>';
            }
            document.getElementById('country').innerHTML = option;

            let state_code_append_id = document.getElementById("state");

            function create_states_dropdown() {
                let country_code = document.getElementById("country").value;
                let states = states_list[country_code];

                let option = '';
                if (!states || states.length === 0) {
                    option = '<input type="text" class="form-control" id="state" name="state" placeholder="State" required>';
                } else {
                    option = '<select class="form-control" name="state" id="state" required>';
                    for (let i = 0; i < states.length; i++) {
                        option += '<option value="' + states[i].name + '">' + states[i].name + '</option>';
                    }
                    option += '</select>';
                }
                state_code_append_id.outerHTML = option;
            }

            document.getElementById("country").addEventListener('change', create_states_dropdown);
        })();
    </script>
@endsection
