@extends('layouts.admin')

@section('title', 'Receipt ' . $receipt->receipt_number)

@section('page-title', 'Payment Receipt')

@section('breadcrumbs')
    <a href="{{ route('admin.receipts.index') }}" class="hover:text-primary text-gray-600">Receipts</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">{{ $receipt->receipt_number }}</span>
@endsection

@section('header-actions')
    <div class="flex items-center gap-3 no-print">
        <a href="{{ route('admin.receipts.index') }}" class="px-4 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors flex items-center gap-2">
            <span class="material-symbols-outlined text-lg">arrow_back</span>
            <span>Back</span>
        </a>
    </div>
@endsection

@section('content')
@php
    $tplQuery = http_build_query(array_filter(['template' => $templateKey]));
    $downloadBranded = route('admin.receipts.download', $receipt).'?'.$tplQuery;
    $downloadSimple = route('admin.receipts.download', $receipt).'?simple=1';
    $printUrl = route('admin.receipts.print', $receipt).'?'.$tplQuery;
@endphp
<div class="max-w-7xl mx-auto">
    <div class="bg-white rounded-xl border border-gray-200 shadow-sm mb-6">
        <div class="p-6 border-b border-gray-100 flex flex-wrap items-center justify-between gap-4">
            <div>
                <h2 class="text-2xl font-bold text-gray-900">{{ $receipt->receipt_number }}</h2>
                <p class="text-sm text-gray-500 mt-1">
                    {{ $receipt->created_at->format('M d, Y') }}
                    @if($receipt->invoice)
                        · Invoice {{ $receipt->invoice->invoice_number }}
                    @endif
                </p>
                <div class="mt-3 flex flex-wrap items-center gap-2">
                    <label for="receipt-template-select" class="text-xs font-medium text-gray-600">Preview template</label>
                    <select id="receipt-template-select" class="text-sm border border-gray-200 rounded-lg px-3 py-1.5 text-gray-900 bg-white focus:ring-2 focus:ring-primary focus:border-primary" onchange="window.location.href='{{ route('admin.receipts.show', $receipt) }}?template='+encodeURIComponent(this.value)">
                        @foreach(['modern' => 'Standard', 'classic' => 'POS style', 'minimal' => 'Business', 'bold' => 'Modern branded'] as $key => $label)
                            <option value="{{ $key }}" {{ $templateKey === $key ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
            </div>
            <div class="flex flex-wrap items-center gap-2 justify-end">
                <button type="button" onclick="rcOpenEmailModal()" class="inline-flex items-center gap-2 px-3 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm" title="Send receipt by email">
                    <span class="material-symbols-outlined text-[18px]">mail</span>
                    <span class="hidden sm:inline">Email</span>
                </button>
                <button type="button" onclick="rcOpenWaLinkModal()" class="inline-flex items-center gap-2 px-3 py-2 border border-gray-200 text-green-700 rounded-lg hover:bg-green-50 transition-colors text-sm" title="Send public receipt link via WhatsApp">
                    <span class="material-symbols-outlined text-[18px]">chat</span>
                    <span class="hidden sm:inline">WhatsApp link</span>
                </button>
                @if(isset($whatsappConfig) && $whatsappConfig && $whatsappConfig->is_active)
                <button type="button" onclick="rcOpenWaPdfModal()" class="inline-flex items-center gap-2 px-3 py-2 border border-gray-200 text-green-700 rounded-lg hover:bg-green-50 transition-colors text-sm" title="Send PDF via WhatsApp Business API">
                    <span class="material-symbols-outlined text-[18px]">picture_as_pdf</span>
                    <span class="hidden sm:inline">WhatsApp PDF</span>
                </button>
                @endif
                <button type="button" onclick="rcCopyPublicLink()" class="inline-flex items-center gap-2 px-3 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm" title="Copy public receipt link">
                    <span class="material-symbols-outlined text-[18px]">link</span>
                    <span class="hidden sm:inline">Copy link</span>
                </button>
                <a href="{{ $printUrl }}" target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-2 px-3 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm">
                    <span class="material-symbols-outlined text-[18px]">print</span>
                    <span>Print</span>
                </a>
                <a href="{{ $downloadBranded }}" target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-2 px-3 py-2 border border-gray-200 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors text-sm" title="Download PDF using selected template">
                    <span class="material-symbols-outlined text-[18px]">download</span>
                    <span class="hidden sm:inline">Download PDF</span>
                    <span class="sm:hidden">PDF</span>
                </a>
                <a href="{{ $downloadSimple }}" target="_blank" rel="noopener noreferrer" class="inline-flex items-center gap-2 px-3 py-2 border border-dashed border-gray-300 text-gray-600 rounded-lg hover:bg-gray-50 transition-colors text-sm" title="Simple one-page PDF (table layout)">
                    <span class="material-symbols-outlined text-[18px]">description</span>
                    <span class="hidden lg:inline">Simple PDF</span>
                </a>
            </div>
        </div>
        <div class="p-6">
            @if(isset($templateView) && view()->exists($templateView))
                @php
                    $templateContent = view($templateView, ['payment' => $payment])->render();
                    preg_match_all('/<style[^>]*>(.*?)<\/style>/is', $templateContent, $styleMatches);
                    $styles = !empty($styleMatches[1]) ? '<style>' . implode('</style><style>', $styleMatches[1]) . '</style>' : '';
                    $bodyContent = $templateContent;
                    if (preg_match('/<body[^>]*>(.*?)<\/body>/is', $templateContent, $bodyMatches)) {
                        $bodyContent = $bodyMatches[1];
                    }
                    $bodyContent = preg_replace('/<script\b[^>]*>(.*?)<\/script>/is', '', $bodyContent);
                @endphp
                {!! $styles !!}
                <style>
                    .receipt-screen-preview .quotation-container,
                    .receipt-screen-preview [class*="receipt"] {
                        max-width: 100%;
                    }
                    .receipt-screen-preview {
                        color: rgba(0, 0, 0, 1);
                    }
                </style>
                <div class="overflow-x-auto">
                    <div class="receipt-screen-preview min-w-[320px] max-w-[900px] mx-auto bg-white">
                        {!! $bodyContent !!}
                    </div>
                </div>
            @else
                <div class="p-6 text-gray-500">Template not found.</div>
            @endif
        </div>
    </div>
</div>

{{-- Email --}}
<div id="rc-email-modal" data-admin-modal class="hidden fixed inset-0 z-[60] overflow-y-auto" role="dialog" aria-modal="true">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="rcCloseEmailModal()" aria-hidden="true"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-5 sm:p-6 max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-900">Send receipt via email</h3>
                <button type="button" onclick="rcCloseEmailModal()" class="text-gray-400 hover:text-gray-600 rounded-lg p-1 hover:bg-gray-100" aria-label="Close">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="rc-email-form" class="space-y-4">
                <div class="bg-gray-50 rounded-lg p-4 text-sm">
                    <div class="flex justify-between gap-2">
                        <span class="text-gray-600">Receipt</span>
                        <span class="font-semibold text-gray-900">{{ $receipt->receipt_number }}</span>
                    </div>
                </div>
                @if(!isset($emailConfig) || !$emailConfig || !$emailConfig->is_active)
                    <p class="text-sm text-amber-800 bg-amber-50 border border-amber-200 rounded-lg p-3">Email is not configured or inactive. Set up email under <strong>Settings</strong> before sending.</p>
                @endif
                <div>
                    <label for="rc-email-input" class="block text-sm font-medium text-gray-700 mb-2">Recipient email</label>
                    <input type="email" id="rc-email-input" required class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900" placeholder="customer@example.com" value="{{ $receipt->customer?->email ?? '' }}">
                </div>
                <div class="flex flex-col-reverse sm:flex-row gap-3 pt-2 border-t border-gray-200">
                    <button type="button" onclick="rcCloseEmailModal()" class="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">Cancel</button>
                    <button type="submit" id="rc-email-submit" class="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-primary rounded-lg hover:bg-blue-600 disabled:opacity-50" @if(!isset($emailConfig) || !$emailConfig || !$emailConfig->is_active) disabled @endif>Send</button>
                </div>
            </form>
        </div>
    </div>
</div>

{{-- WhatsApp: public link --}}
<div id="rc-wa-link-modal" data-admin-modal class="hidden fixed inset-0 z-[60] overflow-y-auto" role="dialog" aria-modal="true">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="rcCloseWaLinkModal()" aria-hidden="true"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-5 sm:p-6 max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-bold text-gray-900">Send receipt link via WhatsApp</h3>
                <button type="button" onclick="rcCloseWaLinkModal()" class="text-gray-400 hover:text-gray-600 rounded-lg p-1 hover:bg-gray-100" aria-label="Close">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="rc-wa-link-form" class="space-y-4">
                <div class="bg-gray-50 rounded-lg p-4 text-sm space-y-2">
                    <div class="flex justify-between gap-2">
                        <span class="text-gray-600">Receipt</span>
                        <span class="font-semibold text-gray-900">{{ $receipt->receipt_number }}</span>
                    </div>
                    <div class="flex justify-between gap-2 items-start">
                        <span class="text-gray-600 shrink-0 pr-2">Company WhatsApp</span>
                        <span class="font-semibold text-gray-900 text-right break-all">
                            @if(isset($whatsappSettings) && $whatsappSettings && filled(data_get($whatsappSettings->config, 'link_recipient_phone')))
                                {{ data_get($whatsappSettings->config, 'link_recipient_phone') }}
                            @else
                                <span class="font-normal text-gray-500">Not set</span>
                            @endif
                        </span>
                    </div>
                </div>
                <div>
                    <label for="rc-wa-link-phone" class="block text-sm font-medium text-gray-700 mb-2">Customer WhatsApp <span class="text-red-500">*</span></label>
                    <input type="text" id="rc-wa-link-phone" required class="w-full px-4 py-2.5 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900" placeholder="+1234567890" value="{{ $receipt->customer?->phone ?? '' }}" autocomplete="tel">
                </div>
                <div class="flex flex-col-reverse sm:flex-row gap-3 pt-2 border-t border-gray-200">
                    <button type="button" onclick="rcCloseWaLinkModal()" class="flex-1 px-4 py-2.5 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200">Cancel</button>
                    <button type="submit" id="rc-wa-link-submit" class="flex-1 px-4 py-2.5 text-sm font-medium text-white bg-green-600 rounded-lg hover:bg-green-700">Open WhatsApp</button>
                </div>
            </form>
        </div>
    </div>
</div>

@if(isset($whatsappConfig) && $whatsappConfig && $whatsappConfig->is_active)
<div id="rc-wa-pdf-modal" data-admin-modal class="hidden fixed inset-0 z-[60] overflow-y-auto" role="dialog" aria-modal="true">
    <div class="flex min-h-full items-start justify-center px-4 py-6 sm:py-10">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="rcCloseWaPdfModal()" aria-hidden="true"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-5 sm:p-6 max-h-[90vh] overflow-y-auto border border-gray-100">
            <div class="flex items-start justify-between gap-3 mb-4">
                <div class="min-w-0">
                    <h3 class="text-lg font-bold text-gray-900 leading-tight">Send receipt PDF via WhatsApp</h3>
                    <p class="text-sm text-gray-500 mt-0.5">Uses the template selected above</p>
                </div>
                <button type="button" onclick="rcCloseWaPdfModal()" class="text-gray-400 hover:text-gray-600 shrink-0 rounded-lg p-1 hover:bg-gray-100" aria-label="Close">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="rc-wa-pdf-form" class="space-y-4">
                <div>
                    <label for="rc-wa-pdf-phone" class="block text-sm font-semibold text-gray-800 mb-2">Customer WhatsApp <span class="text-red-500">*</span></label>
                    <input type="tel" id="rc-wa-pdf-phone" required autocomplete="tel" class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-3 shadow-sm focus:border-primary focus:ring-2 focus:ring-primary/20 sm:text-sm" placeholder="e.g. +14166368482" value="{{ $receipt->customer?->phone ?? '' }}">
                </div>
                <div class="flex flex-col-reverse sm:flex-row sm:justify-end gap-3 pt-2">
                    <button type="button" onclick="rcCloseWaPdfModal()" class="w-full sm:w-auto px-4 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 text-sm font-medium">Cancel</button>
                    <button type="submit" id="rc-wa-pdf-submit" class="w-full sm:w-auto inline-flex items-center justify-center gap-2 px-4 py-2.5 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm font-semibold shadow-sm">
                        <span class="material-symbols-outlined text-lg">send</span>
                        <span id="rc-wa-pdf-submit-label">Send PDF</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endif

<div id="rc-success-modal" data-admin-modal class="hidden fixed inset-0 z-[70] overflow-y-auto">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="fixed inset-0 bg-black/50 backdrop-blur-sm" onclick="rcCloseSuccessModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-md w-full p-6">
            <div class="flex items-center gap-4 mb-4">
                <div class="flex-shrink-0 w-12 h-12 bg-green-100 rounded-full flex items-center justify-center">
                    <span class="material-symbols-outlined text-green-600 text-2xl">check_circle</span>
                </div>
                <div class="flex-1 min-w-0">
                    <h3 class="text-lg font-bold text-gray-900">Done</h3>
                    <p id="rc-success-message" class="text-sm text-gray-500 mt-1"></p>
                </div>
                <button type="button" onclick="rcCloseSuccessModal()" class="text-gray-400 hover:text-gray-600 shrink-0" aria-label="Close">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <button type="button" onclick="rcCloseSuccessModal()" class="w-full px-4 py-2 text-sm font-medium text-white bg-primary rounded-lg hover:bg-blue-600">OK</button>
        </div>
    </div>
</div>

@push('scripts')
<script>
(function () {
    const receiptId = {{ (int) $receipt->id }};
    const templateKey = @json($templateKey);

    function getAdminCsrfToken() {
        const meta = document.querySelector('meta[name="csrf-token"]');
        if (meta?.content) return meta.content;
        const input = document.querySelector('input[name="_token"]');
        return input?.value || '';
    }

    function adminJsonFetchInit(body) {
        return {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': getAdminCsrfToken(),
            },
            body: body !== undefined ? JSON.stringify(body) : undefined,
        };
    }

    async function rcFetchShareLink() {
        const res = await fetch(`/admin/receipts/${receiptId}/share-link`, {
            method: 'GET',
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': getAdminCsrfToken(),
            },
        });
        const data = await res.json().catch(() => ({}));
        if (!res.ok || !data.success || !data.link) {
            throw new Error(data.message || 'Could not create share link');
        }
        return data.link;
    }

    window.rcShowSuccess = function (message) {
        const el = document.getElementById('rc-success-message');
        const modal = document.getElementById('rc-success-modal');
        if (el) el.textContent = message;
        if (modal) {
            modal.classList.remove('hidden');
            window.clearTimeout(window._rcSuccessT);
            window._rcSuccessT = setTimeout(() => modal.classList.add('hidden'), 3200);
        } else {
            alert(message);
        }
    };

    window.rcCloseSuccessModal = function () {
        document.getElementById('rc-success-modal')?.classList.add('hidden');
    };

    window.rcOpenEmailModal = function () {
        document.getElementById('rc-email-modal')?.classList.remove('hidden');
    };
    window.rcCloseEmailModal = function () {
        document.getElementById('rc-email-modal')?.classList.add('hidden');
    };

    window.rcOpenWaLinkModal = function () {
        document.getElementById('rc-wa-link-modal')?.classList.remove('hidden');
    };
    window.rcCloseWaLinkModal = function () {
        document.getElementById('rc-wa-link-modal')?.classList.add('hidden');
    };

    window.rcOpenWaPdfModal = function () {
        document.getElementById('rc-wa-pdf-modal')?.classList.remove('hidden');
    };
    window.rcCloseWaPdfModal = function () {
        document.getElementById('rc-wa-pdf-modal')?.classList.add('hidden');
    };

    window.rcCopyPublicLink = async function () {
        const bladeUrl = @json($receipt->getPublicUrl());
        try {
            if (bladeUrl) {
                await navigator.clipboard.writeText(bladeUrl);
                rcShowSuccess('Public receipt link copied to clipboard.');
                return;
            }
        } catch (_) { /* fall through */ }
        try {
            const link = await rcFetchShareLink();
            await navigator.clipboard.writeText(link);
            rcShowSuccess('Public receipt link copied to clipboard.');
        } catch (e) {
            alert(e.message || 'Could not copy link');
        }
    };

    document.getElementById('rc-email-form')?.addEventListener('submit', async function (e) {
        e.preventDefault();
        const email = document.getElementById('rc-email-input')?.value.trim();
        if (!email) return;
        const submit = document.getElementById('rc-email-submit');
        const orig = submit ? submit.textContent : '';
        if (submit) { submit.disabled = true; submit.textContent = 'Sending…'; }
        try {
            const res = await fetch(`/admin/receipts/${receiptId}/send-email`, adminJsonFetchInit({ email }));
            const data = await res.json().catch(() => ({}));
            if (res.status === 419) {
                alert('Session expired. Refresh the page and try again.');
                return;
            }
            if (data.success) {
                rcCloseEmailModal();
                rcShowSuccess(data.message || 'Receipt email request completed.');
            } else {
                alert(data.message || 'Could not send email.');
            }
        } catch (err) {
            alert('Network error: ' + (err.message || 'try again'));
        } finally {
            if (submit) { submit.disabled = false; submit.textContent = orig; }
        }
    });

    document.getElementById('rc-wa-link-form')?.addEventListener('submit', async function (e) {
        e.preventDefault();
        const raw = document.getElementById('rc-wa-link-phone')?.value.trim() || '';
        const digits = raw.replace(/\D/g, '');
        if (!digits) {
            alert('Enter a phone number with country code.');
            return;
        }
        const submit = document.getElementById('rc-wa-link-submit');
        const orig = submit ? submit.innerHTML : '';
        if (submit) { submit.disabled = true; submit.innerHTML = '<span class="material-symbols-outlined animate-spin text-[18px]">sync</span>'; }
        try {
            const link = await rcFetchShareLink();
            const msg = `Payment receipt {{ $receipt->receipt_number }}\n\nView:\n\n${link}`;
            window.open(`https://wa.me/${digits}?text=${encodeURIComponent(msg)}`, '_blank', 'noopener,noreferrer');
            rcCloseWaLinkModal();
            rcShowSuccess('If WhatsApp did not open, allow pop-ups for this site.');
        } catch (err) {
            alert(err.message || 'Could not open WhatsApp.');
        } finally {
            if (submit) { submit.disabled = false; submit.innerHTML = orig; }
        }
    });

    document.getElementById('rc-wa-pdf-form')?.addEventListener('submit', async function (e) {
        e.preventDefault();
        const phone = document.getElementById('rc-wa-pdf-phone')?.value.trim() || '';
        if (!phone) {
            alert('Enter the customer WhatsApp number.');
            return;
        }
        const submit = document.getElementById('rc-wa-pdf-submit');
        const label = document.getElementById('rc-wa-pdf-submit-label');
        const origLabel = label ? label.textContent : '';
        if (submit) submit.disabled = true;
        if (label) label.textContent = 'Sending…';
        try {
            const res = await fetch(`/admin/receipts/${receiptId}/send-whatsapp`, adminJsonFetchInit({ phone, template: templateKey }));
            const data = await res.json().catch(() => ({}));
            if (res.ok && data.success) {
                rcCloseWaPdfModal();
                rcShowSuccess(data.message || 'Receipt PDF sent via WhatsApp.');
                return;
            }
            alert(data.message || 'Failed to send PDF via WhatsApp.');
        } catch (err) {
            alert('Error: ' + (err.message || 'try again'));
        } finally {
            if (submit) submit.disabled = false;
            if (label) label.textContent = origLabel;
        }
    });
})();
</script>
@endpush
@endsection
