@extends('layouts.admin')

@section('title', 'Payment Methods')

@section('content')
<div class="min-h-screen bg-slate-50">
    <div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">

        {{-- Toast --}}
        @if(session('success') || session('error'))
            <script>
                Swal.fire({
                    icon: '{{ session("success") ? "success" : "error" }}',
                    title: '{{ session("success") ? "Success!" : "Oops!" }}',
                    text: @json(session('success') ?? session('error')),
                    toast: true,
                    position: 'top-end',
                    timer: 2500,
                    showConfirmButton: false
                });
            </script>
        @endif

        {{-- Header --}}
        <div class="mb-6 flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
            <div>
                <h1 class="text-2xl font-bold text-slate-800 md:text-3xl">Payment Methods</h1>
                <p class="mt-1 text-sm text-slate-500">
                    ইউজারদের সাবস্ক্রিপশন পেমেন্ট নেওয়ার সব মেথড এখানে ম্যানেজ করুন।
                </p>
            </div>

            <a href="{{ route('payment-methods.create') }}"
               class="inline-flex items-center justify-center rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white shadow-sm transition hover:bg-blue-700 hover:shadow-lg">
                <span class="mr-2 text-base">+</span>
                Add Method
            </a>
        </div>

        {{-- Card --}}
        <div class="overflow-hidden rounded-3xl border border-slate-200 bg-white shadow-sm">

            <div class="border-b border-slate-200 px-6 py-4">
                <div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
                    <div>
                        <h2 class="text-lg font-bold text-slate-800">Payment Method List</h2>
                        <p class="text-sm text-slate-500">সব active এবং inactive payment method এর তালিকা</p>
                    </div>

                    <div class="rounded-2xl bg-slate-100 px-4 py-2 text-sm font-medium text-slate-600">
                        Total: {{ $methods->total() }}
                    </div>
                </div>
            </div>

            @if($methods->count() > 0)
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-slate-200">
                        <thead class="bg-slate-50">
                            <tr>
                                <th class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider text-slate-500">ID</th>
                                <th class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider text-slate-500">Method</th>
                                <th class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider text-slate-500">Number</th>
                                <th class="px-6 py-4 text-left text-xs font-bold uppercase tracking-wider text-slate-500">Status</th>
                                <th class="px-6 py-4 text-right text-xs font-bold uppercase tracking-wider text-slate-500">Actions</th>
                            </tr>
                        </thead>

                        <tbody class="divide-y divide-slate-100 bg-white">
                            @foreach($methods as $method)
                                @php
                                    $photoUrl = !empty($method->photo) ? asset($method->photo) : null;
                                @endphp

                                <tr class="transition hover:bg-slate-50/80">
                                    <td class="px-6 py-4 text-sm font-semibold text-slate-700">
                                        #{{ $method->id }}
                                    </td>

                                    <td class="px-6 py-4">
                                        <div class="flex items-center gap-3">
                                            @if($photoUrl)
                                                <img src="{{ $photoUrl }}"
                                                     alt="{{ $method->name }}"
                                                     class="h-12 w-12 rounded-xl border border-slate-200 object-cover">
                                            @else
                                                <div class="flex h-12 w-12 items-center justify-center rounded-xl bg-slate-100 text-lg">
                                                    💳
                                                </div>
                                            @endif

                                            <div>
                                                <div class="font-semibold text-slate-800">{{ $method->name }}</div>
                                                <div class="mt-1 text-xs text-slate-400">Payment gateway / method</div>
                                            </div>
                                        </div>
                                    </td>

                                    <td class="px-6 py-4 text-sm font-medium text-slate-700">
                                        {{ $method->number }}
                                    </td>

                                    <td class="px-6 py-4">
                                        <span id="method-status-badge-{{ $method->id }}"
                                              class="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold {{ $method->status === 'active' ? 'bg-emerald-100 text-emerald-700' : 'bg-rose-100 text-rose-700' }}">
                                            {{ $method->status === 'active' ? 'Active' : 'Inactive' }}
                                        </span>
                                    </td>

                                    <td class="px-6 py-4">
                                        <div class="flex flex-wrap items-center justify-end gap-2">
                                            <a href="{{ route('payment-methods.edit', $method) }}"
                                               class="inline-flex items-center rounded-xl bg-amber-100 px-3 py-2 text-xs font-semibold text-amber-700 transition hover:bg-amber-200">
                                                ✏ Edit
                                            </a>

                                            <form action="{{ route('payment-methods.toggle', $method) }}"
                                                  method="POST"
                                                  class="inline toggle-method-form"
                                                  data-method-id="{{ $method->id }}">
                                                @csrf
                                                @method('PATCH')
                                                <input type="hidden" name="ajax" value="1">

                                                <button type="submit"
                                                    class="toggle-method-btn inline-flex items-center rounded-xl px-3 py-2 text-xs font-semibold transition {{ $method->status === 'active' ? 'bg-slate-200 text-slate-700 hover:bg-slate-300' : 'bg-emerald-100 text-emerald-700 hover:bg-emerald-200' }}">
                                                    {{ $method->status === 'active' ? 'Deactivate' : 'Activate' }}
                                                </button>
                                            </form>

                                            <form action="{{ route('payment-methods.destroy', $method) }}"
                                                  method="POST"
                                                  class="inline delete-method-form"
                                                  data-method-name="{{ $method->name }}">
                                                @csrf
                                                @method('DELETE')

                                                <button type="submit"
                                                    class="inline-flex items-center rounded-xl bg-rose-100 px-3 py-2 text-xs font-semibold text-rose-700 transition hover:bg-rose-200">
                                                    🗑 Delete
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                <div class="border-t border-slate-200 px-6 py-4">
                    {{ $methods->links() }}
                </div>
            @else
                <div class="px-6 py-16 text-center">
                    <div class="mx-auto flex h-16 w-16 items-center justify-center rounded-2xl bg-slate-100 text-3xl">
                        💳
                    </div>
                    <h3 class="mt-4 text-lg font-bold text-slate-800">No Payment Methods Found</h3>
                    <p class="mt-2 text-sm text-slate-500">
                        এখনো কোনো payment method যোগ করা হয়নি।
                    </p>
                    <div class="mt-6">
                        <a href="{{ route('payment-methods.create') }}"
                           class="inline-flex items-center rounded-2xl bg-blue-600 px-5 py-3 text-sm font-semibold text-white shadow-sm transition hover:bg-blue-700">
                            Add Your First Method
                        </a>
                    </div>
                </div>
            @endif
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function () {
    const deleteForms = document.querySelectorAll('.delete-method-form');

    deleteForms.forEach(form => {
        form.addEventListener('submit', function (e) {
            e.preventDefault();

            const methodName = this.dataset.methodName || 'this payment method';

            Swal.fire({
                title: 'Delete Payment Method?',
                text: `Are you sure you want to delete "${methodName}"?`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#64748b',
                confirmButtonText: 'Yes, delete it',
                cancelButtonText: 'Cancel',
                reverseButtons: true,
            }).then((result) => {
                if (result.isConfirmed) {
                    this.submit();
                }
            });
        });
    });

    const toggleForms = document.querySelectorAll('.toggle-method-form');

    toggleForms.forEach(form => {
        form.addEventListener('submit', async function (e) {
            e.preventDefault();

            const button = this.querySelector('.toggle-method-btn');
            const methodId = this.dataset.methodId;
            const formData = new FormData(this);
            const originalText = button.innerHTML;

            button.disabled = true;
            button.innerHTML = 'Updating...';

            try {
                const response = await fetch(this.action, {
                    method: 'POST',
                    headers: {
                        'X-Requested-With': 'XMLHttpRequest',
                        'Accept': 'application/json',
                    },
                    body: formData
                });

                const contentType = response.headers.get('content-type') || '';

                if (!response.ok) {
                    throw new Error('Request failed with status ' + response.status);
                }

                if (!contentType.includes('application/json')) {
                    const text = await response.text();
                    console.error('Non-JSON response:', text);
                    throw new Error('Server did not return JSON');
                }

                const data = await response.json();

                if (!data.success) {
                    throw new Error('Invalid response data');
                }

                const badge = document.getElementById(`method-status-badge-${methodId}`);

                if (badge) {
                    badge.textContent = data.status_text;

                    if (data.status) {
                        badge.className = 'inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold bg-emerald-100 text-emerald-700';
                        button.className = 'toggle-method-btn inline-flex items-center rounded-xl px-3 py-2 text-xs font-semibold transition bg-slate-200 text-slate-700 hover:bg-slate-300';
                        button.innerHTML = 'Deactivate';
                    } else {
                        badge.className = 'inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold bg-rose-100 text-rose-700';
                        button.className = 'toggle-method-btn inline-flex items-center rounded-xl px-3 py-2 text-xs font-semibold transition bg-emerald-100 text-emerald-700 hover:bg-emerald-200';
                        button.innerHTML = 'Activate';
                    }
                }

                Swal.fire({
                    toast: true,
                    position: 'top-end',
                    icon: 'success',
                    title: data.message,
                    showConfirmButton: false,
                    timer: 2200,
                    timerProgressBar: true
                });
            } catch (error) {
                console.error(error);
                button.innerHTML = originalText;

                Swal.fire({
                    toast: true,
                    position: 'top-end',
                    icon: 'error',
                    title: 'Failed to update payment method status',
                    showConfirmButton: false,
                    timer: 2500,
                    timerProgressBar: true
                });
            } finally {
                button.disabled = false;
            }
        });
    });
});
</script>
@endpush