<!doctype html>
<?php
// Mencegah error jika $company kosong dari Controller dengan memanggilnya langsung di View
if (empty($company)) {
    if (class_exists('\App\Models\CompanySettingModel')) {
        $companyModel = new \App\Models\CompanySettingModel();
        $company = $companyModel->first() ?? [];
    } else {
        $company = [];
    }
}

// --- BUG FIX: CONVERT LOGO TO BASE64 UNTUK DOMPDF ---
$base64Logo = '';
if (!empty($company['logo_url'])) {
    // Menentukan path absolut di server berdasarkan logo_url
    $path = FCPATH . ltrim($company['logo_url'], '/'); 
    
    if (file_exists($path)) {
        $type = pathinfo($path, PATHINFO_EXTENSION);
        $data = file_get_contents($path);
        if ($data !== false) {
            $base64Logo = 'data:image/' . $type . ';base64,' . base64_encode($data);
        }
    }
}
?>
<html lang="id">
<head>
    <meta charset="utf-8">
    <title>Invoice <?= esc($invoice['nomor_invoice'] ?? '-') ?></title>
    <style>
        /* Reset & Base Styles */
        body { 
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 
            color: #334155; 
            font-size: 12px; 
            line-height: 1.5; 
            margin: 0;
            padding: 0;
            background-color: #f8fafc;
        } 
        
        .invoice-container { 
            max-width: 100%; 
            margin: 0 auto; 
            background: #ffffff;
            padding: 40px;
            /* Garis aksen elegan di atas dokumen */
            border-top: 8px solid #0f172a; 
        } 

        /* --- CSS KHUSUS DOMPDF (Tabel Layout) --- */ 
        .layout-table { 
            width: 100%; 
            border-collapse: collapse; 
            border: none; 
        } 
        .layout-table td { 
            border: none; 
            padding: 0; 
            vertical-align: top; 
        } 

        /* --- TYPOGRAPHY & HEADER --- */ 
        .invoice-title {
            font-size: 32px;
            font-weight: 800;
            color: #0f172a;
            letter-spacing: 2px;
            margin-bottom: 5px;
        }
        .invoice-number {
            font-size: 14px;
            font-weight: bold;
            color: #64748b;
        }
        .company-name { 
            font-size: 18px; 
            font-weight: bold; 
            color: #0f172a; 
            margin-bottom: 6px; 
            text-transform: uppercase;
            letter-spacing: 0.5px;
        } 
        .company-contact { 
            color: #64748b; 
            font-size: 11px; 
            line-height: 1.6;
        } 
        .company-logo { 
            max-width: 140px; 
            max-height: 70px; 
            object-fit: contain;
            margin-bottom: 15px;
        } 

        /* --- LABELS & BADGES --- */
        .section-label {
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #94a3b8;
            font-weight: bold;
            margin-bottom: 5px;
        }
        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 11px;
            text-transform: uppercase;
            letter-spacing: 1px;
        }
        .badge-paid { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
        .badge-unpaid { background: #fee2e2; color: #991b1b; border: 1px solid #fecaca; }
        .badge-partial { background: #ffedd5; color: #9a3412; border: 1px solid #fed7aa; }

        /* --- CUSTOMER INFO SECTION --- */ 
        .info-box-wrapper {
            margin-top: 40px;
            margin-bottom: 30px;
            border-top: 1px solid #f1f5f9;
            border-bottom: 1px solid #f1f5f9;
            padding: 20px 0;
        }
        .customer-name {
            font-size: 14px;
            font-weight: bold;
            color: #1e293b;
            margin-bottom: 4px;
        }
        .meta-data-text {
            font-size: 12px;
            color: #1e293b;
            font-weight: bold;
        }

        /* --- TABEL DATA INVOICE --- */ 
        .data-table { 
            width: 100%; 
            border-collapse: collapse; 
            margin-bottom: 30px; 
        } 
        .data-table th, .data-table td { 
            padding: 12px 10px; 
        } 
        .data-table th { 
            background: #f8fafc; 
            color: #475569;
            font-size: 10px; 
            text-align: left; 
            text-transform: uppercase;
            letter-spacing: 1px;
            border-bottom: 2px solid #cbd5e1;
            border-top: 1px solid #e2e8f0;
        } 
        .data-table td {
            border-bottom: 1px solid #f1f5f9;
            color: #334155;
        }
        .right { text-align: right !important; } 
        .center { text-align: center !important; } 
        
        .total-row td { 
            font-size: 13px;
            border-bottom: none;
            padding-top: 8px;
            padding-bottom: 8px;
        } 
        .total-row.grand-total td {
            font-weight: bold;
            background: #f8fafc;
            color: #0f172a;
            border-top: 2px solid #cbd5e1;
            padding-top: 12px;
            padding-bottom: 12px;
        }
        .total-row.balance td {
            font-weight: bold;
            color: #dc2626;
        }

        /* --- BANK & PAYMENT BOX --- */ 
        .payment-info-box { 
            background: #f8fafc; 
            border-left: 4px solid #3b82f6; 
            padding: 15px 20px; 
            margin-bottom: 30px; 
            font-size: 11px; 
        } 
        .payment-info-title { 
            font-weight: bold; 
            color: #1e293b; 
            margin-bottom: 6px; 
            text-transform: uppercase;
            letter-spacing: 0.5px;
        } 

        /* --- FOOTER --- */
        .footer { 
            margin-top: 50px; 
            font-size: 11px; 
            color: #94a3b8; 
            text-align: center;
            border-top: 1px solid #f1f5f9;
            padding-top: 20px;
        } 
    </style>
</head>
<body>
    <div class="invoice-container">
        
        <!-- HEADER SECTION -->
        <table class="layout-table">
            <tr>
                <!-- Kiri: Logo & Data Perusahaan -->
                <td style="width: 60%; padding-right: 20px;">
                    <?php if (!empty($base64Logo)): ?>
                        <img src="<?= $base64Logo ?>" alt="Logo" class="company-logo">
                    <?php elseif (!empty($company['logo_url'])): ?>
                        <img src="<?= base_url($company['logo_url']) ?>" alt="Logo" class="company-logo">
                    <?php endif; ?>

                    <div class="company-name"><?= esc($company['company_name'] ?? 'NAMA PERUSAHAAN') ?></div>
                    
                    <div class="company-contact">
                        <?php if (!empty($company['address'])): ?>
                            <div style="margin-bottom: 4px;"><?= nl2br(esc($company['address'])) ?></div>
                        <?php endif; ?>
                        
                        <div>
                            <?php if (!empty($company['email'])) echo "E: " . esc($company['email']) . " &nbsp;|&nbsp; "; ?>
                            <?php if (!empty($company['phone'])) echo "T: " . esc($company['phone']); ?>
                        </div>
                        
                        <?php if (!empty($company['npwp'])): ?>
                            <div style="margin-top: 4px;"><strong>NPWP:</strong> <?= esc($company['npwp']) ?></div>
                        <?php endif; ?>
                    </div>
                </td>
                
                <!-- Kanan: Judul Invoice & Status -->
                <td style="width: 40%; text-align: right;">
                    <div class="invoice-title">INVOICE</div>
                    <div class="invoice-number"># <?= esc($invoice['nomor_invoice'] ?? '-') ?></div>
                    
                    <div style="margin-top: 15px;">
                        <?php 
                            $status = strtoupper($invoice['status'] ?? 'UNPAID'); 
                            $badgeClass = 'badge-unpaid';
                            if ($status == 'PAID') $badgeClass = 'badge-paid';
                            if ($status == 'PARTIAL') $badgeClass = 'badge-partial';
                        ?>
                        <span class="badge <?= $badgeClass ?>"><?= $status ?></span>
                    </div>
                </td>
            </tr>
        </table>

        <!-- INFO PELANGGAN & ORDER SECTION -->
        <div class="info-box-wrapper">
            <table class="layout-table">
                <tr>
                    <!-- Kiri: Ditagihkan Kepada -->
                    <td style="width: 50%; padding-right: 20px;">
                        <div class="section-label">Ditagihkan Kepada:</div>
                        <div class="customer-name"><?= esc($order['customer_name'] ?? 'Pelanggan') ?></div>
                        <div class="company-contact">
                            <?php if(!empty($order['customer_phone'])): ?>
                                <?= esc($order['customer_phone']) ?><br>
                            <?php endif; ?>
                            <?php if(!empty($order['customer_email'])): ?>
                                <?= esc($order['customer_email']) ?>
                            <?php endif; ?>
                        </div>
                    </td>
                    
                    <!-- Kanan: Meta Data -->
                    <td style="width: 50%;">
                        <table class="layout-table">
                            <tr>
                                <td class="company-contact" style="padding-bottom: 6px;">No. Order</td>
                                <td class="meta-data-text right" style="padding-bottom: 6px;"><?= esc($order['order_number'] ?? '-') ?></td>
                            </tr>
                            <tr>
                                <td class="company-contact" style="padding-bottom: 6px;">Tanggal Invoice</td>
                                <td class="meta-data-text right" style="padding-bottom: 6px;">
                                    <?= isset($invoice['created_at']) ? date('d M Y', strtotime($invoice['created_at'])) : date('d M Y') ?>
                                </td>
                            </tr>
                            <tr>
                                <td class="company-contact">Jatuh Tempo</td>
                                <td class="meta-data-text right" style="color: #ef4444;">
                                    <?= !empty($invoice['tanggal_jatuh_tempo']) ? date('d M Y', strtotime($invoice['tanggal_jatuh_tempo'])) : '-' ?>
                                </td>
                            </tr>
                        </table>
                    </td>
                </tr>
            </table>
        </div>

        <!-- TABEL RINCIAN ITEM -->
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width: 45%;">Item / Produk</th>
                    <th style="width: 15%;" class="center">Qty</th>
                    <th style="width: 20%;" class="right">Harga Satuan</th>
                    <th style="width: 20%;" class="right">Subtotal</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($items)): ?>
                    <?php foreach ($items as $item): ?>
                    <tr>
                        <td style="font-weight: bold; color: #1e293b;"><?= esc($item['product_name'] ?? $item['nama_product'] ?? 'Produk') ?></td>
                        <td class="center"><?= esc($item['qty'] ?? 0) ?></td>
                        <td class="right">Rp <?= number_format((float)($item['price'] ?? $item['harga'] ?? 0), 0, ',', '.') ?></td>
                        <td class="right" style="font-weight: bold; color: #1e293b;">
                            Rp <?= number_format((float)($item['subtotal'] ?? 0), 0, ',', '.') ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="4" class="center company-contact" style="padding: 20px;">Tidak ada rincian item.</td>
                    </tr>
                <?php endif; ?>
                
                <!-- Spacer -->
                <tr><td colspan="4" style="border: none; padding: 5px;"></td></tr>

                <tr class="total-row">
                    <td colspan="2" style="border: none;"></td>
                    <td class="right" style="color: #64748b;">Subtotal</td>
                    <td class="right">Rp <?= number_format((float)($invoice['total_tagihan'] ?? $order['total'] ?? 0), 0, ',', '.') ?></td>
                </tr>
                <tr class="total-row grand-total">
                    <td colspan="2" style="border: none; background: #fff;"></td>
                    <td class="right">TOTAL TAGIHAN</td>
                    <td class="right">Rp <?= number_format((float)($invoice['total_tagihan'] ?? $order['total'] ?? 0), 0, ',', '.') ?></td>
                </tr>
                <tr class="total-row balance">
                    <td colspan="2" style="border: none;"></td>
                    <td class="right">SISA TAGIHAN</td>
                    <td class="right">Rp <?= number_format((float)($invoice['sisa_tagihan'] ?? 0), 0, ',', '.') ?></td>
                </tr>
            </tbody>
        </table>

        <!-- REKENING BANK DARI SETTINGS -->
        <?php if (!empty($company['rekening_bank'])): ?>
        <div class="payment-info-box">
            <div class="payment-info-title">Informasi Pembayaran / Transfer Bank</div>
            <div style="color: #475569; white-space: pre-line; line-height: 1.6;">
                <?= esc($company['rekening_bank']) ?>
            </div>
        </div>
        <?php endif; ?>

        <!-- RIWAYAT PEMBAYARAN -->
        <?php if (!empty($payments ?? []) && count($payments) > 0): ?>
        <div style="margin-top: 40px;">
            <div class="section-label">Riwayat Pembayaran</div>
            <table class="layout-table" style="border: 1px solid #e2e8f0; font-size: 11px;">
                <thead>
                    <tr style="background: #f8fafc; border-bottom: 1px solid #e2e8f0;">
                        <th style="padding: 10px; text-align: left; color: #64748b;">Tanggal</th>
                        <th style="padding: 10px; text-align: left; color: #64748b;">Metode</th>
                        <th style="padding: 10px; text-align: right; color: #64748b;">Jumlah</th>
                        <th style="padding: 10px; text-align: center; color: #64748b;">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($payments as $payment): ?>
                    <tr>
                        <td style="padding: 10px; border-bottom: 1px solid #f1f5f9;"><?= esc($payment['tanggal_bayar']) ?></td>
                        <td style="padding: 10px; border-bottom: 1px solid #f1f5f9;"><?= esc($payment['nama_metode'] ?? '-') ?></td>
                        <td style="padding: 10px; border-bottom: 1px solid #f1f5f9; text-align: right; color: #166534; font-weight: bold;">
                            Rp <?= number_format((float)$payment['jumlah_bayar'], 0, ',', '.') ?>
                        </td>
                        <td style="padding: 10px; border-bottom: 1px solid #f1f5f9; text-align: center;">
                            <strong><?= strtoupper($payment['status']) ?></strong>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

        <!-- FOOTER -->
        <div class="footer">
            <p style="margin: 0 0 5px 0;">Terima kasih atas pesanan Anda. Kami menghargai bisnis Anda bersama <strong><?= esc($company['company_name'] ?? 'Perusahaan') ?></strong>.</p>
            <p style="margin: 0;">Dokumen ini dihasilkan secara otomatis oleh sistem dan sah tanpa tanda tangan.</p>
        </div>

    </div>
</body>
</html>