@extends('layouts.admin')

@section('title', 'Vouchers')
@section('page-title', 'Vouchers')

@section('content')
<div x-data="voucherPush()" class="space-y-6">
    <section class="flex flex-wrap items-center justify-between gap-4 rounded-3xl border border-slate-200 bg-white p-6 shadow-sm">
        <div>
            <h2 class="text-xl font-bold text-slate-900">Voucher Campaigns</h2>
            <p class="mt-1 text-sm text-slate-500">Create promo codes for paid plans and track redemption usage.</p>
        </div>
        <a href="{{ route('admin.vouchers.create') }}" class="inline-flex rounded-2xl bg-brand-600 px-5 py-3 text-sm font-semibold text-white transition hover:bg-brand-700">Create Vouchers</a>
    </section>

    <section class="rounded-3xl border border-slate-200 bg-white shadow-sm">
        <div class="overflow-x-auto">
            <table class="min-w-full text-left text-sm">
                <thead class="border-b border-slate-200 bg-slate-50 text-slate-500">
                    <tr>
                        <th class="px-6 py-4 font-semibold">Code</th>
                        <th class="px-6 py-4 font-semibold">Plan</th>
                        <th class="px-6 py-4 font-semibold">Period</th>
                        <th class="px-6 py-4 font-semibold">Usage</th>
                        <th class="px-6 py-4 font-semibold">Expiry</th>
                        <th class="px-6 py-4 font-semibold">Status</th>
                        <th class="px-6 py-4 font-semibold text-right">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    @forelse($vouchers as $voucher)
                        <tr class="table-row-hover">
                            <td class="px-6 py-5">
                                <div class="font-mono text-sm font-bold text-slate-900">{{ $voucher->code }}</div>
                                @if($voucher->notes)
                                    <div class="mt-1 text-xs text-slate-500">{{ $voucher->notes }}</div>
                                @endif
                            </td>
                            <td class="px-6 py-5"><span class="rounded-full bg-slate-100 px-3 py-1 text-xs font-semibold text-slate-700">{{ ucfirst($voucher->plan) }}</span></td>
                            <td class="px-6 py-5 text-slate-600">{{ ucfirst($voucher->period) }} · {{ $voucher->days }} days</td>
                            <td class="px-6 py-5 text-slate-600">{{ $voucher->used_count }}/{{ $voucher->max_uses }}</td>
                            <td class="px-6 py-5 text-slate-600">{{ $voucher->expires_at?->format('d M Y') ?? 'No expiry' }}</td>
                            <td class="px-6 py-5">
                                <span class="rounded-full px-3 py-1 text-xs font-semibold {{ $voucher->isUsable() ? 'badge-active' : 'badge-expired' }}">{{ $voucher->isUsable() ? 'Usable' : 'Inactive' }}</span>
                            </td>
                            <td class="px-6 py-5">
                                <div class="flex items-center justify-end gap-2">
                                    {{-- Send push notification --}}
                                    <button type="button"
                                            @click="open('{{ $voucher->id }}', '{{ $voucher->code }}', '{{ route('admin.vouchers.sendPush', $voucher) }}', '{{ route('admin.vouchers.getDevices', $voucher) }}')"
                                            class="rounded-xl border border-indigo-300 bg-indigo-50 px-3 py-2 text-xs font-semibold text-indigo-700 transition hover:bg-indigo-100">
                                        Send Push
                                    </button>
                                    <form method="POST" action="{{ route('admin.vouchers.toggle', $voucher) }}">
                                        @csrf
                                        <button type="submit" class="rounded-xl border border-slate-300 px-3 py-2 text-xs font-semibold text-slate-700 transition hover:border-brand-600 hover:text-brand-600">{{ $voucher->is_active ? 'Disable' : 'Enable' }}</button>
                                    </form>
                                    <form method="POST" action="{{ route('admin.vouchers.destroy', $voucher) }}" onsubmit="return confirm('Delete this voucher?')">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="rounded-xl bg-slate-900 px-3 py-2 text-xs font-semibold text-white transition hover:bg-slate-700">Delete</button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    @empty
                        <tr><td colspan="7" class="px-6 py-16 text-center text-sm text-slate-500">No vouchers created yet.</td></tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        <div class="border-t border-slate-200 px-6 py-4">{{ $vouchers->links() }}</div>
    </section>

    {{-- Send Push Modal --}}
    <div x-show="modal" x-transition class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4" style="display:none">
        <div @click.outside="modal = false" class="w-full max-w-lg rounded-2xl bg-white p-6 shadow-xl max-h-[90vh] flex flex-col">
            <h3 class="text-base font-bold text-slate-900 mb-1">Send Voucher Push Notification</h3>
            <p class="text-xs text-slate-500 mb-4">Code: <span class="font-mono font-bold text-slate-800" x-text="code"></span></p>

            <div class="space-y-3 overflow-y-auto flex-1 pr-1">
                <div>
                    <label class="mb-1.5 block text-xs font-semibold text-slate-700">Title</label>
                    <input type="text" x-model="title" placeholder="Your exclusive voucher code"
                           class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand-600 focus:ring-2 focus:ring-brand-600/10">
                </div>
                <div>
                    <label class="mb-1.5 block text-xs font-semibold text-slate-700">Message</label>
                    <textarea x-model="body" rows="2" placeholder="Use code ... to get a discount on your subscription."
                              class="w-full rounded-xl border border-slate-300 px-3 py-2 text-sm outline-none focus:border-brand-600 focus:ring-2 focus:ring-brand-600/10 resize-none"></textarea>
                </div>

                {{-- Recipients --}}
                <div>
                    <div class="flex items-center justify-between mb-2">
                        <label class="text-xs font-semibold text-slate-700">Recipients</label>
                        <div class="flex items-center gap-3">
                            <label class="flex items-center gap-1.5 text-xs text-slate-600 cursor-pointer">
                                <input type="checkbox" x-model="noSubOnly" @change="loadUsers()" class="rounded">
                                <span>No subscription only</span>
                            </label>
                            <label class="flex items-center gap-1.5 text-xs text-slate-600 cursor-pointer">
                                <input type="checkbox" x-model="sendAll" @change="onSendAllChange()" class="rounded">
                                <span>All devices</span>
                            </label>
                        </div>
                    </div>

                    <div x-show="!sendAll">
                        <div x-show="loadingUsers" class="py-4 text-center text-xs text-slate-500">Loading users…</div>
                        <div x-show="!loadingUsers && users.length === 0" class="py-4 text-center text-xs text-slate-500">No users with active devices found.</div>
                        <div x-show="!loadingUsers && users.length > 0" class="rounded-xl border border-slate-200 divide-y divide-slate-100 max-h-48 overflow-y-auto">
                            <template x-for="user in users" :key="user.id">
                                <div class="p-3">
                                    <div class="flex items-center justify-between">
                                        <div>
                                            <div class="text-xs font-semibold text-slate-800" x-text="user.name"></div>
                                            <div class="text-xs text-slate-500" x-text="user.email + ' · ' + user.plan"></div>
                                        </div>
                                        <span class="text-xs text-slate-400" x-text="user.devices.length + ' device(s)'"></span>
                                    </div>
                                    <div class="mt-2 flex flex-wrap gap-1.5">
                                        <template x-for="device in user.devices" :key="device.id">
                                            <label class="flex items-center gap-1 rounded-lg border border-slate-200 bg-slate-50 px-2 py-1 text-xs cursor-pointer"
                                                   :class="selectedDeviceIds.includes(device.id) ? 'border-indigo-400 bg-indigo-50 text-indigo-700' : 'text-slate-600'">
                                                <input type="checkbox"
                                                       :value="device.id"
                                                       :checked="selectedDeviceIds.includes(device.id)"
                                                       @change="toggleDevice(device.id)"
                                                       class="sr-only">
                                                <span x-text="device.platform + ' · ' + device.model"></span>
                                            </label>
                                        </template>
                                    </div>
                                </div>
                            </template>
                        </div>
                        <p class="mt-1 text-xs text-slate-400">
                            <span x-show="selectedDeviceIds.length > 0" x-text="selectedDeviceIds.length + ' device(s) selected'"></span>
                            <span x-show="selectedDeviceIds.length === 0">Select devices above, or enable "All devices"</span>
                        </p>
                    </div>
                </div>
            </div>

            <div x-show="resultMsg" class="mt-3 rounded-xl px-3 py-2 text-xs font-semibold"
                 :class="resultOk ? 'bg-emerald-50 text-emerald-700' : 'bg-red-50 text-red-700'"
                 x-text="resultMsg"></div>

            <div class="mt-4 flex gap-3">
                <button type="button" @click="send()" :disabled="sending || (!sendAll && selectedDeviceIds.length === 0)"
                        class="flex-1 rounded-xl bg-indigo-600 py-2.5 text-sm font-semibold text-white transition hover:bg-indigo-700 disabled:opacity-50">
                    <span x-show="!sending" x-text="sendAll ? 'Send to All Devices' : 'Send to Selected (' + selectedDeviceIds.length + ')'"></span>
                    <span x-show="sending">Sending…</span>
                </button>
                <button type="button" @click="modal = false"
                        class="rounded-xl border border-slate-300 px-4 py-2.5 text-sm font-semibold text-slate-700 transition hover:border-slate-400">
                    Close
                </button>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
function voucherPush() {
    return {
        modal: false,
        voucherId: null,
        code: '',
        url: '',
        devicesUrl: '',
        title: '',
        body: '',
        sending: false,
        resultMsg: '',
        resultOk: false,
        // recipients
        sendAll: true,
        noSubOnly: false,
        users: [],
        selectedDeviceIds: [],
        loadingUsers: false,

        open(id, code, url, devicesUrl) {
            this.voucherId = id;
            this.code = code;
            this.url = url;
            this.devicesUrl = devicesUrl;
            this.title = 'Your exclusive voucher code 🎁';
            this.body = `Use code ${code} to get a discount on your subscription.`;
            this.resultMsg = '';
            this.sending = false;
            this.sendAll = true;
            this.noSubOnly = false;
            this.users = [];
            this.selectedDeviceIds = [];
            this.modal = true;
        },

        async loadUsers() {
            this.loadingUsers = true;
            this.users = [];
            this.selectedDeviceIds = [];
            try {
                const suffix = this.noSubOnly ? '?no_sub=1' : '';
                const res = await fetch(this.devicesUrl + suffix, {
                    headers: {
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    },
                });
                const data = await res.json();
                this.users = data.users || [];
                // default: select all devices
                this.selectedDeviceIds = this.users.flatMap(u => u.devices.map(d => d.id));
            } catch (e) {
                this.users = [];
            } finally {
                this.loadingUsers = false;
            }
        },

        toggleDevice(deviceId) {
            const idx = this.selectedDeviceIds.indexOf(deviceId);
            if (idx === -1) this.selectedDeviceIds.push(deviceId);
            else this.selectedDeviceIds.splice(idx, 1);
        },

        async send() {
            if (!this.sendAll && this.selectedDeviceIds.length === 0) return;
            this.sending = true;
            this.resultMsg = '';
            try {
                const res = await fetch(this.url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    },
                    body: JSON.stringify({
                        title: this.title,
                        body: this.body,
                        device_ids: this.sendAll ? [] : this.selectedDeviceIds,
                    }),
                });
                const data = await res.json();
                this.resultOk = data.ok;
                this.resultMsg = data.message;
            } catch (e) {
                this.resultOk = false;
                this.resultMsg = 'Network error — please try again.';
            } finally {
                this.sending = false;
            }
        },

        // called when "All devices" checkbox toggles off → lazy-load users
        onSendAllChange() {
            if (!this.sendAll && this.users.length === 0) {
                this.loadUsers();
            }
        },
    };
}
</script>
@endpush
@endsection
