@extends('layouts.admin')

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

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

@section('breadcrumbs')
    <a href="{{ route('admin.invoices.index') }}" class="hover:text-primary">Invoices</a>
    <span class="material-symbols-outlined text-xs">chevron_right</span>
    <span class="text-primary font-medium">{{ $invoice->invoice_number }}</span>
@endsection

@section('header-actions')
    <div class="flex items-center gap-3">
        @if($invoice->status === 'paid' && $invoice->receipt)
            <a href="{{ route('admin.receipts.show', $invoice->receipt) }}" class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors flex items-center gap-2">
                <span class="material-symbols-outlined text-lg">receipt</span>
                <span>View Receipt</span>
            </a>
        @elseif($invoice->status === 'paid' && !$invoice->receipt)
            <form method="POST" action="{{ route('admin.receipts.store') }}" class="inline">
                @csrf
                <input type="hidden" name="invoice_id" value="{{ $invoice->id }}">
                <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-blue-600 transition-colors flex items-center gap-2">
                    <span class="material-symbols-outlined text-lg">receipt</span>
                    <span>Create Receipt</span>
                </button>
            </form>
        @endif
        <a href="{{ route('admin.invoices.download', $invoice) }}" target="_blank" rel="noopener noreferrer" class="px-4 py-2 border border-[#dbe0e6] text-[#617589] rounded-lg hover:bg-background-light transition-colors flex items-center gap-2">
            <span class="material-symbols-outlined text-lg">download</span>
            <span>Download PDF</span>
        </a>
        <a href="{{ route('admin.invoices.edit', $invoice) }}" class="px-4 py-2 border border-[#dbe0e6] text-[#617589] rounded-lg hover:bg-background-light transition-colors flex items-center gap-2">
            <span class="material-symbols-outlined text-lg">edit</span>
            <span>Edit</span>
        </a>
        {{-- Send Invoice functionality is available via the email modal in the view page --}}
    </div>
@endsection

@section('content')
<div class="max-w-5xl mx-auto flex flex-col gap-6">
    <!-- Invoice Header -->
    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <div class="flex justify-between items-start mb-6">
            <div>
                <h2 class="text-2xl font-bold text-[#111418] text-gray-900 mb-2">{{ $invoice->invoice_number }}</h2>
                <div class="flex items-center gap-4 text-sm text-[#617589]">
                    <span>Issue Date: {{ $invoice->issue_date->format('M d, Y') }}</span>
                    <span>Due Date: {{ $invoice->due_date->format('M d, Y') }}</span>
                </div>
            </div>
            <div class="text-right">
                @php
                    $statusColors = [
                        'draft' => 'bg-gray-100 text-gray-800',
                        'sent' => 'bg-blue-100 text-blue-800',
                        'viewed' => 'bg-purple-100 text-purple-800',
                        'partial' => 'bg-yellow-100 text-yellow-800',
                        'paid' => 'bg-green-100 text-green-800',
                        'overdue' => 'bg-red-100 text-red-800',
                        'cancelled' => 'bg-gray-100 text-gray-800',
                    ];
                    $color = $statusColors[$invoice->status] ?? 'bg-gray-100 text-gray-800';
                @endphp
                <span class="px-3 py-1 rounded-lg text-sm font-medium {{ $color }}">
                    {{ ucfirst($invoice->status) }}
                </span>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <p class="text-xs font-semibold text-[#617589] uppercase tracking-wider mb-2">Billed To</p>
                <div class="text-sm text-[#111418] text-gray-900">
                    <p class="font-semibold">{{ $invoice->customer->name }}</p>
                    @if($invoice->customer->email)
                        <p class="text-[#617589]">{{ $invoice->customer->email }}</p>
                    @endif
                    @if($invoice->customer->address)
                        <p class="text-[#617589]">{{ $invoice->customer->address }}</p>
                    @endif
                </div>
            </div>
            <div>
                <p class="text-xs font-semibold text-[#617589] uppercase tracking-wider mb-2">Payment Summary</p>
                <div class="text-sm space-y-1">
                    <div class="flex justify-between">
                        <span class="text-[#617589]">Total Amount:</span>
                        <span class="font-medium text-[#111418] text-gray-900">{{ $invoice->currency }} {{ number_format($invoice->total, 2) }}</span>
                    </div>
                    <div class="flex justify-between">
                        <span class="text-[#617589]">Paid Amount:</span>
                        <span class="font-medium text-green-600">{{ \App\Models\Currency::formatAmount($invoice->paid_amount, $invoice->currency) }}</span>
                    </div>
                    <div class="flex justify-between pt-2 border-t border-[#e5e7eb]">
                        <span class="font-semibold text-[#111418] text-gray-900">Balance Due:</span>
                        <span class="font-bold text-lg {{ $invoice->balance > 0 ? 'text-red-600' : 'text-green-600' }}">
                            {{ \App\Models\Currency::formatAmount($invoice->balance, $invoice->currency) }}
                        </span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Invoice Items -->
    <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
        <h3 class="text-lg font-bold text-[#111418] text-gray-900 mb-6">Invoice Items</h3>
        <div class="overflow-x-auto">
            <table class="w-full text-left">
                <thead class="bg-background-light border-b border-[#e5e7eb]">
                    <tr>
                        <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider">Description</th>
                        <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Quantity</th>
                        <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Unit Price</th>
                        <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Tax Rate</th>
                        <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Amount</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-[#e5e7eb]">
                    @foreach($invoice->items as $item)
                        <tr>
                            <td class="py-4 px-4 text-sm text-[#111418] text-gray-900">{{ $item->description }}</td>
                            <td class="py-4 px-4 text-sm text-[#617589] text-right">{{ number_format($item->quantity, 2) }}</td>
                            <td class="py-4 px-4 text-sm text-[#617589] text-right">{{ $invoice->currency }} {{ number_format($item->unit_price, 2) }}</td>
                            <td class="py-4 px-4 text-sm text-[#617589] text-right">{{ number_format($item->tax_rate, 2) }}%</td>
                            <td class="py-4 px-4 text-sm font-medium text-[#111418] text-gray-900 text-right">{{ $invoice->currency }} {{ number_format($item->total, 2) }}</td>
                        </tr>
                    @endforeach
                </tbody>
                <tfoot class="bg-background-light">
                    <tr>
                        <td colspan="4" class="py-4 px-4 text-sm font-semibold text-[#111418] text-gray-900 text-right">Subtotal:</td>
                        <td class="py-4 px-4 text-sm font-semibold text-[#111418] text-gray-900 text-right">{{ $invoice->currency }} {{ number_format($invoice->subtotal, 2) }}</td>
                    </tr>
                    @if($invoice->tax_amount > 0)
                        <tr>
                            <td colspan="4" class="py-4 px-4 text-sm font-semibold text-[#111418] text-gray-900 text-right">Tax:</td>
                            <td class="py-4 px-4 text-sm font-semibold text-[#111418] text-gray-900 text-right">{{ \App\Models\Currency::formatAmount($invoice->tax_amount, $invoice->currency) }}</td>
                        </tr>
                    @endif
                    @if($invoice->discount_amount > 0)
                        <tr>
                            <td colspan="4" class="py-4 px-4 text-sm font-semibold text-[#111418] text-gray-900 text-right">Discount:</td>
                            <td class="py-4 px-4 text-sm font-semibold text-[#111418] text-gray-900 text-right">- {{ \App\Models\Currency::formatAmount($invoice->discount_amount, $invoice->currency) }}</td>
                        </tr>
                    @endif
                    <tr class="border-t-2 border-[#e5e7eb]">
                        <td colspan="4" class="py-4 px-4 text-lg font-bold text-[#111418] text-gray-900 text-right">Total:</td>
                        <td class="py-4 px-4 text-lg font-bold text-primary text-right">{{ $invoice->currency }} {{ number_format($invoice->total, 2) }}</td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <!-- Notes & Terms -->
    @if($invoice->notes || $invoice->terms)
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            @if($invoice->notes)
                <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
                    <h3 class="text-sm font-bold text-[#111418] text-gray-900 mb-4">Notes</h3>
                    <p class="text-sm text-[#617589] whitespace-pre-line">{{ $invoice->notes }}</p>
                </div>
            @endif
            @if($invoice->terms)
                <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
                    <h3 class="text-sm font-bold text-[#111418] text-gray-900 mb-4">Terms & Conditions</h3>
                    <p class="text-sm text-[#617589] whitespace-pre-line">{{ $invoice->terms }}</p>
                </div>
            @endif
        </div>
    @endif

    <!-- Payments -->
    @if($invoice->payments->count() > 0)
        <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
            <h3 class="text-lg font-bold text-[#111418] text-gray-900 mb-6">Payment History</h3>
            <div class="overflow-x-auto">
                <table class="w-full text-left">
                    <thead class="bg-background-light border-b border-[#e5e7eb]">
                        <tr>
                            <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider">Payment #</th>
                            <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider">Date</th>
                            <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider">Method</th>
                            <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider text-right">Amount</th>
                            <th class="py-3 px-4 text-xs font-semibold text-[#617589] uppercase tracking-wider">Status</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-[#e5e7eb]">
                        @foreach($invoice->payments as $payment)
                            <tr>
                                <td class="py-4 px-4 text-sm text-[#111418] text-gray-900">{{ $payment->payment_number }}</td>
                                <td class="py-4 px-4 text-sm text-[#617589]">{{ $payment->payment_date->format('M d, Y') }}</td>
                                <td class="py-4 px-4 text-sm text-[#617589]">{{ ucfirst(str_replace('_', ' ', $payment->payment_method)) }}</td>
                                <td class="py-4 px-4 text-sm font-medium text-[#111418] text-gray-900 text-right">{{ \App\Models\Currency::formatAmount($payment->amount, $payment->currency) }}</td>
                                <td class="py-4 px-4">
                                    <span class="px-2 py-1 rounded text-xs font-medium {{ $payment->status === 'completed' ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-800' }}">
                                        {{ ucfirst($payment->status) }}
                                    </span>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    @endif

    @if(auth()->user()->hasPermission('send_manual_reminders') || auth()->user()->hasRole(\App\Enums\RoleEnum::SUPER_ADMIN->value))
        <div class="bg-white rounded-xl shadow-sm border border-[#e5e7eb] p-6">
            <div class="flex flex-wrap items-center justify-between gap-3 mb-4">
                <h3 class="text-lg font-bold text-[#111418]">Billing reminders</h3>
                <button type="button" id="open-invoice-reminder-modal" class="px-4 py-2 rounded-lg bg-violet-600 text-white text-sm font-semibold hover:bg-violet-700">Send reminder</button>
            </div>
            <p class="text-sm text-[#617589] mb-3">Recent emails queued or sent for this invoice.</p>
            <div class="overflow-x-auto">
                <table class="w-full text-left text-sm">
                    <thead class="border-b border-[#e5e7eb] text-xs uppercase text-[#617589]">
                        <tr>
                            <th class="py-2 pr-4">Type</th>
                            <th class="py-2 pr-4">To</th>
                            <th class="py-2 pr-4">Status</th>
                            <th class="py-2">Sent</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-[#e5e7eb]">
                        @forelse($invoice->reminderLogs as $log)
                            <tr>
                                <td class="py-2 pr-4 font-medium text-[#111418]">{{ str_replace('_', ' ', $log->reminder_type) }}</td>
                                <td class="py-2 pr-4 text-[#617589]">{{ $log->recipient_email }}</td>
                                <td class="py-2 pr-4"><span class="px-2 py-0.5 rounded text-xs font-medium {{ $log->status === 'sent' ? 'bg-emerald-100 text-emerald-800' : ($log->status === 'failed' ? 'bg-rose-100 text-rose-800' : 'bg-slate-100 text-slate-700') }}">{{ $log->status }}</span></td>
                                <td class="py-2 text-[#617589]">{{ $log->sent_at?->format('M j, Y g:i A') ?? '—' }}</td>
                            </tr>
                        @empty
                            <tr><td colspan="4" class="py-6 text-center text-[#617589]">No reminder log entries yet.</td></tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>

        <div id="invoice-reminder-modal" class="fixed inset-0 z-50 hidden items-center justify-center bg-slate-900/50 p-4">
            <div class="bg-white rounded-xl shadow-xl max-w-lg w-full p-6 border border-[#e5e7eb]">
                <h4 class="text-lg font-bold text-[#111418] mb-4">Send reminder email</h4>
                <form id="invoice-reminder-form" class="space-y-4">
                    @csrf
                    <div>
                        <label class="block text-sm font-medium text-[#617589] mb-1">Recipient</label>
                        <input type="email" name="recipient_email" value="{{ $invoice->customer->email ?? '' }}" required class="w-full rounded-lg border border-[#dbe0e6] px-3 py-2 text-sm">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-[#617589] mb-1">Subject</label>
                        <input type="text" name="subject" value="Reminder: Invoice {{ $invoice->invoice_number }}" required class="w-full rounded-lg border border-[#dbe0e6] px-3 py-2 text-sm">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-[#617589] mb-1">Message (HTML allowed)</label>
                        <textarea name="body" rows="5" required class="w-full rounded-lg border border-[#dbe0e6] px-3 py-2 text-sm font-mono"><p>Dear {{ $invoice->customer->name ?? 'Customer' }},</p><p>This is a reminder regarding invoice <strong>{{ $invoice->invoice_number }}</strong>.</p><p>Thank you.</p></textarea>
                    </div>
                    <label class="flex items-center gap-2 text-sm text-[#617589]">
                        <input type="checkbox" name="as_follow_up" value="1" class="rounded border-gray-300 text-violet-600">
                        Log as follow-up reminder
                    </label>
                    <div class="flex gap-2 justify-end pt-2">
                        <button type="button" id="close-invoice-reminder-modal" class="px-4 py-2 rounded-lg border border-[#dbe0e6] text-sm font-semibold text-[#617589]">Cancel</button>
                        <button type="submit" class="px-4 py-2 rounded-lg bg-violet-600 text-white text-sm font-semibold">Send</button>
                    </div>
                </form>
                <p id="invoice-reminder-msg" class="mt-3 text-sm hidden"></p>
            </div>
        </div>
        @push('scripts')
        <script>
        (function () {
            var modal = document.getElementById('invoice-reminder-modal');
            var form = document.getElementById('invoice-reminder-form');
            var msg = document.getElementById('invoice-reminder-msg');
            if (!modal || !form) return;
            document.getElementById('open-invoice-reminder-modal')?.addEventListener('click', function () {
                modal.classList.remove('hidden');
                modal.classList.add('flex');
                msg.classList.add('hidden');
            });
            document.getElementById('close-invoice-reminder-modal')?.addEventListener('click', function () {
                modal.classList.add('hidden');
                modal.classList.remove('flex');
            });
            form.addEventListener('submit', function (e) {
                e.preventDefault();
                msg.classList.add('hidden');
                var fd = new FormData(form);
                fetch('{{ route('admin.invoices.send-reminder', $invoice) }}', {
                    method: 'POST',
                    headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
                    body: fd
                }).then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
                .then(function (x) {
                    msg.classList.remove('hidden');
                    msg.textContent = x.j.message || (x.ok ? 'Sent.' : 'Failed');
                    msg.className = 'mt-3 text-sm ' + (x.ok ? 'text-emerald-600' : 'text-rose-600');
                    if (x.ok) setTimeout(function () { location.reload(); }, 1200);
                }).catch(function () {
                    msg.classList.remove('hidden');
                    msg.textContent = 'Network error';
                    msg.className = 'mt-3 text-sm text-rose-600';
                });
            });
        })();
        </script>
        @endpush
    @endif
</div>
@endsection



