<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice {{ $invoice->invoice_number ?? 'INV-001' }}</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; color: #111827; line-height: 1.6; }
        .invoice-container { max-width: 210mm; margin: 0 auto; padding: 1px; background: #fff; }
        .header-banner { background: linear-gradient(135deg, #137fec 0%, #0d5aa7 100%); color: #fff; padding: 30px 25mm; width: 854px; }
        .header-content { display: flex; justify-content: space-between; align-items: center; }
        .company-info { flex: 1; }
        .company-logo { width: 160px; max-height: 80px; margin-bottom: 15px; object-fit: contain; }
        .company-name { font-size: 28px; font-weight: 700; margin-bottom: 10px; }
        .company-details { font-size: 14px; opacity: 0.9; line-height: 1.8; }
        .customer-logo { width: 150px; max-height: 60px; margin-bottom: 10px; object-fit: contain; }
        .invoice-box { background: #fff; border-radius: 8px; padding: 20px; min-width: 200px; }
        .invoice-label { font-size: 11px; text-transform: uppercase; letter-spacing: 1px; color: #6b7280; margin-bottom: 5px; }
        .invoice-number { font-size: 20px; font-weight: 700; color: #137fec; }
        .content { padding: 30px 0; width: 855px; }
        .info-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin: 30px 0; }
        .info-box { border: 2px solid #e5e7eb; border-radius: 8px; padding: 15px 20px; height: 190px; width: 100%; }
        .box-title { font-size: 15px; font-weight: 700; text-transform: uppercase; color: #137fec; letter-spacing: 1px; margin-bottom: 15px; }
        .box-content { font-size: 16px; line-height: 1.8; color: rgba(0, 0, 0, 1); }
        .box-name { font-size: 16px; font-weight: 600; margin-bottom: 8px; color: #111827; }
        .invoice-title { padding-top: 10px; padding-bottom: 10px; }
        .items-table { width: 100%; border-collapse: collapse; margin: 30px 0; }
        .items-table thead { background: #137fec; color: #fff; }
        .items-table th { padding: 15px; text-align: left; font-size: 12px; font-weight: 600; text-transform: uppercase; color: rgba(0, 0, 0, 1); border-bottom-color: rgba(227, 227, 227, 1); background-color: rgba(240, 247, 255, 1); }
        .items-table th.text-right { background-color: rgba(240, 247, 255, 1); }
        .items-table td { padding: 15px; border-bottom: 1px solid #e5e7eb; border-bottom-color: rgba(223, 224, 225, 1); font-size: 14px; color: rgba(0, 0, 0, 1); }
        .items-table tbody tr:nth-child(even) { background: #f9fafb; }
        .text-right { text-align: right; }
        .items-table td.text-right { color: rgba(0, 0, 0, 1); font-size: 14px; }
        .totals-box { background: #137fec; color: #fff; border-radius: 8px; padding: 25px; margin-top: 30px; max-width: 350px; margin-left: auto; }
        .total-row { display: flex; justify-content: space-between; padding: 10px 0; font-size: 14px; border-bottom: 1px solid rgba(255,255,255,0.2); }
        .total-row:last-child { border-bottom: none; border-top: 2px solid rgba(255,255,255,0.3); padding-top: 15px; }
        .total-label { opacity: 0.9; font-size: 16px; }
        .total-value { font-weight: 600; }
        .grand-total { font-size: 20px; font-weight: 700; }
        .footer { padding: 25px 25mm; background: #f9fafb; border-top: 3px solid #137fec; }
        .footer-grid { display: flex; gap: 40px; }
        .footer-column { flex: 1; }
        .footer-column-left { border-right: 1px solid #e5e7eb; padding-right: 20px; }
        .footer-column-right { padding-left: 20px; }
        .footer-section { margin-bottom: 20px; }
        .footer-title { font-size: 16px; font-weight: 600; color: #374151; margin-bottom: 8px; }
        .footer-text { font-size: 15px; color: #6b7280; line-height: 1.8; }
        .payment-details { }
        .payment-title { font-size: 18px; font-weight: 600; color: #374151; margin-bottom: 8px; }
        .payment-info { font-size: 13px; color: #6b7280; line-height: 1.8; }
        .payment-bank { margin-bottom: 12px; }
        .payment-bank-name { font-weight: 600; color: #111827; margin-bottom: 4px; }
        .payment-bank-detail { font-size: 14px; color: #6b7280; line-height: 1.6; }
        .payment-button { display: inline-block; background: #137fec; color: #fff; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: 600; font-size: 14px; margin-top: 12px; transition: background 0.2s; }
        .payment-button:hover { background: #0d5aa7; }
        .payment-instructions { background: #eff6ff; border-left: 4px solid #137fec; padding: 20px; border-radius: 4px; margin-top: 30px; }
        .payment-instructions-title { font-size: 16px; font-weight: 600; color: #374151; margin-bottom: 12px; }
        .payment-instructions-content { font-size: 14px; color: #6b7280; line-height: 1.8; }
        .payment-instructions-details { margin-top: 15px; padding-top: 15px; border-top: 1px solid #dbeafe; }
        .watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 72px;
            color: rgba(255, 0, 0, 0.1);
            z-index: 1000;
            pointer-events: none;
            font-weight: bold;
            display: none;
        }
        @media print {
            * {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            .invoice-container { padding: 0; max-width: 100% !important; width: 100% !important; }
            body { background: #fff !important; }
            .header-banner { break-inside: avoid; }
        }
    </style>
</head>
<body style="background-color: #ffffff !important;">
    @if(isset($showWatermark) && $showWatermark)
        <div class="watermark" style="display: block;">UNLICENSED</div>
    @endif
    <div class="invoice-container">
        <div class="header-banner">
            <div class="header-content">
                <div class="company-info">
                    @php
                        $companySettings = \App\Models\CompanySetting::getSettings();
                    @endphp
                    @if($companySettings && $companySettings->company_logo && \Illuminate\Support\Facades\Storage::disk('public')->exists($companySettings->company_logo))
                        <img src="{{ \Illuminate\Support\Facades\Storage::url($companySettings->company_logo) }}" alt="{{ $companySettings->company_name ?? config('app.name') }}" class="company-logo">
                    @endif
                    <div class="company-name">{{ $companySettings->company_name ?? config('app.name') }}</div>
                    <div class="company-details">
                        @if($companySettings->company_address){{ $companySettings->company_address }}<br>@endif
                        @if($companySettings->company_phone){{ $companySettings->company_phone }} | @endif
                        @if($companySettings->company_email){{ $companySettings->company_email }}@endif
                    </div>
                </div>
                <div class="invoice-box">
                    <div class="invoice-label">Invoice Details</div>
                    <div style="margin-top: 10px; font-size: 13px; color: #6b7280; line-height: 1.8;">
                        <div><strong>Status:</strong> {{ ucfirst($invoice->status ?? 'Draft') }}</div>
                        <div><strong>Currency:</strong> {{ $invoice->currency ?? 'USD' }}</div>
                    </div>
                </div>
            </div>
        </div>

        <div class="content">
            <div class="info-grid">
                <div class="info-box">
                    <div class="box-title">Bill To</div>
                    @if($invoice->customer ?? null)
                    <div class="box-content">
                        @if(isset($invoice->customer->image) && $invoice->customer->image && \Illuminate\Support\Facades\Storage::disk('public')->exists($invoice->customer->image))
                            <img src="{{ \Illuminate\Support\Facades\Storage::url($invoice->customer->image) }}" alt="{{ $invoice->customer->name }}" class="customer-logo">
                        @elseif(isset($invoice->customer->logo) && $invoice->customer->logo && \Illuminate\Support\Facades\Storage::disk('public')->exists($invoice->customer->logo))
                            <img src="{{ \Illuminate\Support\Facades\Storage::url($invoice->customer->logo) }}" alt="{{ $invoice->customer->name }}" class="customer-logo">
                        @endif
                        <div class="box-name">{{ $invoice->customer->name }}</div>
                        @if($invoice->customer->email){{ $invoice->customer->email }}<br>@endif
                        @if($invoice->customer->phone){{ $invoice->customer->phone }}<br>@endif
                        @if($invoice->customer->address){{ $invoice->customer->address }}@endif
                    </div>
                    @endif
                </div>
                <div class="info-box">
                    <div class="box-title">Invoice Number</div>
                    <div class="box-content">
                        <div class="box-name">{{ $invoice->invoice_number ?? 'INV-001' }}</div>
                        <strong>Issue:</strong> {{ ($invoice->issue_date ?? now())->format('M d, Y') }}<br>
                        <strong>Due:</strong> {{ ($invoice->due_date ?? now()->addDays(30))->format('M d, Y') }}
                    </div>
                </div>
            </div>

            <table class="items-table">
                <thead>
                    <tr>
                        <th>Description</th>
                        <th class="text-right">Qty</th>
                        <th class="text-right">Unit Price</th>
                        <th class="text-right">Tax</th>
                        <th class="text-right">Total</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($invoice->items ?? [] as $item)
                    <tr>
                        <td>
                            <strong>{{ $item->description }}</strong>
                            @if($item->notes)
                                <br><small style="color: #6b7280;">{{ $item->notes }}</small>
                            @endif
                        </td>
                        <td class="text-right">{{ number_format($item->quantity, 2) }}</td>
                        <td class="text-right">{{ $invoice->currency ?? 'USD' }} {{ number_format($item->unit_price, 2) }}</td>
                        <td class="text-right">{{ $item->tax_rate ?? 0 }}%</td>
                        <td class="text-right"><strong>{{ $invoice->currency ?? 'USD' }} {{ number_format(($item->quantity * $item->unit_price) * (1 + ($item->tax_rate ?? 0) / 100), 2) }}</strong></td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="5" style="text-align: center; padding: 30px; color: #9ca3af;">No items</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>

            <div class="totals-box">
                <div class="total-row">
                    <span class="total-label">Subtotal</span>
                    <span class="total-value">{{ $invoice->currency ?? 'USD' }} {{ number_format($invoice->subtotal ?? 0, 2) }}</span>
                </div>
                @if(($invoice->tax_amount ?? 0) > 0)
                <div class="total-row">
                    <span class="total-label">Tax</span>
                    <span class="total-value">{{ $invoice->currency ?? 'USD' }} {{ number_format($invoice->tax_amount ?? 0, 2) }}</span>
                </div>
                @endif
                @if(($invoice->discount_amount ?? 0) > 0)
                <div class="total-row">
                    <span class="total-label">Discount</span>
                    <span class="total-value">-{{ $invoice->currency ?? 'USD' }} {{ number_format($invoice->discount_amount ?? 0, 2) }}</span>
                </div>
                @endif
                <div class="total-row grand-total">
                    <span>Total Due</span>
                    <span>{{ $invoice->currency ?? 'USD' }} {{ number_format($invoice->total ?? 0, 2) }}</span>
                </div>
            </div>
        </div>

        <div class="footer">
            <div class="footer-grid">
                <div class="footer-column footer-column-left">
                    @if($invoice->notes ?? null)
                    <div class="footer-section">
                        <div class="footer-title">Notes</div>
                        <div class="footer-text">{{ $invoice->notes }}</div>
                    </div>
                    @endif
                    @if($invoice->terms ?? null)
                    <div class="footer-section">
                        <div class="footer-title">Terms & Conditions</div>
                        <div class="footer-text">{{ $invoice->terms }}</div>
                    </div>
                    @endif
                </div>
                <div class="footer-column footer-column-right payment-details">
                    @php
                        // Handle both new invoice (invoiceData) and existing invoice (invoice object)
                        $paymentMethod = null;
                        if (isset($invoice) && $invoice && is_object($invoice) && !empty($invoice->payment_method)) {
                            $paymentMethod = $invoice->payment_method;
                        } elseif (isset($invoiceData) && is_array($invoiceData) && !empty($invoiceData['payment_method'])) {
                            $paymentMethod = $invoiceData['payment_method'];
                        }
                        
                        $selectedBankAccount = null;
                        
                        // Check if payment method is a bank account (format: bank_X where X is bank account ID)
                        if ($paymentMethod && is_string($paymentMethod) && str_starts_with($paymentMethod, 'bank_')) {
                            $bankId = str_replace('bank_', '', $paymentMethod);
                            $selectedBankAccount = \App\Models\BankAccount::find($bankId);
                        }
                    @endphp
                    
                    @if($paymentMethod)
                        <div class="footer-section">
                            <div class="payment-title">Payment Details</div>
                            
                            @if($paymentMethod === 'online')
                                <div class="payment-bank">
                                    <div class="payment-bank-name">Online Payment</div>
                                    <div class="payment-bank-detail">
                                        <div style="margin-bottom: 12px;">Payments can be made online via our payment gateway.</div>
                                        @php
                                            // Determine payment URL based on invoice state
                                            $paymentUrl = null;
                                            
                                            // Check if we have a saved invoice with public token
                                            if (isset($invoice) && is_object($invoice) && $invoice->id) {
                                                // Invoice is saved, get or generate public URL
                                                if ($invoice->public_token) {
                                                    $paymentUrl = route('invoice.public', ['token' => $invoice->public_token]);
                                                } elseif (method_exists($invoice, 'getPublicUrl')) {
                                                    $paymentUrl = $invoice->getPublicUrl();
                                                }
                                            }
                                        @endphp
                                        
                                        @if($paymentUrl)
                                            <a href="{{ $paymentUrl }}" class="payment-button" target="_blank" style="display: inline-block; background: #137fec; color: #fff; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: 600; font-size: 14px; margin-top: 8px; transition: background 0.2s;">
                                                Pay Now
                                            </a>
                                        @else
                                            <div style="margin-top: 8px; padding: 10px 14px; background: #f3f4f6; border-radius: 6px; font-size: 13px; color: #6b7280; display: inline-block;">
                                                Payment link will be generated after invoice is saved.
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            @elseif($selectedBankAccount)
                                <div class="payment-bank">
                                    <div class="payment-bank-name">{{ $selectedBankAccount->bank_name }}</div>
                                    <div class="payment-bank-detail">
                                        @if($selectedBankAccount->account_name)
                                            <div><strong>Account Name:</strong> {{ $selectedBankAccount->account_name }}</div>
                                        @endif
                                        @if($selectedBankAccount->account_number)
                                            <div><strong>Account Number:</strong> {{ $selectedBankAccount->account_number }}</div>
                                        @endif
                                        @if($selectedBankAccount->swift_code)
                                            <div><strong>SWIFT Code:</strong> {{ $selectedBankAccount->swift_code }}</div>
                                        @endif
                                        @if($selectedBankAccount->iban)
                                            <div><strong>IBAN:</strong> {{ $selectedBankAccount->iban }}</div>
                                        @endif
                                        @if($selectedBankAccount->branch_name)
                                            <div><strong>Branch:</strong> {{ $selectedBankAccount->branch_name }}</div>
                                        @endif
                                        @if($selectedBankAccount->currency)
                                            <div><strong>Currency:</strong> {{ $selectedBankAccount->currency }}</div>
                                        @endif
                                    </div>
                                </div>
                            @endif
                        </div>
                    @else
                        {{-- Fallback: Show all bank accounts if no payment method is selected --}}
                        @php
                            $bankAccounts = \App\Models\BankAccount::where('is_active', true)->orderBy('bank_name')->get();
                        @endphp
                        @if($bankAccounts->count() > 0)
                            <div class="footer-section">
                                <div class="payment-title">Payment Details</div>
                                @foreach($bankAccounts as $account)
                                <div class="payment-bank">
                                    <div class="payment-bank-name">{{ $account->bank_name }}</div>
                                    <div class="payment-bank-detail">
                                        @if($account->account_name)
                                            <div><strong>Account Name:</strong> {{ $account->account_name }}</div>
                                        @endif
                                        @if($account->account_number)
                                            <div><strong>Account Number:</strong> {{ $account->account_number }}</div>
                                        @endif
                                        @if($account->swift_code)
                                            <div><strong>SWIFT Code:</strong> {{ $account->swift_code }}</div>
                                        @endif
                                        @if($account->iban)
                                            <div><strong>IBAN:</strong> {{ $account->iban }}</div>
                                        @endif
                                        @if($account->branch_name)
                                            <div><strong>Branch:</strong> {{ $account->branch_name }}</div>
                                        @endif
                                        @if($account->currency)
                                            <div><strong>Currency:</strong> {{ $account->currency }}</div>
                                        @endif
                                    </div>
                                </div>
                                @endforeach
                            </div>
                        @endif
                    @endif
                </div>
            </div>
            
            <!-- Payment Instructions Section -->
            <div class="payment-instructions">
                <div class="payment-instructions-title">Payment Instructions</div>
                <div class="payment-instructions-content">
                    @php
                        // Calculate days until due
                        $issueDate = isset($invoice) && is_object($invoice) && $invoice->issue_date 
                            ? \Carbon\Carbon::parse($invoice->issue_date) 
                            : (isset($invoiceData) && is_array($invoiceData) && isset($invoiceData['issue_date']) 
                                ? \Carbon\Carbon::parse($invoiceData['issue_date']) 
                                : now());
                        $dueDate = isset($invoice) && is_object($invoice) && $invoice->due_date 
                            ? \Carbon\Carbon::parse($invoice->due_date) 
                            : (isset($invoiceData) && is_array($invoiceData) && isset($invoiceData['due_date']) 
                                ? \Carbon\Carbon::parse($invoiceData['due_date']) 
                                : now()->addDays(30));
                        $daysUntilDue = max(0, $issueDate->diffInDays($dueDate));
                    @endphp
                    <p>Please make payment within <strong>{{ $daysUntilDue }}</strong> days of the invoice date.</p>
                    
                    @php
                        // Get payment method details
                        $paymentMethod = null;
                        if (isset($invoice) && is_object($invoice) && !empty($invoice->payment_method)) {
                            $paymentMethod = $invoice->payment_method;
                        } elseif (isset($invoiceData) && is_array($invoiceData) && !empty($invoiceData['payment_method'])) {
                            $paymentMethod = $invoiceData['payment_method'];
                        }
                        
                        $selectedBankAccount = null;
                        if ($paymentMethod && is_string($paymentMethod) && str_starts_with($paymentMethod, 'bank_')) {
                            $bankId = str_replace('bank_', '', $paymentMethod);
                            $selectedBankAccount = \App\Models\BankAccount::find($bankId);
                        }
                    @endphp
                    
                    <div class="payment-instructions-details">
                        @if($paymentMethod === 'online')
                            <p><strong>Payment Method:</strong> Online Payment</p>
                            <p>Payments can be made online via our payment gateway.</p>
                            @php
                                $paymentUrl = null;
                                if (isset($invoice) && is_object($invoice) && $invoice->id) {
                                    if ($invoice->public_token) {
                                        $paymentUrl = route('invoice.public', ['token' => $invoice->public_token]);
                                    } elseif (method_exists($invoice, 'getPublicUrl')) {
                                        $paymentUrl = $invoice->getPublicUrl();
                                    }
                                }
                            @endphp
                            @if($paymentUrl)
                                <a href="{{ $paymentUrl }}" class="payment-button" target="_blank" style="display: inline-block; background: #137fec; color: #fff; padding: 12px 24px; border-radius: 6px; text-decoration: none; font-weight: 600; font-size: 14px; margin-top: 12px; transition: background 0.2s;">
                                    Pay Now
                                </a>
                            @else
                                <p style="margin-top: 12px; padding: 10px; background: #f3f4f6; border-radius: 6px; font-size: 13px; color: #6b7280; display: inline-block;">
                                    Payment link will be available after invoice is saved.
                                </p>
                            @endif
                        @elseif($selectedBankAccount)
                            <p><strong>Payment Method:</strong> Bank Transfer</p>
                            <p><strong>Bank:</strong> {{ $selectedBankAccount->bank_name }}</p>
                            @if($selectedBankAccount->account_name)
                                <p><strong>Account Name:</strong> {{ $selectedBankAccount->account_name }}</p>
                            @endif
                            @if($selectedBankAccount->account_number)
                                <p><strong>Account Number:</strong> {{ $selectedBankAccount->account_number }}</p>
                            @endif
                            @if($selectedBankAccount->swift_code)
                                <p><strong>SWIFT Code:</strong> {{ $selectedBankAccount->swift_code }}</p>
                            @endif
                            @if($selectedBankAccount->iban)
                                <p><strong>IBAN:</strong> {{ $selectedBankAccount->iban }}</p>
                            @endif
                            @if($selectedBankAccount->branch_name)
                                <p><strong>Branch:</strong> {{ $selectedBankAccount->branch_name }}</p>
                            @endif
                            @if($selectedBankAccount->currency)
                                <p><strong>Currency:</strong> {{ $selectedBankAccount->currency }}</p>
                            @endif
                        @else
                            <p>Payment can be made via bank transfer or other agreed methods.</p>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
