<!doctype html>
<?php
// Mencegah error dan memastikan data selalu diambil dari Settings (Jalan Pintas)
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 ---
// This ensures DOMPDF always renders the image by embedding it directly into the HTML,
// bypassing any URL/Path resolution issues on the server.
$base64Logo = '';
if (!empty($company['logo_url'])) {
    // Determine the absolute server path based on the URL
    // Assuming 'logo_url' is something like 'uploads/logo.png'
    $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>
        body {
            /* Using standard web-safe fonts strictly for PDF compatibility */
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; 
            color: #334155;
            font-size: 12px;
            line-height: 1.5;
            background-color: #f8fafc;
            margin: 0;
            padding: 0;
        }

        .invoice-wrapper {
            background-color: #ffffff;
            max-width: 800px;
            margin: 20px auto;
            padding: 40px 50px;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            border-top: 6px solid #1e3a8a; /* Deep professional blue accent */
        }

        /* --- CSS DOMPDF COMPATIBILITY (STRICT TABLE LAYOUT) --- */
        table {
            width: 100%;
            border-collapse: collapse;
            border-spacing: 0;
        }
        
        .layout-table {
            width: 100%;
            border: none;
        }

        .layout-table td {
            border: none;
            padding: 0;
            vertical-align: top;
        }

        .action-bar {
            margin-bottom: 30px;
            text-align: right;
            padding-bottom: 15px;
            border-bottom: 1px solid #e2e8f0;
        }

        .btn {
            display: inline-block;
            padding: 8px 16px;
            text-decoration: none;
            border-radius: 4px;
            color: #fff;
            font-size: 12px;
            font-weight: bold;
            margin-left: 10px;
        }

        .btn-download { background: #ef4444; }
        .btn-print { background: #2563eb; }

        @media print {
            body { background-color: #ffffff; }
            .invoice-wrapper { box-shadow: none; margin: 0 auto; padding: 0; border-top: none; }
            .action-bar { display: none !important; }
        }

        .invoice-title {
            font-size: 26px;
            font-weight: bold;
            color: #0f172a;
            letter-spacing: 1px;
            margin-bottom: 4px;
            text-transform: uppercase;
        }

        .brand-name {
            font-size: 18px;
            font-weight: bold;
            color: #0f172a;
            margin-bottom: 6px;
            text-transform: uppercase;
        }

        .text-muted {
            color: #64748b;
        }
        
        .text-label {
            color: #94a3b8;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-weight: bold;
        }

        .logo-img {
            max-width: 140px;
            max-height: 70px;
            object-fit: contain;
            display: block;
            /* Failsafe styling if image is blocked by DOMPDF */
            color: #94a3b8; 
            font-size: 11px;
            font-style: italic;
        }

        .badge {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 4px;
            font-weight: bold;
            font-size: 10px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .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;}

        .data-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 35px;
            margin-bottom: 20px;
        }

        .data-table th, .data-table td {
            padding: 12px 14px;
            font-size: 12px;
        }

        .data-table th {
            background-color: #f8fafc; 
            color: #334155;
            text-align: left;
            text-transform: uppercase;
            font-weight: bold;
            font-size: 11px;
            border-bottom: 2px solid #cbd5e1;
            border-top: 1px solid #e2e8f0;
        }

        .data-table td {
            border-bottom: 1px solid #f1f5f9;
            color: #1e293b;
        }

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

        .total-row td {
            font-size: 13px;
            color: #0f172a;
            border-bottom: none;
            padding: 8px 14px;
        }
        
        .total-row.grand-total td {
            font-weight: bold;
            background-color: #f8fafc;
        }
        
        .total-row.balance td {
            font-weight: bold;
            color: #dc2626;
        }

        .bank-box {
            background: #f8fafc;
            border-left: 3px solid #2563eb;
            padding: 15px;
            margin-top: 25px;
            margin-bottom: 30px;
            font-size: 11px;
        }

        .bank-title {
            font-weight: bold;
            color: #1e293b;
            margin-bottom: 5px;
            font-size: 11px;
            text-transform: uppercase;
        }

        .footer {
            margin-top: 40px;
            padding-top: 20px;
            border-top: 1px solid #e2e8f0;
            text-align: center;
            font-size: 11px;
            color: #94a3b8;
        }
    </style>
</head>
<body>
    <div class="invoice-wrapper">

        <div class="action-bar">
            <a href="<?= site_url('admin/invoice/pdf/'.($invoice['access_token'] ?? '')) ?>" class="btn btn-download">
                Download PDF
            </a>
            <a href="javascript:window.print();" class="btn btn-print">
                Print Invoice
            </a>
        </div>

        <table class="layout-table" style="margin-bottom: 35px;">
            <tr>
                <!-- Kiri: Logo & Data Perusahaan -->
                <td style="width: 55%; padding-right: 20px;">
                    <?php if (!empty($base64Logo)): ?>
                        <!-- Using Base64 encoded image to guarantee PDF rendering -->
                        <div style="margin-bottom: 15px; min-height: 40px;">
                            <img src="<?= $base64Logo ?>" alt="Logo Perusahaan" class="logo-img">
                        </div>
                    <?php elseif (!empty($company['logo_url'])): ?>
                         <!-- Fallback to normal URL if Base64 conversion fails (e.g., file not found on disk) -->
                         <div style="margin-bottom: 15px; min-height: 40px;">
                            <img src="<?= base_url($company['logo_url']) ?>" alt="Logo Perusahaan" class="logo-img">
                        </div>
                    <?php endif; ?>
                    
                    <div class="brand-name"><?= esc($company['company_name'] ?? 'NAMA PERUSAHAAN') ?></div>
                    <div class="text-muted" style="font-size: 11px; line-height: 1.6;">
                        <?php if (!empty($company['address'])): ?>
                            <div style="margin-bottom: 6px;"><?= nl2br(esc($company['address'])) ?></div>
                        <?php endif; ?>
                        
                        <div>
                            <?php if (!empty($company['email'])): ?>
                                <span style="color: #475569;">E:</span> <?= esc($company['email']) ?><br>
                            <?php endif; ?>
                            <?php if (!empty($company['phone'])): ?>
                                <span style="color: #475569;">T:</span> <?= esc($company['phone']) ?>
                            <?php endif; ?>
                        </div>
                        
                        <?php if (!empty($company['npwp'])): ?>
                            <div style="margin-top: 4px;"><strong style="color: #475569;">NPWP:</strong> <?= esc($company['npwp']) ?></div>
                        <?php endif; ?>
                    </div>
                </td>

                <!-- Kanan: Judul Invoice & Meta -->
                <td style="width: 45%; text-align: right; vertical-align: top;">
                    <div class="invoice-title">INVOICE</div>
                    <div class="text-muted" style="margin-bottom: 15px; font-size: 14px; font-weight: bold; color: #475569;">
                        # <?= esc($invoice['nomor_invoice'] ?? '-') ?>
                    </div>
                    
                    <?php 
                        $status = strtoupper($invoice['status'] ?? 'UNPAID'); 
                        $badgeClass = 'badge-unpaid';
                        if ($status == 'PAID') $badgeClass = 'badge-paid';
                        if ($status == 'PARTIAL') $badgeClass = 'badge-partial';
                    ?>
                    <div>
                        <span class="badge <?= $badgeClass ?>"><?= $status ?></span>
                    </div>
                </td>
            </tr>
        </table>

        <table class="layout-table" style="margin-bottom: 25px;">
            <tr>
                <!-- Kiri: Kepada -->
                <td style="width: 55%; padding-right: 20px;">
                    <div class="text-label" style="margin-bottom: 6px;">Tagihan Kepada:</div>
                    <div style="font-size: 14px; font-weight: bold; color: #0f172a; margin-bottom: 4px;">
                        <?= esc($order['customer_name'] ?? '-') ?>
                    </div>
                    <div class="text-muted" style="font-size: 11px; line-height: 1.6;">
                        <?php if(!empty($order['customer_phone'])): ?>
                            <span style="color: #475569;">T:</span> <?= esc($order['customer_phone']) ?><br>
                        <?php endif; ?>
                        <?php if(!empty($order['customer_email'])): ?>
                            <span style="color: #475569;">E:</span> <?= esc($order['customer_email']) ?>
                        <?php endif; ?>
                    </div>
                </td>

                <!-- Kanan: Detail Invoice -->
                <td style="width: 45%;">
                    <table class="layout-table" style="font-size: 11px;">
                        <tr>
                            <td class="text-muted" style="padding-bottom: 8px;">No. Order</td>
                            <td class="right" style="padding-bottom: 8px; font-weight: bold; color: #1e293b;">
                                <?= esc($order['order_number'] ?? '-') ?>
                            </td>
                        </tr>
                        <tr>
                            <td class="text-muted" style="padding-bottom: 8px;">Tanggal Invoice</td>
                            <td class="right" style="padding-bottom: 8px; color: #1e293b;">
                                <?= isset($invoice['created_at']) ? date('d M Y', strtotime($invoice['created_at'])) : date('d M Y') ?>
                            </td>
                        </tr>
                        <tr>
                            <td class="text-muted">Jatuh Tempo</td>
                            <td class="right" style="font-weight: bold; color: #dc2626;">
                                <?= !empty($invoice['tanggal_jatuh_tempo']) ? date('d M Y', strtotime($invoice['tanggal_jatuh_tempo'])) : '-' ?>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>

        <table class="data-table">
            <thead>
                <tr>
                    <th style="width: 45%;">Deskripsi Produk / Item</th>
                    <th style="width: 15%; text-align: center;">Qty</th>
                    <th style="width: 20%; text-align: right;">Harga Satuan</th>
                    <th style="width: 20%; text-align: right;">Total</th>
                </tr>
            </thead>
            <tbody>
                <?php if(!empty($items)): ?>
                    <?php foreach ($items as $item): ?>
                    <tr>
                        <td style="font-weight: bold;">
                            <?= 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;">
                            Rp <?= number_format((float)($item['subtotal'] ?? 0), 0, ',', '.') ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="4" class="center text-muted" style="padding: 20px;">Tidak ada item.</td>
                    </tr>
                <?php endif; ?>

                <!-- Spacer -->
                <tr><td colspan="4" style="height: 10px; border: none; padding: 0;"></td></tr>

                <!-- Baris Total -->
                <tr class="total-row grand-total">
                    <td colspan="3" class="right" style="padding-top: 15px;">TOTAL TAGIHAN</td>
                    <td class="right" style="padding-top: 15px; font-size: 14px;">
                        Rp <?= number_format((float)($invoice['total_tagihan'] ?? $order['total'] ?? 0), 0, ',', '.') ?>
                    </td>
                </tr>
                <tr class="total-row balance">
                    <td colspan="3" class="right" style="padding-bottom: 15px;">SISA TAGIHAN</td>
                    <td class="right" style="padding-bottom: 15px;">
                        Rp <?= number_format((float)($invoice['sisa_tagihan'] ?? 0), 0, ',', '.') ?>
                    </td>
                </tr>
            </tbody>
        </table>

        <?php if (!empty($company['rekening_bank'])): ?>
        <div class="bank-box">
            <div class="bank-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; ?>

        <?php if (!empty($payments ?? []) && count($payments) > 0): ?>
        <div style="margin-top: 35px;">
            <div class="text-label" style="margin-bottom: 8px;">Riwayat Pembayaran</div>
            <table style="width: 100%; border-collapse: collapse; font-size: 11px; border: 1px solid #e2e8f0;">
                <thead>
                    <tr style="background-color: #f8fafc; border-bottom: 1px solid #e2e8f0;">
                        <th style="padding: 10px; text-align: left; color: #475569;">Tanggal</th>
                        <th style="padding: 10px; text-align: left; color: #475569;">Metode</th>
                        <th style="padding: 10px; text-align: right; color: #475569;">Jumlah</th>
                        <th style="padding: 10px; text-align: center; color: #475569;">Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($payments as $payment): ?>
                    <tr>
                        <td style="padding: 10px; border-bottom: 1px solid #f1f5f9; color: #334155;"><?= esc($payment['tanggal_bayar']) ?></td>
                        <td style="padding: 10px; border-bottom: 1px solid #f1f5f9; color: #334155;"><?= 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; color: #334155;">
                            <?= strtoupper($payment['status']) ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

        <div class="footer">
            <p style="margin: 0 0 4px 0;">Terima kasih atas kepercayaan Anda berbisnis dengan <strong><?= esc($company['company_name'] ?? 'Perusahaan') ?></strong>.</p>
            <p style="margin: 0;">Invoice ini sah dan diproses secara otomatis oleh sistem.</p>
        </div>

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