@extends('layouts.app')
@section('title', $invoice->number)

@section('content')
<div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-3">
    <div>
        <h1 class="h4 fw-bold mb-0" dir="ltr">🧾 {{ $invoice->number }}</h1>
        <span class="mb-muted small">
            <a href="{{ route('tenant.patients.show', $invoice->patient) }}">{{ $invoice->patient->full_name }}</a>
            @if($invoice->treatmentPlan)
                · <a href="{{ route('tenant.treatment-plans.show', $invoice->treatmentPlan) }}">{{ $invoice->treatmentPlan->title }}</a>
            @endif
        </span>
    </div>
    <div class="d-flex gap-2 align-items-center">
        <span class="status-chip" style="background: {{ $invoice->status->color() }}">{{ $invoice->status->label() }}</span>
        <a class="btn btn-sm mb-btn-ghost" target="_blank" href="{{ route('tenant.invoices.pdf', $invoice) }}">📄 PDF</a>
        @if($invoice->patient->whatsapp_opt_in && $invoice->status !== \App\Enums\InvoiceStatus::Draft)
        @can('update', $invoice)
            <form method="POST" action="{{ route('tenant.invoices.send-whatsapp', $invoice) }}">
                @csrf <button class="btn btn-sm mb-btn-ghost">💬 {{ __('Send on WhatsApp') }}</button>
            </form>
        @endcan
        @endif
    </div>
</div>

@if($invoice->status === \App\Enums\InvoiceStatus::Draft)
@can('update', $invoice)
<div class="mb-card p-3 mb-3 d-flex flex-wrap gap-2 align-items-center">
    <form method="POST" action="{{ route('tenant.invoices.issue', $invoice) }}" class="d-flex gap-2 align-items-center">
        @csrf
        <label class="small mb-muted">{{ __('Due date') }}</label>
        <input type="date" name="due_date" class="form-control form-control-sm" min="{{ today()->toDateString() }}">
        <button class="btn mb-btn-primary btn-sm">{{ __('Issue invoice') }}</button>
    </form>
    <form method="POST" action="{{ route('tenant.invoices.void', $invoice) }}"
          onsubmit="return confirm('{{ __('Void this invoice?') }}')">
        @csrf
        <button class="btn mb-btn-ghost btn-sm">{{ __('Void') }}</button>
    </form>
</div>
@endcan
@endif

<div class="row g-3">
    <div class="col-lg-7">
        {{-- Items --}}
        <div class="mb-card p-3 mb-3">
            <table class="table mb-table align-middle mb-0">
                <thead><tr><th>{{ __('Description') }}</th><th>{{ __('Tooth') }}</th><th>{{ __('Qty') }}</th><th>{{ __('Amount') }}</th></tr></thead>
                <tbody>
                @foreach($invoice->items as $item)
                    <tr>
                        <td>{{ $item->description }}</td>
                        <td>{{ $item->tooth ?? '—' }}</td>
                        <td>{{ $item->qty }}</td>
                        <td dir="ltr">{{ number_format($item->amount) }}</td>
                    </tr>
                @endforeach
                </tbody>
                <tfoot>
                    <tr><td colspan="3" class="text-end mb-muted">{{ __('Subtotal') }}</td><td dir="ltr">{{ number_format($invoice->subtotal) }}</td></tr>
                    <tr><td colspan="3" class="text-end mb-muted">{{ __('Discount') }}</td><td dir="ltr">− {{ number_format($invoice->discount_amount) }}</td></tr>
                    <tr class="fw-bold"><td colspan="3" class="text-end">{{ __('Total') }}</td><td dir="ltr">{{ number_format($invoice->total) }}</td></tr>
                    <tr><td colspan="3" class="text-end text-success">{{ __('Paid') }}</td><td dir="ltr" class="text-success">{{ number_format($invoice->paid_amount) }}</td></tr>
                    <tr class="fw-bold"><td colspan="3" class="text-end {{ $invoice->remaining() ? 'text-danger' : '' }}">{{ __('Remaining') }}</td>
                        <td dir="ltr" class="{{ $invoice->remaining() ? 'text-danger' : '' }}">{{ number_format($invoice->remaining()) }}</td></tr>
                </tfoot>
            </table>
        </div>

        {{-- Payment history --}}
        <div class="mb-card p-3">
            <h2 class="h6 fw-semibold px-2 pt-2">{{ __('Payments') }}</h2>
            <table class="table mb-table align-middle mb-0">
                <tbody>
                @forelse($invoice->payments as $p)
                    <tr>
                        <td>{{ $p->method->icon() }} {{ $p->method->label() }}
                            @if($p->reference)<span class="mb-muted small" dir="ltr">#{{ $p->reference }}</span>@endif
                        </td>
                        <td dir="ltr" class="text-success fw-semibold">{{ number_format($p->amount) }}</td>
                        <td class="mb-muted small">{{ $p->paid_at->setTimezone(\App\Support\ClinicTime::timezone())->format('d M Y · H:i') }}</td>
                        <td class="mb-muted small">{{ $p->receiver?->name }}</td>
                    </tr>
                @empty
                    <tr><td class="mb-muted py-3 text-center">{{ __('No payments yet.') }}</td></tr>
                @endforelse
                </tbody>
            </table>
        </div>
    </div>

    <div class="col-lg-5">
        {{-- Quick payment --}}
        @if($invoice->status->isOpen())
        @can('recordPayment', $invoice)
        <div class="mb-card p-4 mb-3" style="border-color: var(--mb-primary)">
            <h2 class="h6 fw-semibold mb-2">⚡ {{ __('Quick payment') }}</h2>
            <p class="mb-muted small">{{ __('Amount is prefilled with the remaining balance — tap a method to record.') }}</p>
            @include('invoices._quickpay', ['invoice' => $invoice, 'methods' => $methods])
        </div>
        @endcan
        @endif

        {{-- Installments --}}
        <div class="mb-card p-4">
            <h2 class="h6 fw-semibold mb-3">💰 {{ __('Installments') }}</h2>

            @if($invoice->installments->isEmpty())
                @if($invoice->status->isOpen() && $invoice->remaining() > 0)
                @can('installments.manage')
                <form method="POST" action="{{ route('tenant.invoices.installments.store', $invoice) }}">
                    @csrf
                    <div class="row g-2">
                        <div class="col-4">
                            <label class="form-label small">{{ __('Months') }}</label>
                            <input type="number" name="months" value="6" min="1" max="36" class="form-control form-control-sm" id="instMonths">
                        </div>
                        <div class="col-8">
                            <label class="form-label small">{{ __('Down payment (IQD)') }}</label>
                            <input type="number" name="down_payment" value="0" min="0" step="250"
                                   max="{{ $invoice->remaining() - 250 }}" class="form-control form-control-sm" id="instDown">
                        </div>
                        <div class="col-7">
                            <label class="form-label small">{{ __('First installment due') }}</label>
                            <input type="date" name="first_due_date" class="form-control form-control-sm"
                                   min="{{ today()->toDateString() }}" value="{{ today()->addMonth()->toDateString() }}">
                        </div>
                        <div class="col-5 d-flex align-items-end">
                            <button class="btn mb-btn-primary btn-sm w-100">{{ __('Create schedule') }}</button>
                        </div>
                    </div>
                    <p class="mb-muted small mt-2 mb-0" id="instPreview" dir="auto"></p>
                </form>
                @endcan
                @else
                    <p class="mb-muted small mb-0">—</p>
                @endif
            @else
                <table class="table mb-table table-sm align-middle mb-0">
                    <tbody>
                    @foreach($invoice->installments as $inst)
                        <tr class="{{ $inst->isOverdue() ? 'table-danger' : '' }}">
                            <td class="mb-muted">{{ $inst->seq === 0 ? __('Down') : '#'.$inst->seq }}</td>
                            <td>{{ $inst->due_date->format('d M Y') }}
                                @if($inst->isOverdue())<span class="badge text-bg-danger">{{ __('Overdue') }}</span>@endif
                            </td>
                            <td dir="ltr">{{ number_format($inst->paid_amount) }}/{{ number_format($inst->amount) }}</td>
                            <td>
                                <span class="badge text-bg-{{ match($inst->status) {
                                    \App\Enums\InstallmentStatus::Paid => 'success',
                                    \App\Enums\InstallmentStatus::Partial => 'warning',
                                    default => 'secondary' } }}">{{ $inst->status->label() }}</span>
                            </td>
                        </tr>
                        @if($inst->remaining() > 0 && $invoice->status->isOpen())
                        @can('recordPayment', $invoice)
                        <tr><td colspan="4" class="pt-0">
                            @include('invoices._quickpay', ['invoice' => $invoice, 'installment' => $inst, 'methods' => $methods])
                        </td></tr>
                        @endcan
                        @endif
                    @endforeach
                    </tbody>
                </table>
            @endif
        </div>
    </div>
</div>

@push('page-scripts')
<script>
// Live installment preview: "6 × 125,000 IQD"
const months = document.getElementById('instMonths');
const down = document.getElementById('instDown');
const preview = document.getElementById('instPreview');
const remaining = {{ $invoice->remaining() }};
function instPreview() {
    if (!months || !preview) return;
    const m = Math.max(1, parseInt(months.value || 1));
    const d = Math.max(0, parseInt(down.value || 0));
    const financed = remaining - d;
    if (financed <= 0) { preview.textContent = ''; return; }
    const per = Math.max(250, Math.floor(financed / m / 250) * 250);
    const last = financed - per * (m - 1);
    preview.textContent = `≈ ${m} × ${per.toLocaleString()} IQD` + (last !== per ? ` ({{ __('last') }}: ${last.toLocaleString()})` : '');
}
months?.addEventListener('input', instPreview);
down?.addEventListener('input', instPreview);
instPreview();
</script>
@endpush
@endsection
