@extends('layouts.app')

@section('content')
@php
    $docLabel = match($invoice->document_type ?? 'invoice') {
        'quotation' => 'Quotation',
        'proforma'  => 'Proforma Invoice',
        default     => 'Tax Invoice'
    };
    $currSymbol = $invoice->currency?->symbol ?? '';
    $statusClass = match($invoice->status) {
        'paid'    => 'bg-success',
        'partial' => 'bg-info',
        'sent'    => 'bg-primary',
        'overdue' => 'bg-danger',
        'voided'  => 'bg-dark',
        'draft'   => 'bg-secondary',
        default   => 'bg-warning'
    };
@endphp

{{-- Page Header --}}
<div class="row">
    <div class="col-sm-12">
        <div class="page-title-box">
            <div class="row">
                <div class="col">
                    <h4 class="page-title">{{ $docLabel }}: {{ $invoice->invoice_number }}</h4>
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{{ route('finance.invoices.index') }}">Invoices</a></li>
                        <li class="breadcrumb-item active">{{ $invoice->invoice_number }}</li>
                    </ol>
                </div>
                <div class="col-auto align-self-center d-flex gap-1 flex-wrap">
                    @if(!in_array($invoice->status, ['paid', 'voided']))
                    <a href="{{ route('finance.invoices.edit', $invoice->id) }}" class="btn btn-sm btn-outline-secondary">
                        <i class="ti ti-edit me-1"></i>Edit
                    </a>
                    @endif
                    <a href="{{ route('finance.invoices.download', $invoice->id) }}" class="btn btn-sm btn-outline-dark" target="_blank">
                        <i class="ti ti-download me-1"></i>PDF
                    </a>
                    @if(!in_array($invoice->status, ['paid', 'voided']))
                    <a href="{{ route('finance.payments.create', ['invoice_id' => $invoice->id]) }}" class="btn btn-sm btn-success">
                        <i class="ti ti-cash me-1"></i>Record Payment
                    </a>
                    @endif
                    <div class="btn-group">
                        <button type="button" class="btn btn-sm btn-outline-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="ti ti-dots me-1"></i>More
                        </button>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a class="dropdown-item" href="javascript:void(0);" onclick="sendInvoice()">
                                <i class="ti ti-send me-2 text-primary"></i>Send by Email
                            </a>
                            <a class="dropdown-item" href="javascript:void(0);" onclick="duplicateInvoice()">
                                <i class="ti ti-copy me-2 text-info"></i>Duplicate
                            </a>
                            <a class="dropdown-item" href="{{ route('public.invoice.show', $invoice->public_hash) }}" target="_blank">
                                <i class="ti ti-external-link me-2 text-secondary"></i>Public Link
                            </a>
                            <div class="dropdown-divider"></div>
                            <span class="dropdown-item text-muted small px-3 py-1">Change Status</span>
                            @foreach(['draft','unpaid','sent','partial','paid','overdue','voided'] as $st)
                                @if($st !== $invoice->status)
                                <a class="dropdown-item" href="javascript:void(0);" onclick="changeStatus('{{ $st }}')">
                                    <i class="ti ti-circle-dot me-2"></i>Mark as {{ ucfirst($st) }}
                                </a>
                                @endif
                            @endforeach
                            @if(!in_array($invoice->status, ['voided']))
                            <div class="dropdown-divider"></div>
                            <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="voidInvoice()">
                                <i class="ti ti-ban me-2"></i>Void Invoice
                            </a>
                            @endif
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Status + Financials Bar --}}
<div class="row mb-3">
    <div class="col-12">
        <div class="card border-0 shadow-sm mb-0">
            <div class="card-body py-2 px-4">
                <div class="d-flex align-items-center justify-content-between flex-wrap gap-2">
                    <div class="d-flex align-items-center gap-2">
                        <span class="badge {{ $statusClass }} fs-6 px-3 py-2">{{ ucfirst($invoice->status) }}</span>
                        @if($invoice->due_date?->isPast() && !in_array($invoice->status, ['paid','voided']))
                            <span class="badge bg-danger-subtle text-danger border border-danger small">
                                <i class="ti ti-alert-circle me-1"></i>Overdue by {{ $invoice->due_date->diffInDays(now()) }} day(s)
                            </span>
                        @endif
                    </div>
                    <div class="d-flex gap-4 text-center">
                        <div>
                            <div class="text-muted small text-uppercase fw-bold" style="font-size:10px;">Total</div>
                            <div class="fw-bold fs-5">{{ $currSymbol }}{{ number_format($invoice->total_amount, 2) }}</div>
                        </div>
                        <div class="vr"></div>
                        <div>
                            <div class="text-muted small text-uppercase fw-bold" style="font-size:10px;">Paid</div>
                            <div class="fw-bold fs-5 text-success">{{ $currSymbol }}{{ number_format($invoice->paid_amount, 2) }}</div>
                        </div>
                        <div class="vr"></div>
                        <div>
                            <div class="text-muted small text-uppercase fw-bold" style="font-size:10px;">Balance Due</div>
                            <div class="fw-bold fs-5 {{ $invoice->balance_amount > 0 ? 'text-danger' : 'text-success' }}">
                                {{ $currSymbol }}{{ number_format($invoice->balance_amount, 2) }}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{{-- Main Invoice Card --}}
<div class="row">
    <div class="col-12">
        <div class="card shadow-sm">
            <div class="card-body p-4 p-md-5">

                {{-- Header: Bill To + Invoice Details --}}
                <div class="row mb-4">
                    <div class="col-md-6">
                        <p class="text-muted small fw-bold text-uppercase mb-1">Bill To</p>
                        <h5 class="mb-1 fw-bold">{{ $invoice->client?->name ?? 'N/A' }}</h5>
                        @if($invoice->client?->email)
                            <p class="text-muted mb-0 small"><i class="ti ti-mail me-1"></i>{{ $invoice->client->email }}</p>
                        @endif
                        @if($invoice->client?->phone)
                            <p class="text-muted mb-0 small"><i class="ti ti-phone me-1"></i>{{ $invoice->client->phone }}</p>
                        @endif
                        @if($invoice->client?->address)
                            <p class="text-muted mb-0 small mt-1" style="white-space:pre-line;">{{ $invoice->client->address }}</p>
                        @endif
                    </div>
                    <div class="col-md-6">
                        <div class="text-md-end">
                            <h3 class="text-primary fw-bold mb-3">{{ $docLabel }}</h3>
                        </div>
                        <table class="table table-borderless table-sm ms-auto mb-0" style="max-width:320px;">
                            <tr>
                                <td class="text-muted py-1 ps-0 small fw-bold text-uppercase" style="font-size:11px;">Invoice No.</td>
                                <td class="py-1 text-end fw-semibold">{{ $invoice->invoice_number }}</td>
                            </tr>
                            <tr>
                                <td class="text-muted py-1 ps-0 small fw-bold text-uppercase" style="font-size:11px;">Invoice Date</td>
                                <td class="py-1 text-end">{{ $invoice->invoice_date?->format('d M Y') }}</td>
                            </tr>
                            <tr>
                                <td class="text-muted py-1 ps-0 small fw-bold text-uppercase" style="font-size:11px;">Due Date</td>
                                <td class="py-1 text-end {{ $invoice->due_date?->isPast() && !in_array($invoice->status, ['paid','voided']) ? 'text-danger fw-bold' : '' }}">
                                    {{ $invoice->due_date?->format('d M Y') }}
                                </td>
                            </tr>
                            @if($invoice->currency)
                            <tr>
                                <td class="text-muted py-1 ps-0 small fw-bold text-uppercase" style="font-size:11px;">Currency</td>
                                <td class="py-1 text-end">{{ $invoice->currency->iso_code }} ({{ $invoice->currency->symbol }})</td>
                            </tr>
                            @endif
                            @if($invoice->po_number ?? null)
                            <tr>
                                <td class="text-muted py-1 ps-0 small fw-bold text-uppercase" style="font-size:11px;">PO Number</td>
                                <td class="py-1 text-end">{{ $invoice->po_number }}</td>
                            </tr>
                            @endif
                            @if($invoice->reference ?? null)
                            <tr>
                                <td class="text-muted py-1 ps-0 small fw-bold text-uppercase" style="font-size:11px;">Reference</td>
                                <td class="py-1 text-end">{{ $invoice->reference }}</td>
                            </tr>
                            @endif
                        </table>
                    </div>
                </div>

                <hr class="my-3">

                {{-- Line Items --}}
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light">
                            <tr>
                                <th style="width:4%">#</th>
                                <th>Description</th>
                                <th class="text-center" style="width:10%">Qty</th>
                                <th class="text-end" style="width:15%">Unit Price</th>
                                @if($invoice->items->sum('discount_amount') > 0)
                                <th class="text-end" style="width:12%">Discount</th>
                                @endif
                                <th class="text-center" style="width:12%">Tax</th>
                                <th class="text-end" style="width:14%">Amount</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($invoice->items as $i => $item)
                            <tr>
                                <td class="text-muted small">{{ $i + 1 }}</td>
                                <td>
                                    <div class="fw-semibold">{{ $item->description }}</div>
                                    @if($item->taxes->count())
                                    <div class="mt-1">
                                        @foreach($item->taxes as $tax)
                                            <span class="badge bg-light text-dark border small">{{ $tax->name }} ({{ $tax->rate }}{{ $tax->type === 'percentage' ? '%' : '' }})</span>
                                        @endforeach
                                    </div>
                                    @endif
                                </td>
                                <td class="text-center">{{ number_format($item->quantity, 2) }}</td>
                                <td class="text-end">{{ number_format($item->unit_price, 2) }}</td>
                                @if($invoice->items->sum('discount_amount') > 0)
                                <td class="text-end text-warning">{{ number_format($item->discount_amount ?? 0, 2) }}</td>
                                @endif
                                <td class="text-center">{{ number_format($item->tax_amount, 2) }}</td>
                                <td class="text-end fw-semibold">{{ number_format($item->total_amount, 2) }}</td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="7" class="text-center text-muted py-4">
                                    <i class="ti ti-inbox font-24 d-block mb-2"></i>No line items
                                </td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>

                {{-- Totals --}}
                <div class="row mt-3">
                    <div class="col-md-6 col-lg-5 ms-auto">
                        <table class="table table-borderless table-sm mb-0">
                            <tr>
                                <td class="text-muted">Subtotal</td>
                                <td class="text-end">{{ $currSymbol }}{{ number_format($invoice->sub_total, 2) }}</td>
                            </tr>
                            @if(($invoice->discount_amount ?? 0) > 0)
                            <tr>
                                <td class="text-muted">Discount</td>
                                <td class="text-end text-warning">- {{ $currSymbol }}{{ number_format($invoice->discount_amount, 2) }}</td>
                            </tr>
                            @endif
                            <tr>
                                <td class="text-muted">Tax Total</td>
                                <td class="text-end">{{ $currSymbol }}{{ number_format($invoice->tax_total, 2) }}</td>
                            </tr>
                            <tr class="border-top">
                                <td class="fw-bold fs-5 py-2">Grand Total</td>
                                <td class="text-end fw-bold fs-5 py-2 text-primary">{{ $currSymbol }}{{ number_format($invoice->total_amount, 2) }}</td>
                            </tr>
                            @if($invoice->paid_amount > 0)
                            <tr>
                                <td class="text-success">Amount Paid</td>
                                <td class="text-end text-success">- {{ $currSymbol }}{{ number_format($invoice->paid_amount, 2) }}</td>
                            </tr>
                            <tr class="border-top table-active">
                                <td class="fw-bold py-2">Balance Due</td>
                                <td class="text-end fw-bold py-2 {{ $invoice->balance_amount > 0 ? 'text-danger' : 'text-success' }}">
                                    {{ $currSymbol }}{{ number_format($invoice->balance_amount, 2) }}
                                </td>
                            </tr>
                            @endif
                        </table>
                    </div>
                </div>

                {{-- Notes --}}
                @if($invoice->notes)
                <div class="mt-4 p-3 bg-light rounded border-start border-4 border-primary">
                    <p class="text-muted small fw-bold mb-1 text-uppercase">Notes / Terms</p>
                    <p class="mb-0 small" style="white-space:pre-line;">{{ $invoice->notes }}</p>
                </div>
                @endif

            </div>
        </div>
    </div>
</div>

{{-- Payment History --}}
@if($invoice->payments->count() > 0)
<div class="row mt-3">
    <div class="col-12">
        <div class="card shadow-sm">
            <div class="card-header d-flex align-items-center justify-content-between">
                <h5 class="card-title mb-0"><i class="ti ti-cash me-2 text-success"></i>Payment History</h5>
                <span class="badge bg-success-subtle text-success border border-success">
                    {{ $invoice->payments->count() }} Payment(s)
                </span>
            </div>
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0 align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th>Date</th>
                                <th>Method</th>
                                <th>Reference / Note</th>
                                <th class="text-end">Amount</th>
                                <th class="text-center" style="width:80px;">Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($invoice->payments as $idx => $payment)
                            <tr>
                                <td class="text-muted small">{{ $idx + 1 }}</td>
                                <td>{{ $payment->payment_date?->format('d M Y') }}</td>
                                <td>
                                    @php
                                        $mLabel = match($payment->payment_method) {
                                            'bank_transfer' => 'Bank Transfer',
                                            'credit_card'   => 'Credit Card',
                                            'paypal'        => 'PayPal',
                                            'cheque'        => 'Cheque',
                                            'cash'          => 'Cash',
                                            default         => ucfirst($payment->payment_method ?? 'Other')
                                        };
                                    @endphp
                                    <span class="badge bg-light text-dark border">{{ $mLabel }}</span>
                                </td>
                                <td class="text-muted small">{{ $payment->reference ?? ($payment->notes ?? '—') }}</td>
                                <td class="text-end fw-semibold text-success">
                                    {{ $currSymbol }}{{ number_format($payment->amount, 2) }}
                                </td>
                                <td class="text-center">
                                    <a href="{{ route('finance.payments.show', $payment->id) }}" class="btn btn-xs btn-outline-primary px-2" title="View">
                                        <i class="ti ti-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            @endforeach
                        </tbody>
                        <tfoot class="table-light">
                            <tr>
                                <td colspan="4" class="text-end fw-bold">Total Paid</td>
                                <td class="text-end fw-bold text-success">
                                    {{ $currSymbol }}{{ number_format($invoice->payments->sum('amount'), 2) }}
                                </td>
                                <td></td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
@endif

@endsection

@section('scripts')
<script>
const invoiceId = {{ $invoice->id }};
const csrfToken = "{{ csrf_token() }}";

function changeStatus(status) {
    Swal.fire({
        title: 'Change Status',
        text: 'Mark this invoice as "' + status + '"?',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#aaa',
        confirmButtonText: 'Yes, update!'
    }).then(result => {
        if (result.isConfirmed) {
            $.post("{{ route('finance.invoices.status', $invoice->id) }}", {
                _token: csrfToken, status: status
            }).done(res => {
                if (res.status) {
                    Swal.fire({ icon: 'success', title: 'Updated!', text: res.message, timer: 1500 })
                        .then(() => location.reload());
                }
            }).fail(() => Swal.fire('Error', 'Could not update status.', 'error'));
        }
    });
}

function sendInvoice() {
    Swal.fire({
        title: 'Send Invoice by Email',
        html: 'Send this invoice to <strong>{{ $invoice->client?->email ?? "client" }}</strong>?',
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: '<i class="ti ti-send me-1"></i> Send',
        cancelButtonText: 'Cancel'
    }).then(result => {
        if (result.isConfirmed) {
            $.post("{{ route('finance.invoices.send', $invoice->id) }}", { _token: csrfToken })
                .done(res => Swal.fire('Sent!', res.message, 'success'))
                .fail(() => Swal.fire('Error', 'Could not send email. Check SMTP settings.', 'error'));
        }
    });
}

function duplicateInvoice() {
    Swal.fire({
        title: 'Duplicate Invoice',
        text: 'A new draft invoice will be created as a copy.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'Duplicate'
    }).then(result => {
        if (result.isConfirmed) {
            $.post("{{ route('finance.invoices.duplicate', $invoice->id) }}", { _token: csrfToken })
                .done(res => {
                    if (res.status) {
                        Swal.fire('Duplicated!', 'New draft invoice created.', 'success')
                            .then(() => window.location.href = '/finance/invoices/' + res.id);
                    }
                }).fail(() => Swal.fire('Error', 'Could not duplicate invoice.', 'error'));
        }
    });
}

function voidInvoice() {
    Swal.fire({
        title: 'Void Invoice',
        text: 'This will void the invoice. This action cannot be undone!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        confirmButtonText: 'Yes, void it!'
    }).then(result => {
        if (result.isConfirmed) {
            $.post("{{ route('finance.invoices.status', $invoice->id) }}", {
                _token: csrfToken, status: 'voided'
            }).done(res => {
                if (res.status) {
                    Swal.fire({ icon: 'success', title: 'Voided!', timer: 1500 })
                        .then(() => location.reload());
                }
            });
        }
    });
}
</script>
@endsection
