@extends('admin.layouts.default')
@section('page_title', 'Card Requests' . config('default.page_title_delimiter') . config('default.app_name'))

@section('content')
<div class="w-full max-w-7xl mx-auto px-4 md:px-6 py-6 md:py-8" 
     x-data="{ 
        selectAll: false, 
        selectedCount: 0,
        showMailModal: false,
        showReviewModal: false,
        selectedMemberName: '',
        selectedId: null,
        paymentMethod: '',
        updateCount() {
            this.selectedCount = document.querySelectorAll('.item-checkbox:checked').length;
        }
     }"
	 x-effect="showReviewModal ? document.body.classList.add('overflow-hidden') : document.body.classList.remove('overflow-hidden')"
	 >

    <div class="mb-8 flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between">
        <div class="flex items-center gap-3">
            <div class="p-2.5 bg-primary-50 dark:bg-primary-500/10 rounded-xl text-primary-600 shadow-sm">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="w-6 h-6"><polyline points="22 12 16 12 14 15 10 15 8 12 2 12"></polyline><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"></path></svg>
            </div>
            <div>
                <h1 class="text-2xl md:text-3xl font-bold text-secondary-900 dark:text-white tracking-tight">Requests Center</h1>
                <div class="flex items-center gap-2 mt-1">
                    <span class="inline-flex px-2 py-0.5 rounded-md bg-secondary-100 dark:bg-secondary-800 text-[11px] font-medium text-secondary-500">
                        {{ $items->total() }} results found
                    </span>
                </div>
            </div>
        </div>

        <div class="lg:w-96">
            <form action="{{ url()->current() }}" method="GET" class="relative group">
                <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-secondary-400 group-focus-within:text-primary-500 transition-colors"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>
                </div>
                <input type="search" name="search" value="{{ request('search') }}"
                       class="w-full bg-white dark:bg-secondary-800 border border-secondary-200 dark:border-secondary-700 rounded-2xl pl-11 pr-4 py-3 text-sm shadow-sm outline-none focus:ring-1 focus:ring-primary-500/10 focus:border-primary-500 transition-all placeholder:text-secondary-400"
                       placeholder="Search...">
            </form>
        </div>
    </div>

    <div class="bg-white dark:bg-secondary-900 border border-secondary-200 dark:border-secondary-800 rounded-3xl shadow-sm overflow-hidden">
        <div class="overflow-x-auto text-secondary-900 dark:text-white">
            <table class="w-full text-sm text-left">
                <thead class="bg-secondary-50/30 dark:bg-secondary-800/20 text-[11px] text-secondary-400 uppercase font-bold tracking-wider border-b border-secondary-100 dark:border-secondary-800">
                    <tr class="h-16">
                        <th class="px-6 w-4">
                            <input type="checkbox" x-model="selectAll" 
                                   @change="document.querySelectorAll('.item-checkbox').forEach(cb => cb.checked = selectAll); updateCount()"
                                   class="w-4 h-4 rounded border-secondary-300 text-primary-600 focus:ring-primary-500 cursor-pointer">
                        </th>
                        <th class="px-4">Member Info</th>
                        <th class="px-4 text-center">Card Type</th>
                        <th class="px-4 text-center">Status</th>
                        <th class="px-4 text-center">Date</th>
                        <th class="px-6 text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-secondary-50 dark:divide-secondary-800/50">
                    @forelse($items as $item)
                    <tr class="h-20 hover:bg-secondary-50/30 dark:hover:bg-secondary-800/30 transition-colors">
                        <td class="px-6">
                            <input type="checkbox" name="id[]" value="{{ $item->id }}" 
                                   @change="updateCount()"
                                   class="item-checkbox w-4 h-4 rounded border-secondary-300 text-primary-600 focus:ring-primary-500">
                        </td>
                        <td class="px-4">
                            <div class="flex flex-col">
                                <span class="text-secondary-900 dark:text-white font-bold">{{ $item->member_name }}</span>
                                <span class="text-[11px] text-secondary-400 font-medium">{{ $item->member_email }}</span>
                            </div>
                        </td>
                        <td class="px-4 text-center text-secondary-600 dark:text-secondary-300 font-medium">{{ $item->name }}</td>
                        
                        <td class="px-4 text-center">
                            @if($item->is_active == 0)
                                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[10px] font-bold bg-amber-50 dark:bg-amber-500/10 text-amber-600 dark:text-amber-400 border border-amber-100 dark:border-amber-500/20 uppercase tracking-wider">
                                    <span class="w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse"></span>
                                    Pending
                                </span>
                            @elseif($item->is_active == 2)
                                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[10px] font-bold bg-blue-50 dark:bg-blue-500/10 text-blue-600 dark:text-blue-400 border border-blue-100 dark:border-blue-500/20 uppercase tracking-wider">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/></svg>
                                    Review
                                </span>
                            @else
                                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[10px] font-bold bg-emerald-50 dark:bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border border-emerald-100 dark:border-emerald-500/20 uppercase tracking-wider">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>
                                    Approved
                                </span>
                            @endif
                        </td>

                        <td class="px-4 text-center">
                            <div class="text-secondary-600 dark:text-secondary-300 font-medium">{{ $item->created_at->format('M d, Y') }}</div>
                            <div class="text-[10px] text-secondary-400 mt-1 uppercase">{{ $item->created_at->format('h:i A') }}</div>
                        </td>

                        <td class="px-6 text-right">
                            <div class="flex justify-end gap-1">
                                @if($item->is_active == 2)
                                <button type="button" @click="showReviewModal = true; openActivationModal('{{ $item->id }}')" 
                                        class="p-2 text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-500/10 rounded-xl transition-all cursor-pointer">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>
                                </button>
                                @endif

                                <button type="button" @click="selectedMemberName = '{{ $item->member_name }}'; selectedId = '{{ $item->id }}'; showMailModal = true"
                                        class="p-2 text-secondary-400 hover:text-emerald-600 hover:bg-emerald-50 dark:hover:bg-emerald-500/10 rounded-xl transition-all cursor-pointer">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
                                </button>

                                

                                <button type="button" @click="handleAjaxAction('delete', '{{ $item->id }}')"
                                        class="p-2 text-secondary-400 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-500/10 rounded-xl transition-all">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>
                                </button>
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr><td colspan="6" class="py-24 text-center text-secondary-300 italic">No results found</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <div class="p-6 bg-secondary-50/30 dark:bg-secondary-800/10 border-t border-secondary-50 dark:border-secondary-800 flex flex-col md:flex-row justify-between items-center gap-4">
            <div class="flex items-center gap-3 w-full md:w-auto">
                <div class="relative group min-w-[220px]">
                    <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none z-3 text-secondary-400 group-focus-within:text-primary-500">
                        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 11 3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>
                    </div>
                    <select id="table-with-selected" :disabled="selectedCount === 0"
                            class="appearance-none w-full bg-white dark:bg-secondary-800 border border-secondary-200 dark:border-secondary-700 text-secondary-700 dark:text-secondary-300 text-sm rounded-2xl pl-11 pr-10 py-3 shadow-sm outline-none focus:border-primary-500 disabled:opacity-50 transition-all cursor-pointer">
                        <option value="">With selected...</option>
                        <option value="approve">Approve Selection</option>
                        <option value="delete">Delete Selection</option>
                    </select>
                </div>
                <button type="button" @click="handleApply()" x-show="selectedCount > 0" class="text-sm font-bold text-primary-600 px-2">Apply</button>
            </div>
            <div>{{ $items->links() }}</div>
        </div>
    </div>

    {{-- Review Modal (Alpine Only) --}}
    <div x-show="showReviewModal" x-transition class="fixed inset-0 z-[9999] w-screen h-screen overflow-hidden flex items-center justify-center"" x-cloak>
        <div class="flex items-center justify-center min-h-screen px-4">
            <div class="fixed inset-0 bg-secondary-900/60 backdrop-blur-sm" @click="showReviewModal = false"></div>

            <div class="bg-white dark:bg-secondary-900 rounded-3xl max-w-4xl w-full p-8 shadow-2xl relative z-10  dark:border-secondary-800">
                <div class="flex justify-between items-center mb-6 border-b dark:border-secondary-800 pb-4">
                    <h5 class="font-bold text-secondary-900 dark:text-white">Review Payment Proof</h5>
                    <button type="button" @click="showReviewModal = false" class="text-secondary-400 text-2xl">&times;</button>
                </div>

                <form id="activationForm" method="POST" action="{{ route('admin.cards.activate') }}">
                    @csrf
                    <input type="hidden" name="request_id" id="modal_request_id">
                    
                    

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-8 text-left">
                        <div class="bg-secondary-50 dark:bg-secondary-800 rounded-2xl p-4  dark:border-secondary-700">
                            <label class="text-[10px] font-black text-blue-500 uppercase mb-3 block tracking-widest">Payment Screenshot</label>
                            <img src="" id="proof_img" class="rounded-xl w-full object-contain max-h-64 shadow-sm bg-white mb-4">
                            <div class="text-xs space-y-2 text-secondary-500">
                                <p>Transaction: <span id="proof_ref" class="text-secondary-900 dark:text-white font-bold"></span></p>
                                <p>Amount: <span id="proof_amount" class="text-emerald-600 font-black text-base"></span> <span id="card_currency" class="text-emerald-600"></span></p>
                                <p>Notes: <span id="member_notes"></span> </p>
                            </div>
                        </div>

                        <div class="space-y-5">
						<div class="mb-6 p-4 bg-secondary-50 dark:bg-secondary-800/50 rounded-2xl">
                        <h6 class="text-primary-600 font-bold mb-3 text-xs uppercase tracking-widest">Customer Details</h6>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                            <p class="text-secondary-500">Name: <span id="customer_name" class="text-secondary-900 dark:text-white font-bold">---</span></p>
                            <p class="text-secondary-500">Email: <span id="customer_email" class="text-secondary-900 dark:text-white font-bold">---</span></p>
                            <p class="text-secondary-500">Card Type: <span id="cust_card_type" class="px-2 py-0.5 bg-blue-100 text-blue-600 rounded-md font-bold text-xs">---</span></p>
                        </div>
                    </div>
                            <label class="text-[10px] font-black text-emerald-500 uppercase tracking-widest block">Activation Data</label>
                            
                            <div class="grid grid-cols-2 gap-4">
                                <div>
                                    <label class="text-xs font-bold mb-1 block text-secondary-700 dark:text-secondary-300">Start Date</label>
                                    <input type="date" name="start_date" class="w-full bg-white dark:bg-secondary-800 border border-secondary-200 dark:border-secondary-700 rounded-xl p-3 text-xs outline-none" value="{{ date('Y-m-d') }}" required>
                                </div>
                                <div>
                                    <label class="text-xs font-bold mb-1 block text-secondary-700 dark:text-secondary-300">Expiry Date</label>
                                    <input type="date" name="expiry_date" class="w-full bg-white dark:bg-secondary-800 border border-secondary-200 dark:border-secondary-700 rounded-xl p-3 text-xs outline-none" value="{{ date('Y-m-d', strtotime('+1 year')) }}" required>
                                </div>
                            </div>
                            <button type="submit" class="w-full bg-emerald-600 hover:bg-emerald-700 py-4 rounded-2xl text-white font-black text-sm shadow-lg shadow-emerald-500/20 transition-all uppercase mt-2">Activate Card Now</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    {{-- Mail Modal --}}
    <div x-show="showMailModal" x-transition class="fixed inset-0 z-[999] overflow-y-auto" style="display: none;" x-cloak>
        <div class="flex items-center justify-center min-h-screen px-4 text-center">
            <div class="fixed inset-0 bg-secondary-900/60 backdrop-blur-sm" @click="showMailModal = false"></div>
            <div class="bg-white dark:bg-secondary-900 rounded-3xl max-w-md w-full p-8 shadow-2xl relative z-10 border border-secondary-100 dark:border-secondary-800">
                <div class="w-16 h-16 bg-blue-50 dark:bg-blue-500/10 rounded-2xl flex items-center justify-center mx-auto mb-4 text-blue-600">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                    </svg>
                </div>
                <h3 class="text-xl font-bold text-secondary-900 dark:text-white mb-2 tracking-tight">Send Instructions</h3>
                <p class="text-sm text-secondary-500 mb-6 leading-relaxed">Send activation steps to <span class="font-bold text-secondary-900 dark:text-secondary-200" x-text="selectedMemberName"></span>?</p>
                
                <div class="mt-6 space-y-4 text-left mb-8">
                    
                    <div>
                        <label class="block text-[10px] font-black text-secondary-500 uppercase tracking-widest mb-1">Payment Method</label>
                        <div class="relative">
                            <select x-model="paymentMethod" name="payment"
                                    class="appearance-none w-full bg-secondary-50 dark:bg-secondary-800 border-none rounded-xl p-3 text-sm focus:ring-2 focus:ring-blue-500 transition-all outline-none text-secondary-900 dark:text-white cursor-pointer" required>
                                
                                <option></option>
                                <option value="bank_transfer" >Bank Transfer</option>
                                
                            </select>
                            <div class="absolute inset-y-0 right-0 pr-4 flex items-center pointer-events-none text-secondary-400">
                                <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex gap-3">
                    <button @click="showMailModal = false" class="flex-1 px-4 py-3 rounded-xl bg-secondary-100 dark:bg-secondary-800 text-secondary-600 dark:text-secondary-400 font-bold hover:bg-secondary-200 transition-all">Cancel</button>
                    <button @click="handleAjaxAction('mail', selectedId, paymentMethod); showMailModal = false" :disabled="!paymentMethod" class="flex-1 px-4 py-3 rounded-xl bg-blue-600 text-white font-bold hover:bg-blue-700 shadow-lg shadow-blue-500/30 transition-all">Confirm & Send</button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function openActivationModal(id) {
    const input = document.getElementById('modal_request_id');
    if (input) input.value = id;

    const locale = window.location.pathname.split('/')[1] || 'en-us';
    const url = `/${locale}/admin/payment-proof/${id}`;

    fetch(url, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        }
    })
    .then(response => {
        if (!response.ok) throw new Error('Network response was not ok');
        return response.json();
    })
    .then(res => {
        if (res.success) {
            document.getElementById('customer_name').innerText = res.proof.customer_name;
            document.getElementById('customer_email').innerText = res.proof.customer_email;
            document.getElementById('cust_card_type').innerText = res.proof.card_type_name || 'Standard';
            document.getElementById('proof_img').src = res.proof.receipt_path;
            document.getElementById('proof_ref').innerText = res.proof.transaction_number;
            document.getElementById('proof_amount').innerText = res.proof.amount_paid;
            document.getElementById('member_notes').innerText = res.proof.member_notes;
            document.getElementById('card_currency').innerText = res.proof.card_currency;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Could not load payment proof.');
    });
}

function handleAjaxAction(type, id = null, payment = null) {
    const spinner = document.getElementById('global-spinner');
    if(spinner) spinner.classList.remove('hidden');
    
    let ids = id ? [id] : Array.from(document.querySelectorAll('.item-checkbox:checked')).map(el => el.value);
    if(!ids.length) {
        if(spinner) spinner.classList.add('hidden');
        return;
    }
    
    appConfirm('Confirm', 'Are you sure?', {
        'btnConfirm': {
            'click': function() {
                fetch('{{ route("admin.requests.action") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    },
                    body: JSON.stringify({ 
                        ids: ids, 
                        action: type,
                        payment: payment
                    })
                })
                .then(response => response.json())
                .then(data => {
                    location.reload();
                });
            }
        },
        'btnCancel': {
            'click': function() {
                if(spinner) spinner.classList.add('hidden');
            }
        }
    });
}

function handleApply() {
    const act = document.getElementById('table-with-selected').value;
    if(act) handleAjaxAction(act);
}
</script>
@endsection