<?= $this->extend('layouts/owner') ?>

<?= $this->section('content') ?>

<script src="https://cdn.tailwindcss.com"></script>
<script>
  tailwind.config = {
    darkMode: 'class',
    theme: {
      extend: {
        colors: {
          slate: { 950: '#0b1329' }
        }
      }
    }
  }
</script>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    .invoice-card {
        border: none;
        border-radius: 12px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
        background: #ffffff;
    }
    .info-label {
        font-size: 0.75rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #6c757d;
        font-weight: 700;
        margin-bottom: 4px;
    }
    .info-value {
        font-weight: 600;
        color: #2d3748;
    }
    .table-custom-header {
        background-color: #f8f9fa;
        border-bottom: 2px solid #e2e8f0;
    }
    .table-custom-header th {
        font-size: 0.8rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #4a5568;
        font-weight: 700;
    }
    .signature-line {
        margin-top: 60px;
        border-top: 2px solid #e2e8f0;
        width: 80%;
        margin-left: auto;
        margin-right: auto;
    }
    
    /* CSS Khusus untuk Mode Cetak/Print */
    @media print {
        body {
            background-color: #ffffff !important;
            color: #000000 !important;
        }
        .no-print {
            display: none !important;
        }
        .invoice-card {
            box-shadow: none !important;
            border: none !important;
            padding: 0 !important;
            margin: 0 !important;
        }
        .card-body {
            padding: 0 !important;
        }
        /* Menghilangkan sidebar dan header layout bawaan saat diprint */
        header, footer, nav, .sidebar, .navbar, .btn-print-back {
            display: none !important;
        }
        /* Memaksa margin halaman cetak agar presisi */
        @page {
            size: A4;
            margin: 1.5cm;
        }
    }
</style>

<!-- Tombol Navigasi & Aksi Atas (Akan disembunyikan saat dicetak) -->
<div class="d-flex justify-content-between align-items-center mb-4 no-print">
    <div>
        <h4 class="fw-bold text-dark mb-1"><?= esc($title ?? 'Detail Purchase Order') ?></h4>
        <p class="text-muted small mb-0">Kelola dan cetak dokumen resmi pemesanan barang</p>
    </div>
    <div class="d-flex gap-2">
        <a href="<?= base_url('owner/material') ?>" class="btn btn-outline-secondary px-3 py-2 rounded-2">
            <i class="fas fa-arrow-left me-2"></i>Kembali
        </a>
        <button onclick="window.print()" class="btn btn-primary px-4 py-2 rounded-2 shadow-sm">
            <i class="fas fa-print me-2"></i>Cetak Dokumen
        </button>
    </div>
</div>

<!-- Lembar Utama Invoice PO -->
<div class="card invoice-card" id="printable-invoice">
    <div class="card-body p-4 p-md-5">
        
        <!-- Header Dokumen Resmi -->
        <div class="row align-items-center mb-5 pb-4 border-bottom">
            <!-- Sisi Kiri: Identitas Perusahaan -->
            <div class="col-sm-6 mb-4 mb-sm-0">
                <div class="d-flex align-items-center gap-3">
                    <div class="bg-primary text-white rounded-3 d-flex align-items-center justify-content-center" style="width: 55px; height: 55px; box-shadow: 0 4px 10px rgba(13, 110, 253, 0.2);">
                        <i class="fas fa-warehouse fa-lg"></i>
                    </div>
                    <div>
                        <h5 class="fw-bold text-dark mb-0">INTERNAL MANAGEMENT</h5>
                        <p class="text-muted small mb-0">Sistem Inventory & Purchase Order</p>
                    </div>
                </div>
            </div>
            <!-- Sisi Kanan: Judul Dokumen & Status -->
            <div class="col-sm-6 text-sm-end">
                <h2 class="fw-bold text-uppercase text-secondary tracking-wider mb-2" style="letter-spacing: 1.5px;">PURCHASE ORDER</h2>
                <div class="d-flex justify-content-sm-end align-items-center gap-2">
                    <span class="badge bg-success bg-opacity-10 text-success border border-success border-opacity-25 px-3 py-2 rounded-pill fw-semibold">
                        <i class="fas fa-check-circle me-1"></i> APPROVED PO
                    </span>
                </div>
            </div>
        </div>

        <!-- Grid Informasi Metadata Transaksi -->
        <div class="row g-3 mb-5">
            <!-- Kolom 1: Supplier -->
            <div class="col-md-4">
                <div class="p-3 rounded-3 bg-light border h-100">
                    <div class="info-label">Dipesan Dari (Supplier):</div>
                    <div class="info-value text-primary fs-5 mb-2"><?= esc($purchase['nama_supplier'] ?? '-') ?></div>
                    <p class="text-muted small mb-0">
                        <i class="fas fa-map-marker-alt text-danger me-1"></i> 
                        <?= esc($purchase['alamat'] ?? 'Alamat tidak tertera.') ?>
                    </p>
                </div>
            </div>
            <!-- Kolom 2: Detail Transaksi -->
            <div class="col-md-4">
                <div class="p-3 rounded-3 bg-light border h-100">
                    <div class="info-label">Detail Transaksi:</div>
                    <div class="mb-2">
                        <span class="text-muted small d-block">Nomor Pembelian / PO</span>
                        <span class="info-value text-dark"><?= esc($purchase['nomor_purchase'] ?? '-') ?></span>
                    </div>
                    <div>
                        <span class="text-muted small d-block">Tanggal Transaksi</span>
                        <span class="info-value text-dark">
                            <i class="far fa-calendar-alt me-1 text-secondary"></i>
                            <?= isset($purchase['tanggal_beli']) ? date('d F Y', strtotime($purchase['tanggal_beli'])) : '-' ?>
                        </span>
                    </div>
                </div>
            </div>
            <!-- Kolom 3: Tujuan Pengiriman -->
            <div class="col-md-4">
                <div class="p-3 rounded-3 bg-light border h-100">
                    <div class="info-label">Tujuan Pengiriman:</div>
                    <div class="info-value mb-2 text-dark">Gudang Utama (Pusat)</div>
                    <p class="text-muted small mb-0">
                        Konfirmasi fisik barang wajib disesuaikan dengan dokumen resmi ini saat proses bongkar muat logistik.
                    </p>
                </div>
            </div>
        </div>

        <!-- Tabel Daftar Item Barang -->
        <div class="table-responsive rounded-3 border mb-4">
            <table class="table table-hover align-middle mb-0">
                <thead>
                    <tr class="table-custom-header">
                        <th class="py-3 px-4 text-center" style="width: 8%;">No.</th>
                        <th class="py-3" style="width: 47%;">Deskripsi Item / Nama Produk</th>
                        <th class="py-3 text-center" style="width: 12%;">Jumlah (Qty)</th>
                        <th class="py-3 text-end" style="width: 15%;">Harga Satuan</th>
                        <th class="py-3 text-end px-4" style="width: 18%;">Subtotal</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $grand_total = 0;
                    if (!empty($items) && is_array($items)):$no = 1;
                        foreach($items as $i):$qty = floatval($i['qty'] ?? 0);$harga = floatval($i['harga_beli'] ?? 0);$subtotal = $qty * $harga;
                            $grand_total +=$subtotal;
                    ?>
                    <tr>
                        <td class="py-3 text-center text-muted fw-bold"><?= $no++ ?>.</td>
                        <td class="py-3">
                            <div class="fw-bold text-dark"><?= esc($i['nama_product'] ?? '-') ?></div>
                            <span class="text-xs text-muted">ID Item: PROD-<?= esc($i['id_product'] ?? 'N/A') ?></span>
                        </td>
                        <td class="py-3 text-center fw-semibold text-dark"><?= esc($qty) ?></td>
                        <td class="py-3 text-end text-muted">Rp <?= number_format($harga, 0, ',', '.') ?></td>
                        <td class="py-3 text-end fw-bold text-dark px-4">Rp <?= number_format($subtotal, 0, ',', '.') ?></td>
                    </tr>
                    <?php 
                        endforeach; 
                    else:
                    ?>
                    <tr>
                        <td colspan="5" class="text-center py-5 text-muted">
                            <i class="fas fa-folder-open fa-2x mb-2 d-block"></i>
                            Tidak ada data item ditemukan dalam PO ini.
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
                
                <!-- Footer Tabel untuk Menampilkan Total Pembelian -->
                <tfoot class="bg-light border-top-2">
                    <tr>
                        <td colspan="3" class="border-0"></td>
                        <td class="text-end fw-bold text-uppercase py-3 text-secondary">Total Pembelian :</td>
                        <td class="text-end fw-bold py-3 text-primary fs-5 px-4">
                            Rp <?= number_format($grand_total, 0, ',', '.') ?>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>

        <!-- Bagian Catatan & Tanda Tangan Dokumen -->
        <div class="mt-5 pt-4 border-top">
            <div class="row align-items-end">
                <!-- Catatan Syarat dan Ketentuan -->
                <div class="col-md-7 mb-4 mb-md-0">
                    <div class="p-3 bg-light rounded-3 border-start border-primary border-4">
                        <h6 class="fw-bold text-dark mb-1"><i class="fas fa-info-circle text-primary me-1"></i> Catatan Penting:</h6>
                        <ul class="small text-muted mb-0 ps-3">
                            <li>Semua pengiriman barang harus disertai salinan cetak berkas PO resmi ini.</li>
                            <li>Komplain mengenai selisih jumlah Qty wajib dilaporkan maksimal 1x24 jam setelah barang diterima.</li>
                            <li>Dokumen ini adalah bukti transaksi digital sah tanpa tanda tangan basah jika disetujui sistem.</li>
                        </ul>
                    </div>
                </div>
                <!-- Area Tanda Tangan (Penting untuk versi cetak fisik) -->
                <div class="col-md-5">
                    <div class="row text-center">
                        <div class="col-6">
                            <div class="small text-muted mb-5">Dipersiapkan Oleh,</div>
                            <div class="signature-line"></div>
                            <div class="fw-bold text-dark mt-2 small">Staff Gudang</div>
                        </div>
                        <div class="col-6">
                            <div class="small text-muted mb-5">Disetujui Oleh,</div>
                            <div class="signature-line"></div>
                            <div class="fw-bold text-dark mt-2 small">Owner / Management</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
    </div>

<script>
document.addEventListener("DOMContentLoaded", function() {

    // ==========================================
    // PAYROLL CALCULATOR (POKOK + BONUS - POTONGAN)
    // ==========================================
    const pokokInput = document.getElementById('gaji_pokok');
    const bonusInput = document.getElementById('bonus');
    const potonganInput = document.getElementById('potongan');
    const totalInput = document.getElementById('total_gaji');
    const calculatedTotalText = document.getElementById('calculatedTotalText');

    function calculateSalary() {
        const pokok = parseFloat(pokokInput.value) || 0;
        const bonus = parseFloat(bonusInput.value) || 0;
        const potongan = parseFloat(potonganInput.value) || 0;
        
        // Rumus: Gaji Pokok + Bonus - Potongan
        const total = (pokok + bonus) - potongan;

        // Pasangkan hasil mentah ke input terproteksi (readonly)
        totalInput.value = Math.max(0, Math.round(total));

        // Format visual IDR Rupiah di bagian keterangan format terbilang
        calculatedTotalText.innerText = new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            maximumFractionDigits: 0
        }).format(total);
    }

    // Pasang listener real-time pada setiap elemen input kelas '.calc-input'
    document.querySelectorAll('.calc-input').forEach(input => {
        input.addEventListener('input', calculateSalary);
    });

    // Jalankan sekali saat inisiasi muatan DOM agar perhitungan awal benar
    calculateSalary();

    // ==========================================
    // SYSTEM DARK MODE CONTROLLER
    // ==========================================
    window.toggleDarkMode = function() {
        const html = document.documentElement;
        const icon = document.getElementById('themeIcon');
        
        if (html.classList.contains('dark')) {
            html.classList.remove('dark');
            localStorage.setItem('theme', 'light');
            icon.className = "fas fa-moon text-lg";
        } else {
            html.classList.add('dark');
            localStorage.setItem('theme', 'dark');
            icon.className = "fas fa-sun text-lg text-amber-400";
        }
    };

    // Sinkronisasi status tema gelap berdasarkan preferensi sistem/localstorage
    if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
        document.documentElement.classList.add('dark');
        document.getElementById('themeIcon').className = "fas fa-sun text-lg text-amber-400";
    }
});
</script>

<?= $this->endSection() ?>