@extends('layouts.admin')

@section('title', 'Invoice ' . $invoice->invoice_number)

@section('page-title', 'Invoice Details')

@section('content')
<div class="flex-1 overflow-y-auto overflow-x-hidden p-4 md:p-8 bg-gray-50">
    <div class="max-w-7xl mx-auto">
        <!-- Header -->
        <div class="mb-6 flex items-center justify-between no-print">
            <div>
                <a href="{{ route('admin.invoices.index') }}" class="inline-flex items-center gap-2 text-sm text-gray-600 hover:text-primary mb-2">
                    <span class="material-symbols-outlined text-base">arrow_back</span>
                    <span>Back to Invoices</span>
                </a>
                <h1 class="text-2xl md:text-3xl font-bold text-gray-900">Invoice {{ $invoice->invoice_number }}</h1>
                <p class="text-gray-500 mt-1">
                    @php
                        $statusConfig = [
                            'draft' => ['label' => 'Draft', 'bg' => 'bg-gray-100', 'text' => 'text-gray-800'],
                            'partial' => ['label' => 'Partially Paid', 'bg' => 'bg-blue-100', 'text' => 'text-blue-800'],
                            'paid' => ['label' => 'Paid', 'bg' => 'bg-green-100', 'text' => 'text-green-800'],
                            'sent' => ['label' => 'Sent', 'bg' => 'bg-blue-100', 'text' => 'text-blue-800'],
                            'viewed' => ['label' => 'Viewed', 'bg' => 'bg-purple-100', 'text' => 'text-purple-800'],
                            'unpaid' => ['label' => 'Unpaid', 'bg' => 'bg-yellow-100', 'text' => 'text-yellow-800'],
                            'overdue' => ['label' => 'Overdue', 'bg' => 'bg-red-100', 'text' => 'text-red-800'],
                        ];
                        $status = $invoice->status === 'partial' ? 'partial' : ($invoice->balance == 0 && $invoice->status !== 'draft' && $invoice->status !== 'sent' && $invoice->status !== 'viewed' ? 'paid' : ($invoice->balance > 0 && $invoice->status === 'sent' ? 'unpaid' : $invoice->status));
                        $config = $statusConfig[$status] ?? $statusConfig['draft'];
                    @endphp
                    <span class="inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium {{ $config['bg'] }} {{ $config['text'] }}">
                        {{ $config['label'] }}
                    </span>
                    • {{ $invoice->created_at->format('M d, Y') }}
                </p>
            </div>
        </div>

        <!-- 2-Column Layout -->
        <div class="flex flex-col xl:flex-row gap-6">
            <!-- LEFT COLUMN: Invoice Template -->
            <div class="flex-1 xl:flex-[6] min-w-0">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-3 sm:p-4 md:p-8 overflow-x-auto overflow-y-visible invoice-main-container print:shadow-none print:border-0">
                    <div class="print-container">
                        @if(isset($templateView) && view()->exists($templateView))
                            @include($templateView, [
                                'invoice' => $invoice,
                                'invoiceData' => $data ?? [],
                                'customer' => $customer ?? null,
                                'companySettings' => $companySettings ?? null,
                                'currency' => $selectedCurrency ?? null,
                                'signature' => $signature ?? null,
                                'items' => $items ?? [],
                                'calculatedTotals' => [
                                    'subtotal' => $subtotal ?? 0,
                                    'tax_amount' => $taxAmount ?? 0,
                                    'discount' => $discount ?? 0,
                                    'total' => $total ?? 0,
                                    'paid_amount' => $paidAmount ?? 0,
                                    'balance_due' => $balanceDue ?? 0,
                                ],
                                'showWatermark' => false,
                            ])
                        @else
                            <!-- Fallback invoice display -->
                            <div class="p-8">
                                <h2 class="text-2xl font-bold mb-4">Invoice {{ $invoice->invoice_number }}</h2>
                                <p class="text-gray-600">Template not found. Please configure invoice template.</p>
                            </div>
                        @endif
                    </div>
                </div>
            </div>

            <!-- RIGHT COLUMN: Action Buttons -->
            <div class="w-full xl:w-56 flex-shrink-0 no-print">
                <!-- Top Actions (Sticky) -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 sticky top-4 mb-4">
                    <h3 class="text-base font-bold text-gray-900 mb-3 flex items-center gap-2">
                        <span class="material-symbols-outlined text-primary text-lg">settings</span>
                        <span class="hidden xl:inline">Actions</span>
                    </h3>
                    
                    <!-- Grid Layout: Responsive 2-row grid (5 cols desktop, 3 cols tablet, 2 cols mobile) -->
                    <div class="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 auto-rows-fr gap-2">
                        <!-- Edit Button -->
                        <a href="{{ route('admin.invoices.edit', $invoice) }}" class="flex flex-col items-center justify-center gap-1.5 px-2 py-2.5 min-h-[80px] bg-white border border-gray-200 rounded-lg hover:bg-gray-50 active:bg-gray-100 transition-colors" title="Edit Invoice">
                            <span class="material-symbols-outlined text-primary text-xl">edit</span>
                            <span class="text-xs font-medium text-gray-900 text-center leading-tight">Edit</span>
                        </a>

                        <!-- Mark as Paid: only when balance remains (unpaid or partially paid) -->
                        @if(!$isFullyPaid)
                        <button type="button" onclick="openMarkPaidModal({{ $invoice->id }})" class="flex flex-col items-center justify-center gap-1.5 px-2 py-2.5 min-h-[80px] bg-white border border-gray-200 rounded-lg hover:bg-gray-50 active:bg-gray-100 transition-colors" title="Mark as Paid">
                            <span class="material-symbols-outlined text-green-600 text-xl">payments</span>
                            <span class="text-xs font-medium text-gray-900 text-center leading-tight">Mark As Paid</span>
                        </button>
                        @endif

                        <!-- Send public link via WhatsApp (always available regardless of status) -->
                        <button type="button" onclick="openWhatsAppLinkModal({{ $invoice->id }})" class="flex flex-col items-center justify-center gap-1.5 px-2 py-2.5 min-h-[80px] bg-white border border-gray-200 rounded-lg hover:bg-gray-50 active:bg-gray-100 transition-colors" title="Send invoice link via WhatsApp">
                            <span class="material-symbols-outlined text-green-600 text-xl">chat</span>
                            <span class="text-xs font-medium text-gray-900 text-center leading-tight">Send Link via WhatsApp</span>
                        </button>

                        <!-- Print Button -->
                        <button type="button" onclick="printInvoice()" class="flex flex-col items-center justify-center gap-1.5 px-2 py-2.5 min-h-[80px] bg-white border border-gray-200 rounded-lg hover:bg-gray-50 active:bg-gray-100 transition-colors" title="Print Invoice">
                            <span class="material-symbols-outlined text-primary text-xl">print</span>
                            <span class="text-xs font-medium text-gray-900 text-center leading-tight">Print Invoice</span>
                        </button>

                        <!-- Download PDF Button -->
                        <a href="{{ route('admin.invoices.download', $invoice) }}" target="_blank" rel="noopener noreferrer" class="flex flex-col items-center justify-center gap-1.5 px-2 py-2.5 min-h-[80px] bg-white border border-gray-200 rounded-lg hover:bg-gray-50 active:bg-gray-100 transition-colors" title="Download PDF">
                            <span class="material-symbols-outlined text-primary text-xl">download</span>
                            <span class="text-xs font-medium text-gray-900 text-center leading-tight">Download Invoice</span>
                        </a>

                        <!-- Email Button -->
                        <button type="button" onclick="openEmailModal({{ $invoice->id }})" class="flex flex-col items-center justify-center gap-1.5 px-2 py-2.5 min-h-[80px] bg-white border border-gray-200 rounded-lg hover:bg-gray-50 active:bg-gray-100 transition-colors" title="Email Invoice">
                            <span class="material-symbols-outlined text-primary text-xl">email</span>
                            <span class="text-xs font-medium text-gray-900 text-center leading-tight">Send via Email</span>
                        </button>

                        <!-- WhatsApp API PDF Button -->
                        @if(isset($whatsappConfig) && $whatsappConfig && $whatsappConfig->is_active)
                        <button type="button" onclick="openWhatsAppPdfModal({{ $invoice->id }})" class="flex flex-col items-center justify-center gap-1.5 px-2 py-2.5 min-h-[80px] bg-white border border-gray-200 rounded-lg hover:bg-gray-50 active:bg-gray-100 transition-colors" title="Send Invoice PDF via WhatsApp API">
                            <span class="material-symbols-outlined text-green-600 text-xl">description</span>
                            <span class="text-xs font-medium text-gray-900 text-center leading-tight">Send PDF via WhatsApp</span>
                        </button>
                        @endif

                        <!-- Copy Invoice Link Button -->
                        <button type="button" onclick="copyInvoiceLink({{ $invoice->id }})" class="flex flex-col items-center justify-center gap-1.5 px-2 py-2.5 min-h-[80px] bg-white border border-gray-200 rounded-lg hover:bg-gray-50 active:bg-gray-100 transition-colors" title="Copy Invoice Link">
                            <span class="material-symbols-outlined text-primary text-xl">link</span>
                            <span class="text-xs font-medium text-gray-900 text-center leading-tight">Copy Invoice Link</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- WhatsApp Link Modal -->
<div id="whatsapp-link-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
    <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="closeWhatsAppLinkModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-lg w-full p-5 max-h-[calc(100dvh-2rem)] overflow-y-auto">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-bold text-gray-900">Send Invoice Link via WhatsApp</h3>
                <button onclick="closeWhatsAppLinkModal()" class="text-gray-400 hover:text-gray-600">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>

            <form id="whatsapp-link-form" class="space-y-4">
                <input type="hidden" id="whatsapp-link-invoice-id" />

                <div class="bg-gray-50 rounded-lg p-3 space-y-2">
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Invoice No.</span>
                        <span id="whatsapp-link-invoice-number" class="text-sm font-semibold text-gray-900">{{ $invoice->invoice_number }}</span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Company WhatsApp</span>
                        <span id="whatsapp-link-company-number" class="text-sm font-semibold text-gray-900">
                            {{ $whatsappConfig->config['link_recipient_phone'] ?? 'Not set in settings' }}
                        </span>
                    </div>
                </div>

                <div>
                    <label for="whatsapp-link-customer-phone" class="block text-sm font-medium text-gray-700 mb-2">
                        Customer WhatsApp Number <span class="text-red-500">*</span>
                    </label>
                    <input
                        type="text"
                        id="whatsapp-link-customer-phone"
                        class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-2.5 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm"
                        placeholder="+1234567890"
                        required
                    >
                    <p class="mt-1 text-xs text-gray-500">Enter the customer's number to receive this invoice link.</p>
                </div>

                <div class="flex items-center justify-end gap-3 pt-2">
                    <button type="button" onclick="closeWhatsAppLinkModal()" class="px-4 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium">
                        Cancel
                    </button>
                    <button type="submit" class="px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors font-medium shadow-sm">
                        Open WhatsApp
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- WhatsApp PDF (API) Modal -->
@if(isset($whatsappConfig) && $whatsappConfig && $whatsappConfig->is_active)
<div id="whatsapp-pdf-modal" data-admin-modal class="hidden fixed inset-0 z-[55] overflow-y-auto">
    <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="closeWhatsAppPdfModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl border border-gray-100 max-w-lg w-full p-6 max-h-[calc(100dvh-2rem)] overflow-y-auto mt-[90px] mb-[90px]">
            <div class="flex items-start justify-between gap-3 mb-1">
                <div class="flex items-center gap-3">
                    <div class="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-green-50 text-green-700">
                        <span class="material-symbols-outlined text-2xl">description</span>
                    </div>
                    <div>
                        <h3 class="text-lg font-bold text-gray-900 leading-tight">Send invoice PDF via WhatsApp</h3>
                        <p class="text-[14px] font-medium text-gray-500 mt-0.5">Delivered through your configured WhatsApp Business API</p>
                    </div>
                </div>
                <button type="button" onclick="closeWhatsAppPdfModal()" class="text-gray-400 hover:text-gray-600 shrink-0 rounded-lg p-1 hover:bg-gray-100 transition-colors" aria-label="Close">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>

            <form id="whatsapp-pdf-form" class="space-y-5 mt-5">
                <input type="hidden" id="whatsapp-pdf-invoice-id" />

                <div class="rounded-xl border border-gray-200 bg-gradient-to-br from-gray-50 to-white p-4 space-y-3">
                    <div class="flex justify-between items-center gap-2">
                        <span class="text-xs font-semibold uppercase tracking-wide text-gray-500">Invoice</span>
                        <span class="text-sm font-semibold text-gray-900">{{ $invoice->invoice_number }}</span>
                    </div>
                    <div class="flex justify-between items-center gap-2">
                        <span class="text-xs font-semibold uppercase tracking-wide text-gray-500">Customer</span>
                        <span class="text-sm font-medium text-gray-900 text-right truncate max-w-[60%]" title="{{ $customer?->name ?? '' }}">{{ $customer?->name ?? '—' }}</span>
                    </div>
                    <div class="flex justify-between items-center gap-2 pt-1 border-t border-gray-200/80">
                        <span class="text-xs font-semibold uppercase tracking-wide text-gray-500">Total</span>
                        <span class="text-sm font-semibold text-primary">{{ $invoice->currency ?? 'USD' }} {{ number_format((float) ($invoice->total ?? 0), 2) }}</span>
                    </div>
                </div>

                <div>
                    <label for="whatsapp-pdf-customer-phone" class="block text-sm font-semibold text-gray-800 mb-2">
                        Customer WhatsApp number <span class="text-red-500">*</span>
                    </label>
                    <input
                        type="tel"
                        id="whatsapp-pdf-customer-phone"
                        name="phone"
                        autocomplete="tel"
                        class="w-full rounded-lg border border-gray-300 bg-white text-gray-900 px-4 py-3 shadow-sm placeholder:text-gray-400 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-colors sm:text-sm"
                        placeholder="e.g. +353123456789"
                        required
                    />
                    <p class="mt-2 text-[13px] text-gray-500 leading-relaxed">
                        Use international format with country code (E.164). The invoice PDF will be attached to the WhatsApp message.
                    </p>
                </div>

                <div class="flex flex-col-reverse sm:flex-row sm:items-center sm:justify-end gap-3 pt-1">
                    <button type="button" onclick="closeWhatsAppPdfModal()" class="w-full sm:w-auto px-4 py-2.5 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium text-sm">
                        Cancel
                    </button>
                    <button type="submit" id="whatsapp-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 transition-colors font-semibold text-sm shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-600">
                        <span class="material-symbols-outlined text-lg">send</span>
                        <span id="whatsapp-pdf-submit-label">Send PDF</span>
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endif

<!-- Mark as Paid Modal -->
<div id="mark-paid-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
    <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="closeMarkPaidModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-2xl w-full p-5 max-h-[calc(100dvh-2rem)] overflow-y-auto">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-bold text-gray-900">Mark Invoice as Paid</h3>
                <button onclick="closeMarkPaidModal()" class="text-gray-400 hover:text-gray-600">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="mark-paid-form" method="POST" action="{{ route('admin.invoices.mark-paid', $invoice) }}" class="space-y-4">
                @csrf
                <input type="hidden" id="mark-paid-invoice-id" name="invoice_id">
                
                <!-- Invoice Info -->
                <div class="bg-gray-50 rounded-lg p-3 space-y-2">
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Invoice No.</span>
                        <span id="mark-paid-invoice-number" class="text-sm font-semibold text-gray-900"></span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Billed To</span>
                        <span id="mark-paid-customer-name" class="text-sm font-semibold text-gray-900"></span>
                    </div>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-gray-600">Invoice Total</span>
                        <span id="mark-paid-invoice-total" class="text-sm font-semibold text-gray-900"></span>
                    </div>
                </div>

                <!-- Payment Details -->
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Amount Received</label>
                        <input type="number" id="amount-received" name="amount" step="0.01" min="0" required class="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900" placeholder="0.00">
                    </div>
                    <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
                        <div class="flex justify-between items-center">
                            <span class="text-sm font-medium text-gray-700">Amount to Settle</span>
                            <span id="amount-to-settle" class="text-lg font-bold text-blue-600">₦0.00</span>
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Payment Method</label>
                        <select id="payment-method" name="payment_method" required class="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900">
                            <option value="account_transfer">Account Transfer</option>
                            <option value="cash">Cash</option>
                            <option value="cheque">Cheque</option>
                            <option value="credit_card">Credit Card</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="online_payment">Online Payment</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Payment Account</label>
                        <select id="payment-account" name="bank_account_id" class="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900">
                            <option value="">Select Payment Account</option>
                            @php
                                $bankAccounts = \App\Models\BankAccount::where('is_active', true)->get();
                            @endphp
                            @foreach($bankAccounts as $account)
                                <option value="{{ $account->id }}">{{ $account->account_name }} - {{ $account->bank_name }} ({{ $account->account_number }})</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Payment Date</label>
                            <input type="date" id="payment-date" name="payment_date" value="{{ date('Y-m-d') }}" required class="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Transaction ID / Reference</label>
                            <input type="text" id="transaction-id" name="transaction_id" class="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900" placeholder="Optional">
                        </div>
                    </div>
                </div>

                <!-- Options -->
                <div class="space-y-2 border-t border-gray-200 pt-3">
                    <label class="flex items-center gap-3 cursor-pointer">
                        <input type="checkbox" name="notify_client" value="1" checked class="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary">
                        <div>
                            <div class="text-sm font-medium text-gray-900">Notify client about this payment</div>
                            <div class="text-xs text-gray-500">Send a notification email to the customer</div>
                        </div>
                    </label>
                    <label class="flex items-center gap-3 cursor-pointer">
                        <input type="checkbox" name="collect_testimonial" value="1" class="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary">
                        <div>
                            <div class="text-sm font-medium text-gray-900">Collect testimonial from this client</div>
                            <div class="text-xs text-gray-500">We will collect a testimonial on your behalf via an email. This is not an online payment through Refrens. This is a record of payment made by client to you directly.</div>
                        </div>
                    </label>
                </div>

                <!-- Actions -->
                <div class="flex gap-3 pt-3 border-t border-gray-200 sticky bottom-0 bg-white pb-0.5">
                    <button type="button" onclick="closeMarkPaidModal()" class="flex-1 px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200 transition-colors">
                        Cancel
                    </button>
                    <button type="submit" class="flex-1 px-4 py-2 text-sm font-medium text-white bg-primary rounded-lg hover:bg-blue-600 transition-colors">
                        Mark as Paid
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Email Modal -->
<div id="email-modal" data-admin-modal class="hidden fixed inset-0 z-50 overflow-y-auto">
    <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="closeEmailModal()"></div>
        <div class="relative bg-white rounded-xl shadow-xl max-w-4xl w-full p-6 max-h-[calc(100dvh-2rem)] overflow-y-auto">
            <div class="flex items-center justify-between mb-6">
                <h3 id="email-modal-title" class="text-xl font-bold text-gray-900">Email Invoice</h3>
                <button onclick="closeEmailModal()" class="text-gray-400 hover:text-gray-600">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <form id="email-send-form" class="space-y-6">
                @csrf
                <input type="hidden" id="email-modal-invoice-id" name="invoice_id">
                <input type="hidden" id="email-modal-is-receipt" name="is_receipt" value="0">
                
                <!-- Client Name -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Client Name</label>
                    <input type="text" id="email-client-name" name="client_name" readonly class="w-full px-4 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-900">
                </div>

                <!-- Primary Email (hidden but used for sending) -->
                <input type="hidden" id="email-primary-address" name="email">

                <!-- Reply To -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Reply To</label>
                    @php
                        $emailModalCompany = \App\Models\CompanySetting::getSettings();
                        $customersWithEmail = \App\Models\Customer::query()
                            ->whereNotNull('email')
                            ->where('email', '!=', '')
                            ->orderBy('name')
                            ->get(['id', 'name', 'email']);
                    @endphp
                    <select id="email-reply-to" name="reply_to" class="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900 appearance-none bg-white">
                        <option value="">Select...</option>
                        @if($emailModalCompany && $emailModalCompany->company_email)
                            <option value="{{ $emailModalCompany->company_email }}">Company — {{ $emailModalCompany->company_email }}</option>
                        @endif
                        @foreach($customersWithEmail as $cust)
                            <option value="{{ $cust->email }}">{{ $cust->name }} — {{ $cust->email }}</option>
                        @endforeach
                    </select>
                    <p class="text-xs text-gray-500 mt-1">Company email and all customers with a saved email address.</p>
                </div>

                <!-- Also Send To (CC Emails) -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Also Send To
                        <span class="text-xs font-normal text-gray-500 block">CC (optional, separate with commas)</span>
                    </label>
                    <div class="flex flex-col sm:flex-row sm:items-start gap-2">
                        <input type="text" id="email-cc" name="cc_emails" autocomplete="off" placeholder="cc1@example.com, cc2@example.com" class="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-gray-900 bg-white">
                        <a href="#" class="text-sm text-primary hover:underline whitespace-nowrap sm:pt-2" onclick="return false;">Save CC for Client</a>
                    </div>
                </div>

                <!-- Email Subject -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">Email Subject</label>
                    <input type="text" id="email-subject" name="subject" required class="w-full px-4 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-black" style="color: rgba(0, 0, 0, 1) !important;">
                </div>

                <!-- Message -->
                <div>
                    <div class="flex items-center justify-between mb-2">
                        <label class="block text-sm font-medium text-gray-700">Message</label>
                        <a href="#" id="preview-message" class="text-sm text-primary hover:underline">See Preview</a>
                    </div>
                    <textarea id="email-message" name="message" rows="12" required class="w-full px-4 py-2 border-2 border-primary rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-black resize-y" style="color: rgba(0, 0, 0, 1) !important;"></textarea>
                </div>

                <!-- Email Options -->
                <div class="space-y-3 border-t border-gray-200 pt-4">
                    <div class="flex items-start gap-2 text-sm text-gray-600">
                        <span class="material-symbols-outlined text-base">attach_file</span>
                        <span id="email-attachment-info">Payment receipt as a PDF and Online Link will be automatically attached with the email.</span>
                    </div>
                    
                    <label class="flex items-center gap-3 cursor-pointer">
                        <input type="checkbox" id="attach-statement" name="attach_statement" value="1" class="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary">
                        <span class="text-sm text-gray-700">Attach Client Statement</span>
                    </label>
                    
                    <label class="flex items-center gap-3 cursor-pointer">
                        <input type="checkbox" id="email-status" name="email_status" value="1" class="w-4 h-4 text-primary border-gray-300 rounded focus:ring-primary">
                        <span class="flex items-center gap-2 text-sm text-gray-700">
                            Get Email Status
                            <span class="w-2 h-2 bg-red-500 rounded-full"></span>
                        </span>
                    </label>

                    <!-- Text Type Selection -->
                    <div class="flex items-center gap-4 pt-2">
                        <span class="text-sm font-medium text-gray-700">Select text type:</span>
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="text_type" value="rich" checked class="w-4 h-4 text-primary border-gray-300 focus:ring-primary">
                            <span class="text-sm text-gray-700">Rich Text</span>
                        </label>
                        <label class="flex items-center gap-2 cursor-pointer">
                            <input type="radio" name="text_type" value="plain" class="w-4 h-4 text-primary border-gray-300 focus:ring-primary">
                            <span class="text-sm text-gray-700">Plain Text</span>
                        </label>
                    </div>
                </div>

                <!-- Actions -->
                <div class="flex gap-3 pt-4 border-t border-gray-200">
                    <button type="submit" id="email-modal-submit-btn" class="flex-1 px-6 py-3 text-sm font-medium text-white bg-primary rounded-lg hover:bg-blue-600 transition-colors">
                        Send Email
                    </button>
                    <button type="button" id="schedule-email-btn" class="flex-1 px-6 py-3 text-sm font-medium text-primary bg-white border-2 border-primary rounded-lg hover:bg-gray-50 transition-colors flex items-center justify-center gap-2">
                        <span class="w-2 h-2 bg-red-500 rounded-full"></span>
                        Schedule for later
                    </button>
                    <button type="button" onclick="closeEmailModal()" class="flex-1 px-6 py-3 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                        Cancel
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
h1.text-2xl {
    font-size: 25px !important;
}

p.text-gray-500 {
    font-size: 18px !important;
}

/* WhatsApp PDF modal: override rule above (16px subtitle, 600 weight, 13px helper) */
#whatsapp-pdf-modal .relative.bg-white.rounded-xl > div.flex.items-start.justify-between p.text-gray-500 {
    font-size: 16px !important;
    font-weight: 600 !important;
}

#whatsapp-pdf-modal #whatsapp-pdf-form p.leading-relaxed.text-gray-500 {
    font-size: 13px !important;
}

/* Invoice preview: fluid width (templates may define max-width) */
.invoice-main-container {
    width: 100%;
    max-width: 100%;
}

.print-container {
    width: 100%;
    max-width: 100%;
    margin: 0 auto;
}

/* Action button labels font size */
.grid.grid-cols-5 span.text-xs.font-medium.text-gray-900 {
    font-size: 14px !important;
}

/* Print Invoice button label font size */
button[title="Print Invoice"] span.text-base.font-medium.text-gray-900 {
    font-size: 16px !important;
}

/* Email input field text color */
#email-input-field {
    color: rgba(0, 0, 0, 1) !important;
}

/* Email composer styling */
#email-reply-to {
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3E%3C/svg%3E");
    background-position: right 0.5rem center;
    background-repeat: no-repeat;
    background-size: 1.5em 1.5em;
    padding-right: 2.5rem;
    color: rgba(0, 0, 0, 1) !important;
}

#email-cc {
    color: rgba(0, 0, 0, 1) !important;
}

#email-reply-to option {
    color: rgba(0, 0, 0, 1) !important;
    background-color: white;
}

/* Ensure email subject and message text are black */
#email-subject,
#email-message {
    color: rgba(0, 0, 0, 1) !important;
}

@media print {
    @page {
        size: A4 portrait;
        margin: 10mm;
    }

    /* Print backgrounds & brand colors (otherwise Chrome shows B/W preview) */
    html, body,
    .print-container,
    .print-container * {
        -webkit-print-color-adjust: exact !important;
        print-color-adjust: exact !important;
    }

    html, body {
        height: auto !important;
        min-height: 0 !important;
        overflow: visible !important;
        background: #fff !important;
        color: #111 !important;
    }

    body * {
        visibility: visible !important;
    }

    #sidebar,
    #sidebar-overlay,
    header,
    .no-print {
        display: none !important;
    }

    .min-h-screen.flex {
        display: block !important;
        min-height: 0 !important;
        height: auto !important;
        overflow: visible !important;
        background: #fff !important;
    }

    #main-content {
        display: block !important;
        width: 100% !important;
        max-width: none !important;
        min-height: 0 !important;
        height: auto !important;
        overflow: visible !important;
        margin: 0 !important;
        padding: 0 !important;
        background: #fff !important;
    }

    #main-content > main {
        display: block !important;
        width: 100% !important;
        max-width: none !important;
        padding: 0 !important;
        margin: 0 !important;
        overflow: visible !important;
        height: auto !important;
        flex: none !important;
    }

    .flex-1.overflow-y-auto.overflow-x-hidden,
    .max-w-7xl {
        max-width: none !important;
        width: 100% !important;
        padding: 0 !important;
        margin: 0 !important;
        overflow: visible !important;
    }

    .invoice-main-container {
        width: 100% !important;
        max-width: none !important;
        box-shadow: none !important;
        border: none !important;
        border-radius: 0 !important;
        padding: 0 !important;
        margin: 0 !important;
        overflow: visible !important;
    }

    .print-container {
        width: 100% !important;
        max-width: 190mm !important;
        margin: 0 auto !important;
        padding: 0 !important;
        overflow: visible !important;
        position: static !important;
        left: auto !important;
        top: auto !important;
        box-sizing: border-box !important;
    }

    /* Nested invoice HTML templates use their own .invoice-container */
    .print-container .invoice-container {
        max-width: 100% !important;
        width: 100% !important;
        margin: 0 auto !important;
        box-sizing: border-box !important;
    }

    /* Bold / fixed-pixel templates: fit printable A4 width (~190mm content) */
    .print-container .header-full,
    .print-container .content {
        width: 100% !important;
        max-width: 100% !important;
        box-sizing: border-box !important;
    }
}
</style>

<script>
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: JSON.stringify(body),
    };
}

// Mark as Paid Modal
function openMarkPaidModal(invoiceId) {
    fetch(`/admin/invoices/${invoiceId}/data`, {
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('mark-paid-invoice-id').value = invoiceId;
            document.getElementById('mark-paid-invoice-number').textContent = data.invoice_number;
            document.getElementById('mark-paid-customer-name').textContent = data.customer_name;
            document.getElementById('mark-paid-invoice-total').textContent = data.currency + ' ' + parseFloat(data.total).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
            document.getElementById('amount-received').value = data.balance;
            document.getElementById('amount-received').max = data.balance;
            document.getElementById('mark-paid-form').action = `/admin/invoices/${invoiceId}/mark-paid`;
            updateAmountToSettle();
            // Attach event listener when modal opens
            const amountInput = document.getElementById('amount-received');
            if (amountInput) {
                amountInput.removeEventListener('input', updateAmountToSettle);
                amountInput.addEventListener('input', updateAmountToSettle);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error loading invoice data');
        });
    document.getElementById('mark-paid-modal').classList.remove('hidden');
}

function closeMarkPaidModal() {
    document.getElementById('mark-paid-modal').classList.add('hidden');
}

function updateAmountToSettle() {
    const amount = parseFloat(document.getElementById('amount-received').value) || 0;
    const currency = document.getElementById('mark-paid-invoice-total').textContent.split(' ')[0] || '₦';
    document.getElementById('amount-to-settle').textContent = currency + ' ' + amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
}


// Email Modal
function openEmailModal(invoiceId, isReceipt = false) {
    fetch(`/admin/invoices/${invoiceId}/data`, {
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('email-modal-invoice-id').value = invoiceId;
            document.getElementById('email-modal-is-receipt').value = isReceipt ? '1' : '0';
            
            // Set client name
            document.getElementById('email-client-name').value = data.customer_name || '';
            
            // Set primary email address
            document.getElementById('email-primary-address').value = data.customer_email || '';
            
            // Set email subject
            const subject = isReceipt 
                ? `Payment Receipt for #${data.invoice_number}, billed to ${data.customer_name || ''}`
                : `Invoice #${data.invoice_number} from ${data.company_name || ''}`;
            document.getElementById('email-subject').value = subject;
            
            // Set default message
            const invoiceDate = data.issue_date ? new Date(data.issue_date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : '';
            const dueDate = data.due_date ? new Date(data.due_date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) : '';
            const paymentDate = new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
            
            let message = '';
            if (isReceipt) {
                message = `Hi ${data.customer_name || ''},\n\nThank You for the payment.\nThis is an acknowledgment of Payment received against Invoice #${data.invoice_number}.\n\nInvoice No: #${data.invoice_number}\nInvoice Date: ${invoiceDate}\nBilled To: ${data.customer_name || ''}\nDue Date: ${dueDate}\nInvoice Amount: ${data.currency || '₦'} ${parseFloat(data.total || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\nAmount Received: ${data.currency || '₦'} ${parseFloat(data.paid_amount || data.total || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\nTotal: ${data.currency || '₦'} ${parseFloat(data.total || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\nPayment Date: ${paymentDate}`;
                document.getElementById('email-attachment-info').textContent = 'Payment receipt as a PDF and Online Link will be automatically attached with the email.';
            } else {
                message = `Hi ${data.customer_name || ''},\n\nPlease find attached invoice #${data.invoice_number}.\n\nInvoice Details:\nInvoice No: #${data.invoice_number}\nInvoice Date: ${invoiceDate}\nDue Date: ${dueDate}\nAmount: ${data.currency || '₦'} ${parseFloat(data.total || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2})}\n\nPlease make payment by the due date.\n\nThank you!`;
                document.getElementById('email-attachment-info').textContent = 'Invoice as a PDF and Online Link will be automatically attached with the email.';
            }
            document.getElementById('email-message').value = message;

            const replySel = document.getElementById('email-reply-to');
            if (replySel && data.customer_email) {
                const match = [...replySel.options].some(o => o.value === data.customer_email);
                replySel.value = match ? data.customer_email : replySel.value;
            }
            
            // Update modal title
            const modalTitle = document.getElementById('email-modal-title');
            modalTitle.textContent = isReceipt ? 'Email Receipt' : 'Email Invoice';
            
            document.getElementById('email-modal').classList.remove('hidden');
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('email-modal-invoice-id').value = invoiceId;
            document.getElementById('email-modal-is-receipt').value = isReceipt ? '1' : '0';
            document.getElementById('email-modal').classList.remove('hidden');
        });
}

function closeEmailModal() {
    document.getElementById('email-modal').classList.add('hidden');
}

// Handle email form submission
document.getElementById('email-send-form')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const invoiceId = document.getElementById('email-modal-invoice-id').value;
    const clientName = document.getElementById('email-client-name').value;
    const recipientEmail = (document.getElementById('email-primary-address').value || '').trim();
    const replyTo = document.getElementById('email-reply-to').value;
    const ccRaw = document.getElementById('email-cc')?.value || '';
    const ccEmails = ccRaw.split(/[,;\n]/).map(s => s.trim()).filter(Boolean);
    const subject = document.getElementById('email-subject').value;
    const message = document.getElementById('email-message').value;
    const attachStatement = document.getElementById('attach-statement').checked;
    const emailStatus = document.getElementById('email-status').checked;
    const textType = document.querySelector('input[name="text_type"]:checked')?.value || 'rich';
    
    const submitButton = this.querySelector('button[type="submit"]');
    const originalText = submitButton.innerHTML;
    
    if (!recipientEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(recipientEmail)) {
        alert('Please enter a valid recipient email address');
        return;
    }

    if (!subject || !message) {
        alert('Please fill in all required fields');
        return;
    }
    
    submitButton.disabled = true;
    submitButton.innerHTML = '<span class="material-symbols-outlined animate-spin">sync</span> Sending...';
    
    const isReceipt = document.getElementById('email-modal-is-receipt').value === '1';
    
    try {
        const response = await fetch(`/admin/invoices/${invoiceId}/send-email`, adminJsonFetchInit({
                email: recipientEmail,
                reply_to: replyTo,
                cc_emails: ccEmails,
                subject: subject,
                message: message,
                attach_statement: attachStatement,
                email_status: emailStatus,
                text_type: textType,
                receipt: isReceipt,
            }));

        if (response.status === 419) {
            alert('Your session or security token expired. Please refresh the page and try again.');
            return;
        }

        const data = await response.json().catch(() => ({}));
        if (data.success) {
            closeEmailModal();
            const message = isReceipt 
                ? 'Receipt sent successfully' 
                : 'Invoice sent successfully';
            showSuccessModal(message);
        } else {
            alert(data.message || 'Failed to send email');
        }
    } catch (error) {
        console.error('Error sending email:', error);
        alert('Error sending email: ' + error.message);
    } finally {
        submitButton.disabled = false;
        submitButton.innerHTML = originalText;
    }
});

// Schedule email button handler
document.getElementById('schedule-email-btn')?.addEventListener('click', function() {
    alert('Schedule email feature coming soon!');
});

function openWhatsAppLinkModal(invoiceId) {
    document.getElementById('whatsapp-link-invoice-id').value = invoiceId;
    document.getElementById('whatsapp-link-customer-phone').value = '{{ $customer->phone ?? '' }}';
    document.getElementById('whatsapp-link-modal').classList.remove('hidden');
}

function closeWhatsAppLinkModal() {
    document.getElementById('whatsapp-link-modal').classList.add('hidden');
}

// Send invoice link via WhatsApp Web/App
async function sendWhatsApp(invoiceId, customerPhone) {
    try {
        const response = await fetch(`/admin/invoices/${invoiceId}/share-link`, {
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
            },
        });
        const data = await response.json();
        if (data.success) {
            // Put the URL on its own line — WhatsApp auto-links https:// URLs on real domains.
            // Local http://127.0.0.1 or localhost often stays plain text; set INVOICE_PUBLIC_BASE_URL in .env to your public HTTPS URL (e.g. ngrok).
            const message = encodeURIComponent(`Invoice {{ $invoice->invoice_number }}\n\nView:\n\n${data.link}`);
            const phone = (customerPhone || '').replace(/[^0-9]/g, '');
            if (phone) {
                window.open(`https://wa.me/${phone}?text=${message}`, '_blank');
            } else {
                window.open(`https://wa.me/?text=${message}`, '_blank');
            }
        }
    } catch (error) {
        console.error('Error generating WhatsApp link:', error);
        alert('Error generating WhatsApp link');
    }
}

document.getElementById('whatsapp-link-form')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const invoiceId = document.getElementById('whatsapp-link-invoice-id').value;
    const customerPhone = document.getElementById('whatsapp-link-customer-phone').value.trim();

    if (!customerPhone) {
        alert('Please enter customer WhatsApp number.');
        return;
    }

    await sendWhatsApp(invoiceId, customerPhone);
    closeWhatsAppLinkModal();
});

function openWhatsAppPdfModal(invoiceId) {
    const modal = document.getElementById('whatsapp-pdf-modal');
    if (!modal) return;
    document.getElementById('whatsapp-pdf-invoice-id').value = invoiceId;
    const input = document.getElementById('whatsapp-pdf-customer-phone');
    if (input) {
        input.value = '{{ $customer->phone ?? "" }}'.trim();
        input.focus();
    }
    const submit = document.getElementById('whatsapp-pdf-submit');
    const label = document.getElementById('whatsapp-pdf-submit-label');
    if (submit) submit.disabled = false;
    if (label) label.textContent = 'Send PDF';
    modal.classList.remove('hidden');
}

function closeWhatsAppPdfModal() {
    document.getElementById('whatsapp-pdf-modal')?.classList.add('hidden');
}

document.getElementById('whatsapp-pdf-form')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    const invoiceId = document.getElementById('whatsapp-pdf-invoice-id').value;
    const normalizedPhone = document.getElementById('whatsapp-pdf-customer-phone').value.trim();

    if (!normalizedPhone) {
        alert('Please enter the customer WhatsApp number.');
        return;
    }

    const submit = document.getElementById('whatsapp-pdf-submit');
    const label = document.getElementById('whatsapp-pdf-submit-label');
    const originalLabel = label ? label.textContent : 'Send PDF';
    if (submit) submit.disabled = true;
    if (label) label.textContent = 'Sending…';

    try {
        const response = await fetch(`/admin/invoices/${invoiceId}/send-whatsapp`, adminJsonFetchInit({
            phone: normalizedPhone,
        }));

        const data = await response.json().catch(() => ({}));
        if (response.ok && data.success) {
            closeWhatsAppPdfModal();
            showSuccessModal(data.message || 'Invoice PDF sent via WhatsApp successfully.');
            return;
        }

        alert(data.message || 'Failed to send invoice PDF via WhatsApp.');
    } catch (error) {
        console.error('Error sending WhatsApp PDF:', error);
        alert('Error sending invoice PDF via WhatsApp: ' + error.message);
    } finally {
        if (submit) submit.disabled = false;
        if (label) label.textContent = originalLabel;
    }
});

// Copy Invoice Link
async function copyInvoiceLink(invoiceId) {
    try {
        // Get the public URL directly from the invoice model
        const publicUrl = '{{ $invoice->getPublicUrl() }}';
        
        if (publicUrl) {
            await navigator.clipboard.writeText(publicUrl);
            showSuccessModal('Public invoice link copied to clipboard!');
        } else {
            // Fallback to old method if public URL is not available
            const response = await fetch(`/admin/invoices/${invoiceId}/share-link`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-TOKEN': getAdminCsrfToken(),
                },
                credentials: 'same-origin'
            });
            
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `HTTP error! status: ${response.status}`);
            }
            
            const data = await response.json();
            if (data.success && data.link) {
                await navigator.clipboard.writeText(data.link);
                showSuccessModal('Invoice link copied to clipboard!');
            } else {
                alert(data.message || 'Failed to generate share link');
            }
        }
    } catch (error) {
        console.error('Error copying link:', error);
        alert('Error copying link: ' + error.message);
    }
}

// Success Modal
function showSuccessModal(message) {
    const modal = document.getElementById('success-modal');
    const messageEl = document.getElementById('success-message');
    if (modal && messageEl) {
        messageEl.textContent = message;
        modal.classList.remove('hidden');
        setTimeout(() => {
            modal.classList.add('hidden');
        }, 3000);
    } else {
        alert(message);
    }
}

function closeSuccessModal() {
    document.getElementById('success-modal').classList.add('hidden');
}

// Print Invoice — use the current page so template CSS (and images) apply; @media print rules hide chrome
function printInvoice() {
    window.print();
}
</script>

<!-- Success Modal -->
<div id="success-modal" data-admin-modal class="hidden fixed inset-0 z-50 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="closeSuccessModal()"></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">
                    <h3 class="text-lg font-bold text-gray-900">Success</h3>
                    <p id="success-message" class="text-sm text-gray-500 mt-1"></p>
                </div>
                <button onclick="closeSuccessModal()" class="text-gray-400 hover:text-gray-600">
                    <span class="material-symbols-outlined">close</span>
                </button>
            </div>
            <button onclick="closeSuccessModal()" class="w-full px-4 py-2 text-sm font-medium text-white bg-primary rounded-lg hover:bg-blue-600 transition-colors">
                OK
            </button>
        </div>
    </div>
</div>
@endsection
