@extends('layouts.app')

@section('title', 'My Orders - ' . \App\Models\Setting::get('site_name', 'KiyoKart'))

@push('styles')
<style>
    /* Order Cards */
    .order-card {
        background: #FFFFFF;
        border: 1px solid #E5E7EB;
        border-radius: 16px;
        padding: 1rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
        transition: all 0.3s ease;
    }

    .order-card:hover {
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
        transform: translateY(-2px);
    }

    .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        /* margin-bottom: 1.25rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid #F3F4F6; */
    }

    .order-id-section {
         display: flex;
        align-items: center;
    }

    .order-id {
        font-size: 1rem;
        font-weight: 700;
        color: var(--color-primary);
        /* margin-bottom: 0.5rem; */
    }

    .order-date {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        color: #6B7280;
        font-size: 0.8rem;
    }

    .order-badges {
        display: flex;
        /* flex-direction: column; */
        align-items: center;
        gap: 0.5rem;
    }

    /* Status Badges */
    .status-badge {
        padding: 0.5rem 1rem;
        border-radius: 20px;
        font-size: 0.65rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .status-awaiting_payment {
        background-color: #FEF3C7;
        color: #92400E;
        border: 1px solid #FCD34D;
    }

    .status-placed {
        background-color: #FFF7ED;
        color: #C2410C;
        border: 1px solid #FED7AA;
    }

    .status-pending {
        background-color: #FFF7ED;
        color: #C2410C;
        border: 1px solid #FED7AA;
    }

    .status-confirmed {
        background-color: #EFF6FF;
        color: #1E40AF;
        border: 1px solid #BFDBFE;
    }

    .status-packed {
        background-color: #F0F9FF;
        color: #0369A1;
        border: 1px solid #BAE6FD;
    }

    .status-shipped {
        background-color: #DBEAFE;
        color: #1E3A8A;
        border: 1px solid #93C5FD;
    }

    .status-delivered {
        background-color: #D1FAE5;
        color: #065F46;
        border: 1px solid #6EE7B7;
    }

    .status-cancelled {
        background-color: #FEE2E2;
        color: #991B1B;
        border: 1px solid #FCA5A5;
    }

    /* Payment Badge */
    .payment-badge {
        padding: 0.375rem 0.75rem;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: 500;
    }

    .payment-paid {
        background-color: #D1FAE5;
        color: #065F46;
    }

    .payment-pending {
        background-color: #FEF3C7;
        color: #92400E;
    }

    .payment-cod {
        background-color: #DBEAFE;
        color: #1E40AF;
        border: 1px solid #93C5FD;
    }

    .payment-pending-online {
        background-color: #FEF3C7;
        color: #92400E;
        border: 1px solid #FCD34D;
    }

    .payment-cancelled {
        background-color: #FEE2E2;
        color: #991B1B;
        border: 1px solid #FCA5A5;
    }

    .payment-failed {
        background-color: #FEE2E2;
        color: #991B1B;
        border: 1px solid #FCA5A5;
    }

    .payment-refunded {
        background-color: #E0E7FF;
        color: #3730A3;
        border: 1px solid #A5B4FC;
    }

    /* Order Content */
    .order-content {
        display: grid;
        grid-template-columns: 1fr auto;
        gap: 10px;
        margin-bottom: 1.25rem;
    }

    .order-products {
        display: flex;
        /* gap: 1rem; */
        align-items: center;
    }

    .product-thumbnails {
        display: flex;
        gap: 0.75rem;
        align-items: center;
    }

    .product-thumbnail-wrap {
        width: 50px;
        height: 50px;
        min-width: 50px;
        min-height: 50px;
        flex-shrink: 0;
        border-radius: 8px;
        overflow: hidden;
        border: 2px solid #F3F4F6;
        transition: border-color 0.3s ease, transform 0.3s ease;
    }

    .product-thumbnail-wrap:hover {
        border-color: var(--color-primary);
        transform: scale(1.05);
    }

    .product-thumbnail-wrap picture,
    .product-thumbnail-wrap .product-thumbnail {
        width: 50px !important;
        height: 50px !important;
        max-width: 50px !important;
        max-height: 50px !important;
        border-radius: 0;
        border: none;
        display: block;
        overflow: hidden;
    }

    .product-thumbnail-wrap picture img,
    .product-thumbnail-wrap img.product-thumbnail {
        width: 100% !important;
        height: 100% !important;
        max-width: 50px !important;
        max-height: 50px !important;
        object-fit: cover;
        display: block;
    }

    .product-thumbnail-wrap .product-thumbnail:hover,
    .product-thumbnail-wrap picture:hover {
        transform: none;
    }

    .product-info {
        flex: 1;
    }

    .product-count {
        font-size: 0.9rem;
        color: #6B7280;
        margin-top: 0.25rem;
    }

     .order-summary {
        display: flex;
        align-items: center;
        gap: 1rem;
    }

    .order-total {
        /* font-size: 1.5rem; */
        font-weight: 700;
        color: var(--color-primary);
        /* margin-bottom: 0.5rem; */
    }

    .payment-method {
        display: flex;
        align-items: center;
        justify-content:center;
        gap: 0.5rem;
        color: #6B7280;
        font-size: 0.85rem;
        margin-bottom: 1rem;
    }

    /* Order Actions */
    .order-actions {
        display: flex;
        gap: 0.75rem;
        justify-content: center;
    }

    .btn-order-action {
        padding: 0.625rem 1.25rem;
        border-radius: 20px;
        font-weight: 600;
        font-size: 0.9rem;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }

    .btn-view-details {
        background-color: var(--color-primary);
        color: #FFFFFF;
        border: 1px solid var(--color-primary);
    }

    .btn-view-details:hover {
        background-color: var(--color-secondary);
        border-color: var(--color-secondary);
        color: #FFFFFF !important;
        transform: translateY(-1px);
    }

    .btn-reorder {
        background-color: #FFFFFF;
        color: var(--color-primary);
        border: 1px solid var(--color-primary);
    }

    .btn-reorder:hover {
        background-color: var(--color-primary);
        color: #FFFFFF;
        border-color: var(--color-primary);
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(17, 72, 67, 0.2);
    }

    .btn-retry-payment {
        background-color: #DC2626;
        color: #FFFFFF;
        border: 1px solid #DC2626;
        cursor: pointer;
    }

    .btn-retry-payment:hover {
        background-color: #B91C1C;
        border-color: #B91C1C;
        color: #FFFFFF !important;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(220, 38, 38, 0.2);
    }

    .btn-retry-payment:disabled {
        background-color: #9CA3AF;
        border-color: #9CA3AF;
        cursor: not-allowed;
        opacity: 0.6;
    }

    /* Filter Bar */
    .filter-bar {
        background: #FFFFFF;
        border: 1px solid #E5E7EB;
        border-radius: 12px;
        padding: 1.25rem;
        margin-bottom: 2rem;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
    }

    .filter-form {
        display: grid;
        grid-template-columns: 2fr 1.5fr 1.5fr auto;
        gap: 1rem;
        align-items: end;
    }

    .filter-group {
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
    }

    .filter-label {
        font-size: 0.85rem;
        font-weight: 600;
        color: #374151;
        margin: 0;
    }

    .filter-input,
    .filter-select {
        padding: 0.625rem 1rem;
        border: 1px solid #D1D5DB;
        border-radius: 8px;
        font-size: 0.9rem;
        transition: all 0.3s ease;
    }

    .filter-input:focus,
    .filter-select:focus {
        outline: none;
        border-color: var(--color-primary);
        box-shadow: 0 0 0 3px rgba(17, 72, 67, 0.1);
    }

    .btn-filter {
        padding: 0.625rem 1.5rem;
        background-color: var(--color-primary);
        color: #FFFFFF;
        border: none;
        border-radius: 8px;
        font-weight: 600;
        transition: all 0.3s ease;
        white-space: nowrap;
        cursor: pointer;
    }

    .btn-filter:hover {
        background-color: var(--color-secondary);
        border-color: var(--color-secondary);
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }

    .btn-clear {
        padding: 0.625rem 1rem;
        background-color: #F3F4F6;
        color: #374151;
        border: 1px solid #D1D5DB;
        border-radius: 8px;
        font-weight: 500;
        text-decoration: none;
        transition: all 0.3s ease;
        white-space: nowrap;
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
    }

    .btn-clear:hover {
        background-color: #E5E7EB;
        color: var(--color-primary);
        border-color: var(--color-primary);
        transform: translateY(-1px);
    }

    /* Empty State */
    .empty-state {
        text-align: center;
        padding: 4rem 2rem;
        background: #FFFFFF;
        border: 1px solid #E5E7EB;
        border-radius: 16px;
    }

    .empty-state-icon {
        font-size: 4rem;
        color: #D1D5DB;
        margin-bottom: 1rem;
    }

    .empty-state-title {
        font-size: 1.5rem;
        font-weight: 700;
        color: #374151;
        margin-bottom: 0.5rem;
    }

    .empty-state-text {
        color: #6B7280;
        margin-bottom: 1.5rem;
    }

    /* Page Header */
    .page-header {
        margin-bottom: 2rem;
    }

    .page-title {
        font-size: 2rem;
        font-weight: 700;
        color: var(--color-primary);
        margin-bottom: 0.5rem;
    }

    .page-subtitle {
        color: #6B7280;
        font-size: 0.95rem;
    }

    /* Responsive Design */
    @media (max-width: 991.98px) {
        .filter-form {
            grid-template-columns: 1fr;
        }

        .order-content {
         display: grid;
        grid-template-columns: 1fr;
        gap: 0px;
        margin-bottom: 1.25rem;
         width: 100%;
         }

        .order-id {
            font-size: 12px ;
            font-weight: 500;
            color: var(--color-primary);
            margin-bottom: 0rem;
        }

        /* .order-content {
            grid-template-columns: 1fr ;
        } */

        .order-summary {
           display: flex;
           flex-direction: column;
           align-items: flex-start !important;   
           text-align: left;
           gap: 0;
           width: 100%;
        }
          

        .order-actions {
            width: 100%;

            display: flex;
        flex-direction: column;
        align-items: stretch; 
        }

        .order-actions .btn-view-details {
            width: 100% !important;
            justify-content: center;
            text-align: center;
        }
         .payment-method {
        justify-content: flex-start;
        margin-bottom: 0;
    }

         .order-total {
        width: 100%;
        text-align: left;
        font-size: 1.25rem;
        font-size: 15px;
        margin-bottom: 10px;
    }

         .order-header {
        flex-direction: column;
        align-items: flex-start;
        width: 100%;
    }


        .order-badges{
            flex-direction: row;
            align-items: flex-start;
            width: 100%;
            margin-bottom: 5px;
        }

        

        .order-id-section{
             flex-direction: column;
            align-items: flex-start;
            width: 100%;
            border: none;
        }


        .status-badge {
            padding: 0.275rem 0.5rem;
            border-radius: 20px;
            font-size: 0.55rem;
            font-weight: 400;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .payment-badge {
            padding: 0.275rem 0.4rem;
            border-radius: 20px;
            font-size: 0.55rem;
            font-weight: 400;
        }
    }

    @media (max-width: 575.98px) {
        .order-card {
            padding: 1rem;
        }

        .order-content {
            /* grid-template-columns: 1fr; */
            width: 100%;
        }
        .product-count {
           text-align: start;
           margin-bottom: 5px;
        }

        .order-products {
            flex-direction: column;
            align-items: center;
        }

        .product-thumbnails {
            width: 100%;
        }

        .page-title {
            font-size: 1.5rem;
        }

        .filter-bar {
            padding: 1rem;
        }
        .product-info{
            padding: 0.4rem;
        }
    }

    /* Pagination Styles */
    .pagination {
        display: flex;
        justify-content: center;
        align-items: center;
        gap: 0.5rem;
        margin: 2rem 0;
        padding: 0;
        list-style: none;
        flex-wrap: wrap;
    }

    .pagination .page-item {
        margin: 0;
    }

    .pagination .page-link {
        min-width: 44px;
        height: 44px;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0.5rem 1rem;
        margin: 0;
        color: var(--color-primary);
        background: #FFFFFF;
        border: 2px solid #E5E7EB;
        border-radius: 10px;
        font-weight: 600;
        font-size: 0.9rem;
        text-decoration: none;
        transition: all 0.3s ease;
        cursor: pointer;
    }

    .pagination .page-link:hover:not(.disabled) {
        background: var(--color-primary);
        color: #FFFFFF;
        border-color: var(--color-primary);
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(17, 72, 67, 0.2);
    }

    .pagination .page-link:focus {
        outline: none;
        box-shadow: 0 0 0 3px rgba(17, 72, 67, 0.15);
    }

    .pagination .page-item.active .page-link {
        background: var(--color-primary);
        color: #FFFFFF;
        border-color: var(--color-primary);
        box-shadow: 0 4px 12px rgba(17, 72, 67, 0.25);
        cursor: default;
    }

    .pagination .page-item.active .page-link:hover {
        transform: none;
        box-shadow: 0 4px 12px rgba(17, 72, 67, 0.25);
    }

    .pagination .page-item.disabled .page-link {
        color: #CBD5E0;
        background: #F7FAFC;
        border-color: #E2E8F0;
        cursor: not-allowed;
        opacity: 0.6;
    }

    .pagination .page-item.disabled .page-link:hover {
        background: #F7FAFC;
        color: #CBD5E0;
        transform: none;
        box-shadow: none;
    }

    /* Pagination Icons - Style Bootstrap Icons */
    .pagination .page-link i {
        font-size: 1rem;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        line-height: 1;
    }

    .pagination .page-link[rel="prev"],
    .pagination .page-link[rel="next"],
    .pagination .page-item.disabled .page-link[aria-hidden="true"] {
        display: flex;
        align-items: center;
        justify-content: center;
    }

    /* Make arrows more visible and styled on hover */
    .pagination .page-link[rel="prev"]:hover:not(.disabled),
    .pagination .page-link[rel="next"]:hover:not(.disabled) {
        transform: translateY(-2px) scale(1.1);
    }

    .pagination .page-link[rel="prev"]:hover:not(.disabled) i,
    .pagination .page-link[rel="next"]:hover:not(.disabled) i {
        transform: scale(1.2);
    }

    /* Pagination Info Text */
    .pagination-info {
        text-align: center;
        margin-top: 1rem;
        padding: 1rem;
        background: #F8F9FA;
        border-radius: 10px;
        color: #4A5568;
        font-size: 0.9rem;
        font-weight: 500;
    }

    .pagination-info strong {
        color: var(--color-primary);
        font-weight: 700;
    }

    /* Responsive Pagination */
    @media (max-width: 768px) {
        .pagination {
            gap: 0.25rem;
        }
        
        .pagination .page-link {
            min-width: 40px;
            height: 40px;
            padding: 0.375rem 0.75rem;
            font-size: 0.85rem;
        }
    }


   

</style>
@endpush

@section('content')
<div class="container">
    <!-- Page Header -->
    <div class="mt-4">
        <h1 class="page-title">My Orders</h1>
        <p class="page-subtitle">Track and manage all your orders in one place</p>
    </div>

    <!-- Filter Bar -->
    <div class="filter-bar">
        <form method="GET" action="{{ route('customer.orders.index') }}" class="filter-form">
            <div class="filter-group">
                <label class="filter-label">
                    <i class="bi bi-search"></i> Search by Order ID
                </label>
                <input 
                    type="text" 
                    name="search" 
                    class="filter-input" 
                    placeholder="Enter Order ID..."
                    value="{{ request('search') }}"
                >
            </div>

            <div class="filter-group">
                <label class="filter-label">
                    <i class="bi bi-funnel"></i> Filter by Status
                </label>
                <select name="status" class="filter-select">
                    <option value="">All Statuses</option>
                    @foreach($statusOptions as $value => $label)
                        <option value="{{ $value }}" {{ request('status') === $value ? 'selected' : '' }}>
                            {{ $label }}
                        </option>
                    @endforeach
                </select>
            </div>

            <div class="filter-group">
                <label class="filter-label">
                    <i class="bi bi-calendar"></i> Sort by Date
                </label>
                <select name="sort" class="filter-select">
                    <option value="newest" {{ request('sort', 'newest') === 'newest' ? 'selected' : '' }}>
                        Newest First
                    </option>
                    <option value="oldest" {{ request('sort') === 'oldest' ? 'selected' : '' }}>
                        Oldest First
                    </option>
                </select>
            </div>

            <div class="filter-group">
                <button type="submit" class="btn-filter">
                    <i class="bi bi-funnel-fill"></i> Apply Filters
                </button>
                @if(request()->hasAny(['search', 'status', 'sort']))
                    <a href="{{ route('customer.orders.index') }}" class="btn-clear mt-2">
                        <i class="bi bi-x-circle"></i> Clear
                    </a>
                @endif
            </div>
        </form>
    </div>

    <!-- Orders List -->
    @forelse($orders as $order)
        <div class="order-card">
            <!-- Order Header -->
            <div class="order-header">
                <div class="order-id-section">
                    <div class="order-id">Order #{{ $order->id }}
                        <div class="order-date">
                            <i class="bi bi-calendar3"></i>
                            <span>{{ $order->placed_at ? $order->placed_at->format('M d, Y') : $order->created_at->format('M d, Y') }}</span>
                        </div>
                    </div>
                    <div class="vr mx-3 d-none d-lg-block"></div>

                  <div class="order-products">
                    <!-- Product Thumbnails (max 3) -->
                    <div class="product-thumbnails">
                        @php $orderThumbOnerror = "this.onerror=null;this.style.display='none'"; @endphp
                        @foreach($order->items->take(3) as $item)
                            @if($item->product && ($item->product->image_path || $item->product->image))
                                <div class="product-thumbnail-wrap">
                                    <x-product-image :product="$item->product" context="listing" class="product-thumbnail" alt="{{ $item->name }}" title="{{ $item->name }}" :onerror="$orderThumbOnerror" />
                                </div>
                            @else
                                <div class="product-thumbnail-wrap product-thumbnail d-flex align-items-center justify-content-center bg-light">
                                    <i class="bi bi-image text-muted"></i>
                                </div>
                            @endif
                        @endforeach
                    </div>
                    <div class="product-info">
                        <div class="fw-bold">
                            @php
                                $firstItem = $order->items->first();
                            @endphp
                            @if($firstItem)
                                @if($order->items->count() === 1)
                                    {{ $firstItem->name }}
                                @else
                                    {{ $firstItem->name }}
                                    @if($order->items->count() > 1)
                                        <span class="text-muted">+ {{ $order->items->count() - 1 }} more item(s)</span>
                                    @endif
                                @endif
                            @else
                                <span class="text-muted">No items found</span>
                            @endif
                        </div>
                        <div class="product-count">
                            <i class="bi bi-box"></i> {{ $order->items->sum('qty') }} item(s) total
                        </div>
                    </div>
                  </div>
                </div>
              <div class="order-content">
                <div class="order-badges">
                    <span class="status-badge status-{{ $order->status }}">
                        {{ ucfirst($order->status_label) }}
                    </span>
                </div>

                <div class="order-summary">                       
                    <div class="order-actions">
                        <a href="{{ route('customer.orders.show', $order->id) }}" class="btn-order-action btn-view-details">
                            <i class="bi bi-eye"></i> View
                        </a>
                        @php
                            $canRetryPayment = $order->payment_status === 'failed' 
                                && $order->payment_method === 'online' 
                                && $order->items->count() > 0 && $order->status == 'awaiting_payment';
                        @endphp
                        @if($canRetryPayment)
                            <button type="button" class="btn-order-action btn-retry-payment" data-order-id="{{ $order->id }}">
                                <i class="bi bi-credit-card"></i> Retry Payment
                            </button>
                        @endif
                        @if($order->status === 'delivered')
                            <!-- <a href="{{ route('customer.orders.show', $order->id) }}" class="btn-order-action btn-reorder">
                                <i class="bi bi-arrow-repeat"></i> Reorder
                            </a> -->
                        @endif
                    </div>
                </div>
              </div>
            </div>
        </div>
    @empty
        <div class="empty-state">
            <div class="empty-state-icon">
                <i class="bi bi-inbox"></i>
            </div>
            <h2 class="empty-state-title">No Orders Found</h2>
            <p class="empty-state-text">
                @if(request()->hasAny(['search', 'status', 'sort']))
                    No orders match your current filters. Try adjusting your search criteria.
                @else
                    You haven't placed any orders yet. Start shopping to see your orders here!
                @endif
            </p>
            <a href="{{ route('home') }}" class="btn btn-primary" style="background-color: var(--color-primary); border-color: var(--color-primary);">
                <i class="bi bi-cart"></i> Start Shopping
            </a>
        </div>
    @endforelse

    <!-- Pagination -->
    @if($orders->hasPages())
        <div class="d-flex justify-content-center mt-4">
            {{ $orders->links('vendor.pagination.bootstrap-5-custom') }}
        </div>
    @endif
</div>

@push('scripts')
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle retry payment button clicks
    document.querySelectorAll('.btn-retry-payment').forEach(function(button) {
        button.addEventListener('click', function() {
            const orderId = this.getAttribute('data-order-id');
            const originalText = this.innerHTML;
            
            // Disable button and show loading state
            this.disabled = true;
            this.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Processing...';
            
            // Call retry payment endpoint
            fetch('/customer/orders/' + orderId + '/retry-payment', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json'
                }
            })
            .then(res => {
                if (!res.ok) {
                    return res.json().then(err => {
                        throw new Error(err.error || 'Failed to initiate payment retry');
                    });
                }
                return res.json();
            })
            .then(data => {
                if (data.error) {
                    alert(data.error);
                    button.disabled = false;
                    button.innerHTML = originalText;
                    return;
                }

                if (data.recovered && data.redirect) {
                    alert(data.message || 'Payment was already successful. Your order is confirmed.');
                    window.location.href = data.redirect;
                    return;
                }
                
                // Initialize Razorpay payment
                const options = {
                    key: data.key,
                    amount: data.amount,
                    currency: data.currency,
                    name: '{{ \App\Models\Setting::get("site_name", "KiyoKart") }}',
                    description: 'Order Payment Retry',
                    order_id: data.razorpay_order_id,
                    handler: function(response) {
                        const verifyUrl = '{{ route("checkout.razorpay.verify") }}';
                        const csrfToken = '{{ csrf_token() }}';
                        let attempts = 0;
                        const maxAttempts = 3;
                        function doVerify() {
                            attempts++;
                            const verifyPayload = {
                                razorpay_order_id: response.razorpay_order_id,
                                razorpay_payment_id: response.razorpay_payment_id,
                                razorpay_signature: response.razorpay_signature
                            };
                            return fetch(verifyUrl, {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json',
                                    'X-CSRF-TOKEN': csrfToken,
                                    'Accept': 'application/json'
                                },
                                body: JSON.stringify(verifyPayload)
                            }).then(function(res) {
                                return res.json().then(function(result) {
                                    if (!res.ok) return Promise.reject(new Error(result.error || 'Verification failed'));
                                    return result;
                                });
                            });
                        }
                        function runVerify() {
                            doVerify()
                                .then(function(result) {
                                    if (result.success) {
                                        window.location.href = result.redirect || '/customer/orders/' + orderId;
                                    } else {
                                        alert(result.error || 'Payment verification failed');
                                        button.disabled = false;
                                        button.innerHTML = originalText;
                                    }
                                })
                                .catch(function(err) {
                                    if (attempts < maxAttempts) {
                                        setTimeout(runVerify, 1500);
                                    } else {
                                        console.error('Payment verification error:', err);
                                        alert('Payment verification failed. Please try again or contact support if the amount was deducted.');
                                        button.disabled = false;
                                        button.innerHTML = originalText;
                                    }
                                });
                        }
                        runVerify();
                    },
                    prefill: {
                        name: '{{ auth()->user()->name }}',
                        email: '{{ auth()->user()->email }}',
                        contact: '{{ auth()->user()->mobile }}'
                    },
                    theme: { color: '#13233c' },
                    modal: {
                        ondismiss: function() {
                            // Re-enable button if user closes payment modal
                            button.disabled = false;
                            button.innerHTML = originalText;
                        }
                    }
                };
                
                const rzp = new Razorpay(options);
                rzp.open();
            })
            .catch(err => {
                console.error('Retry payment error:', err);
                alert(err.message || 'Failed to initiate payment retry. Please try again.');
                button.disabled = false;
                button.innerHTML = originalText;
            });
        });
    });
});
</script>
@endpush
@endsection
