<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Invoice</title>
    <style>
        /* A4 portrait print layout - modern, color accent */
    @page { size: A4; margin: 12mm; }

        html, body {
            height: 100%;
            font-family: Arial, Helvetica, sans-serif;
            color: #222;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        body {
            margin: 0;
            padding: 0;
            background: #fff;
            -webkit-print-color-adjust: exact;
            print-color-adjust: exact;
        }

        .sheet {
            width: 210mm;
            min-height: 297mm;
            padding: 12mm;
            box-sizing: border-box;
            page-break-after: always;
            position: relative;
            overflow: hidden;
        }

        .sheet::before {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-15deg);
            width: 500px;
            height: 500px;
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center;
            opacity: 0.18;
            z-index: 0;
            pointer-events: none;
        }

        .sheet > * {
            position: relative;
            z-index: 1;
        }

        .brand {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 4px solid #006622; /* green accent */
            padding-bottom: 8px;
            margin-bottom: 10px;
        }

        .brand .company {
            display: flex;
            gap: 18px;
            align-items: center;
        }

        /* Increased logo size for printed invoices */
        .company .logo {
            width: 240px; /* increased a bit more */
            height: 140px; /* increased a bit more */
            background: #006622;
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            border-radius: 6px;
            font-size: 20px;
            overflow: hidden;
            flex: 0 0 auto;
        }
        .company .logo img {
            display: block;
            max-width: 100%;
            max-height: 100%;
            width: auto;
            height: auto;
            object-fit: contain;
            background: #fff; /* provide white background when printing */
            padding: 2px; /* even smaller padding so image fills most of the box */
        }

        .company .meta {
            line-height: 1.05;
        }

    .company .meta h2 { margin: 0; font-size: 24px; }
    .company .meta p { margin: 2px 0; color: #555; font-size:15px }

    .tagline { text-align:center; color:#006622; font-style:italic; margin:8px 0 12px 0; font-size:14px; }

        .invoice-meta {
            text-align: right;
         
        }

    .invoice-meta h1 { margin: 0; font-size: 28px; color: #006622; }
    .invoice-meta .meta { color: #555; margin-top: 6px; font-size:15px }

        .top-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-top: 10px;
            margin-bottom: 12px;
        }

        .card {
            border: 1px solid #e6e9ee;
            padding: 10px;
            border-radius: 6px;
            background: #fff;
        }

        .card h3 { margin: 0 0 6px 0; font-size: 16px; color: #333; }
        .small { color: #666; font-size: 15px; }

        table.items {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 12px;
        }

        table.items thead th {
            text-align: left;
            padding: 8px 6px;
            background: #f5f8ff;
            color: #006622;
            border-bottom: 2px solid #e6e9ee;
            font-size: 14px;
        }

        table.items tbody td {
            padding: 8px 6px;
            border-bottom: 1px solid #f0f2f5;
            font-size: 14px;
            vertical-align: top;
        }

        .text-right { text-align: right; }
        .text-center { text-align: center; }

        .totals {
                margin-top: 6px;
                display: flex;
                justify-content: flex-end;
            }

        /* When we need a left remarks/delivery box next to totals */
        .totals-flex { display:flex; gap:12px; align-items:flex-start; justify-content:space-between; }
        .remark-box {
            width: 320px;
            border: 1px dashed #888;
            padding: 10px;
            border-radius: 6px;
            background: #fff;
            font-size: 14px;
        }
        .remark-box h4 { margin: 0 0 6px 0; font-size: 15px; }

        .totals .box {
            width: 300px;
            border: 1px solid #e6e9ee;
            padding: 10px;
            border-radius: 6px;
            background: #fafcff;
        }

    .totals .row { display: flex; justify-content: space-between; margin-bottom: 6px; }
    .totals .grand { font-weight: 700; font-size: 17px; color: #006622; }

        .notes { margin-top: 12px; font-size: 15px; color: #666; }

    .signatures { display:flex; gap: 18px; margin-top: 20px; }
    .sig-box { flex:1; text-align:center; }
    .sig-line { margin-top: 24px; border-top: 1px dashed #ddd; padding-top: 6px; color: #333; }

        /* Installment table styles */
        table.installments { width:100%; border-collapse: collapse; margin-top: 12px; }
        table.installments thead th { background: #fff7f0; color: #d35400; padding: 8px; border-bottom: 2px solid #f0e6df; font-size: 14px; }
        table.installments td { padding: 8px; border-bottom: 1px solid #f7f3f0; font-size: 14px; }

        @media print {
            .sheet { page-break-after: always; }
        }
    </style>
</head>
<body>
@php
    // Load watermark image
    $watermarkFile = public_path('logo/watermark.png');
    $watermarkBase64 = '';
    if(file_exists($watermarkFile)) {
        try {
            $watermarkData = file_get_contents($watermarkFile);
            $watermarkBase64 = 'data:image/png;base64,' . base64_encode($watermarkData);
        } catch(\Exception $e) {
            $watermarkBase64 = '';
        }
    }
    
    // Totals & helper values
    $items = $invoice->items ?? collect();
    $subtotal = 0;
    $totalDiscount = 0;
    foreach($items as $item) {
        $qty = $item->qty ?? 0;
        $price = $item->selling_price ?? ($item->price ?? 0);
        $line = ($price * $qty);
        $subtotal += $line;
        $totalDiscount += $item->discount ?? 0;
    }
    $netTotal = $subtotal - $totalDiscount;
    // Prefer authoritative remaining_balance stored on the invoice (avoids sign/negativity issues
    // Calculate total paid from remaining balance (transactions table removed)
    if (isset($invoice->remaining_balance) && $invoice->remaining_balance !== null) {
        $remaining = floatval($invoice->remaining_balance);
        $totalPaid = max(0, $netTotal - $remaining);
    } else {
        // Fallback: calculate from installments if remaining_balance not available
        $totalPaid = $invoice->installments ? $invoice->installments->sum('paid_amount') : 0;
    }
    $remaining = max(0, $netTotal - $totalPaid);
    $installments = $invoice->installments ?? collect();
    // Payment label: if invoice mode is 'loan' always show 'Down Payment',
    // otherwise show 'Advanced Payment' for cash payments and 'Down Payment' for others
    $payType = strtolower($invoice->payment_type ?? '');
    $invMode = strtolower($invoice->invoice_mode ?? '');
    if ($invMode === 'loan') {
        $downLabel = 'Down Payment';
    } else {
        $downLabel = ($payType === 'cash') ? 'Advanced Payment' : 'Down Payment';
    }
@endphp

<div class="sheet">
    @if($watermarkBase64)
        <style>
            .sheet::before {
                background-image: url('{{ $watermarkBase64 }}');
            }
        </style>
    @endif
    <div class="brand">
        <div class="company">
            @php 
                $logoFile = public_path('logo/Logo.png');
                $logoBase64 = '';
                if(file_exists($logoFile)) {
                    try {
                        $logoData = file_get_contents($logoFile);
                        $logoBase64 = 'data:image/png;base64,' . base64_encode($logoData);
                    } catch(\Exception $e) {
                        $logoBase64 = '';
                    }
                }
            @endphp
            @if($logoBase64)
                <div class="logo"><img src="{{ $logoBase64 }}" alt="Company Logo" style="width: 100%; height: 100%; object-fit: contain;"></div>
            @else
                <div class="logo">LOGO</div>
            @endif
            <div class="meta">
                <h2>HARSHANA SYSTEMS (PVT) LTD</h2>
                <p class="small">No.90/B,Nattandiya Road,Dankotuwa</p>
                <p class="small">Tel: 077 5897772 • 077 5897772</p>
            </div>
        </div>
        <div class="invoice-meta">
            <h1>INVOICE</h1>
            <div class="meta small">
                <!-- Keep the invoice number together on one line (no wrap) -->
                <div style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
                    Invoice #: <strong style="white-space:nowrap;">{{ $invoice->invoice_number }}</strong>
                </div>
                <!-- Put the date on a separate line; do not allow it to break across lines either -->
                <div style="margin-top:6px; white-space:nowrap;">
                    Date: <strong>{{ $invoice->date_time ? \Carbon\Carbon::parse($invoice->date_time)->format('Y-m-d') : date('Y-m-d') }}</strong>
                </div>
            </div>
            @if(isset($invoice->salesman) && $invoice->salesman->name)
            <div class="meta small">Salesman: <strong>{{ $invoice->salesman->name }}</strong></div>
            @endif
        </div>
    </div>

    <div class="top-grid">
        <div class="card">
            <h3>Bill To</h3>
            <div class="small"><strong>{{ $invoice->customer->customer_name ?? 'Walk-in Customer' }}</strong></div>
            @if($invoice->customer && $invoice->customer->address)
                <div class="small">{{ $invoice->customer->address }}</div>
            @endif
            @if($invoice->customer && $invoice->customer->contact_number)
                <div class="small">Tel: {{ $invoice->customer->contact_number }}</div>
            @endif
            <div class="small">Customer Balance: <strong>Rs. {{ number_format($invoice->customer->balance_amount ?? 0, 2) }}</strong></div>
        </div>

        <div class="card">
            <h3>Payment</h3>
            <div class="small">Payment Type: <strong>{{ $invoice->payment_type ?? 'Credit/Cash' }}</strong></div>
            @php
                $mode = $invoice->invoice_mode ?? 'cash';
                $modeLabel = ($mode === 'preorder') ? 'Pre Order Invoice' : (($mode === 'loan') ? 'Loan Invoice' : 'Cash Invoice');
            @endphp
            <div class="small">Invoice Mode: <strong>{{ $modeLabel }}</strong></div>
            @if($invMode === 'loan' && !empty($invoice->loan_number))
                <div class="small">Loan No: <strong>{{ $invoice->loan_number }}</strong></div>
            @endif
            <div class="small">{{ $downLabel }}: <strong>Rs. {{ number_format($invoice->down_payment ?? 0, 2) }}</strong></div>
            <div class="small">Total Paid: <strong>Rs. {{ number_format($totalPaid, 2) }}</strong></div>
            <div class="small">Remaining: <strong>Rs. {{ number_format($remaining, 2) }}</strong></div>
        </div>
    </div>

    <table class="items">
        <thead>
            <tr>
                <th style="width:50%">Description</th>
                <th style="width:12%" class="text-center">Qty</th>
                <th style="width:18%" class="text-right">Unit Price</th>
                <th style="width:20%" class="text-right">Line Total</th>
            </tr>
        </thead>
        <tbody>
            @forelse($items as $item)
            <tr>
                @php $w = $item->warranty ?? optional($item->product)->warranty_days ?? 0; @endphp
                <td>
                    {{ $item->product->product_name ?? ($item->description ?? 'Item') }}
                    @if($w && intval($w) > 0)
                        <div style="font-size:12px; color:#555; margin-top:4px;">Warranty: {{ intval($w) }} Months</div>
                    @endif
                </td>
                <td class="text-center">{{ $item->qty }}</td>
                <td class="text-right">Rs. {{ number_format($item->selling_price ?? 0, 2) }}</td>
                <td class="text-right">Rs. {{ number_format($item->total_value ?? (($item->selling_price ?? 0) * ($item->qty ?? 0)), 2) }}</td>
            </tr>
            @empty
            <tr>
                <td colspan="4" class="text-center small">No items on this invoice</td>
            </tr>
            @endforelse
        </tbody>
    </table>

    <div class="totals totals-flex">
        <div class="remark-box">
            <h4>Delivery / Remarks</h4>
            <div style="min-height:48px;">
                @php
                    $delivery = $invoice->delivery_address ?? $invoice->delivery_address_line ?? null;
                    if(empty($delivery)) {
                        // fallback to customer address if invoice delivery address is not provided
                        $delivery = optional($invoice->customer)->address ?? null;
                    }
                @endphp
                <div style="color:#333;">{!! nl2br(e($delivery ?? '-')) !!}</div>
            </div>
            @if(!empty($invoice->notes))
                <hr style="margin:8px 0;">
                <div style="font-weight:600; margin-bottom:4px;">Remarks</div>
                <div style="color:#333;">{!! nl2br(e($invoice->notes)) !!}</div>
            @endif
        </div>

        <div class="box">
            <div class="row"><div>Sub Total</div><div>Rs. {{ number_format($subtotal, 2) }}</div></div>
            <div class="row" style="display:none"><div>Discount</div><div>Rs. {{ number_format($totalDiscount, 2) }}</div></div>
            <div class="row grand"><div>NET TOTAL</div><div>Rs. {{ number_format($netTotal, 2) }}</div></div>
            <div class="row"><div>Paid</div><div>Rs. {{ number_format($totalPaid, 2) }}</div></div>
            <div class="row"><div>Remaining</div><div>Rs. {{ number_format($remaining, 2) }}</div></div>
        </div>
    </div>

    @if($installments && $installments->count() > 0)
        <h3 style="margin-top:18px; color:#d35400;">Installment Schedule</h3>
        <table class="installments">
            <thead>
                <tr>
                    <th style="width:10%">#</th>
                    <th style="width:30%">Due Date</th>
                    <th style="width:20%" class="text-right">Amount</th>
                    <th style="width:20%" class="text-right">Paid</th>
                    <th style="width:20%" class="text-right">Status</th>
                </tr>
            </thead>
            <tbody>
                @foreach($installments as $inst)
                <tr>
                    <td class="text-center">{{ $inst->installment_number }}</td>
                    <td>{{ $inst->due_date ? \Carbon\Carbon::parse($inst->due_date)->format('Y-m-d') : '-' }}</td>
                    <td class="text-right">Rs. {{ number_format($inst->amount, 2) }}</td>
                    <td class="text-right">Rs. {{ number_format($inst->paid_amount ?? 0, 2) }}</td>
                    <td class="text-right">{{ ucfirst($inst->status ?? ($inst->paid_amount > 0 ? 'partially_paid' : 'pending')) }}</td>
                </tr>
                @endforeach
            </tbody>
        </table>
    @endif

    @if($invoice->notes)
        <div class="notes"><strong>Notes:</strong> {{ $invoice->notes }}</div>
    @endif

    

    <div class="signatures">
        <div class="sig-box">
            <div class="small">Prepared By</div>
            <div class="sig-line">{{ $invoice->creator->name ?? 'System' }}</div>
        </div>
        <div class="sig-box">
            <div class="small">Received By</div>
            <div class="sig-line">&nbsp;</div>
        </div>
        <div class="sig-box">
            <div class="small">Customer</div>
            <div class="sig-line">&nbsp;</div>
        </div>
    </div>
    <div class="tagline">The best household supplies for your house needs, for the best price.</div>
</div>

</body>
</html>
