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

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

<!-- Tailwind CSS Engine for sleek utility styles -->
<script src="https://cdn.tailwindcss.com"></script>
<script>
  tailwind.config = {
    darkMode: 'class',
    theme: {
      extend: {
        colors: {
          slate: { 950: '#0b1329' }
        }
      }
    }
  }
</script>

<!-- Bootstrap 5 CSS for grid architecture -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Google Fonts & FontAwesome -->
<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>
    body {
        font-family: 'Inter', sans-serif !important;
        background-color: #f8fafc;
        transition: background-color 0.3s ease, color 0.3s ease;
    }

    /* Premium card visual properties */
    .product-card {
        background: #ffffff;
        border: 1px solid rgba(226, 232, 240, 0.8);
        border-radius: 1.25rem;
        transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    }
    .product-card:hover {
        transform: translateY(-3px);
        box-shadow: 0 12px 20px -5px rgba(0, 0, 0, 0.05);
    }

    /* Custom badge styles with high contrast glows */
    .badge-cnc-custom {
        background-color: rgba(59, 130, 246, 0.1);
        color: #3b82f6;
        border: 1px solid rgba(59, 130, 246, 0.2);
    }
    .badge-standard {
        background-color: rgba(139, 92, 246, 0.1);
        color: #8b5cf6;
        border: 1px solid rgba(139, 92, 246, 0.2);
    }
    .badge-stock-alert {
        background-color: rgba(239, 68, 68, 0.1);
        color: #ef4444;
        animation: pulse-danger 2s infinite;
    }

    @keyframes pulse-danger {
        0%, 100% { opacity: 1; }
        50% { opacity: 0.6; }
    }

    /* Scrollbars customizing */
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: #f1f5f9; }
    ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }

    /* Dark Mode Core Overrides */
    html.dark body {
        background-color: #0b1329 !important;
        color: #f8fafc !important;
    }
    html.dark .card,
    html.dark .product-card,
    html.dark .table-container {
        background-color: #1e293b !important;
        border-color: #334155 !important;
        color: #f1f5f9 !important;
    }
    html.dark .text-slate-900, html.dark h1, html.dark h2, html.dark h3, html.dark h4, html.dark h5 {
        color: #f8fafc !important;
    }
    html.dark .text-slate-500, html.dark .text-muted {
        color: #94a3b8 !important;
    }
    html.dark .bg-white {
        background-color: #1e293b !important;
    }
    html.dark .border, html.dark .border-bottom {
        border-color: #334155 !important;
    }
    html.dark .bg-slate-50 {
        background-color: #111a2e !important;
    }
    html.dark .table-hover tbody tr:hover {
        background-color: #111b30 !important;
    }
    html.dark .badge-cnc-custom {
        background-color: rgba(59, 130, 246, 0.2);
        color: #60a5fa;
    }
    html.dark .badge-standard {
        background-color: rgba(139, 92, 246, 0.2);
        color: #a78bfa;
    }
</style>

<div class="container-fluid py-4 px-3 sm:px-4 lg:px-6">

    <!-- Flash Alert Handler -->
    <?php if(session()->getFlashdata('success')): ?>
        <div id="flashAlert" class="mb-4 p-4 rounded-xl border border-emerald-200 bg-emerald-50 dark:bg-emerald-950/30 dark:border-emerald-800/50 text-emerald-800 dark:text-emerald-400 flex justify-between items-center shadow-xs">
            <span class="text-sm font-semibold flex items-center gap-2">
                <i class="fas fa-circle-check text-emerald-600"></i>
                <?= session()->getFlashdata('success') ?>
            </span>
            <button onclick="document.getElementById('flashAlert').style.display='none';" class="text-emerald-800 dark:text-emerald-400 opacity-60 hover:opacity-100">
                <i class="fas fa-times"></i>
            </button>
        </div>
    <?php endif; ?>

    <!-- Header & Action Deck -->
    <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6 pb-6 border-b border-slate-200">
        <div>
            <div class="flex items-center gap-2 mb-2">
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-indigo-50 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-400 border border-indigo-200 dark:border-indigo-800/50 shadow-sm">
                    <span class="w-2 h-2 rounded-full bg-indigo-600 animate-pulse"></span>
                    Manajemen Katalog & Kontrol Stok
                </span>
            </div>
            <h1 class="text-2xl sm:text-3xl font-extrabold text-slate-900 tracking-tight flex items-center gap-2">
                <i class="fas fa-cubes text-indigo-600 dark:text-indigo-400"></i>
                Barang Center
            </h1>
            <p class="text-sm text-slate-500 mt-1">Kelola portofolio produk fabrikasi kustom CNC, ketersediaan stok vendor, dan penetapan margin laba modal.</p>
        </div>

        <!-- Utility Action Buttons -->
        <div class="flex flex-wrap items-center gap-2 w-full md:w-auto">
            <!-- Dark Mode Toggle Button -->
            <button onclick="toggleDarkMode()" class="bg-white dark:bg-slate-800 hover:bg-slate-50 dark:hover:bg-slate-700 text-slate-700 dark:text-slate-200 border border-slate-200 dark:border-slate-600 rounded-xl p-2.5 shadow-sm transition-all flex items-center justify-center" title="Ubah Tema Gelap/Terang">
                <i id="themeIcon" class="fas fa-moon text-lg"></i>
            </button>
            <!-- Excel Export -->
            <button onclick="exportProductsExcel()" class="bg-emerald-600 hover:bg-emerald-700 text-white font-medium text-sm rounded-xl px-4 py-2.5 shadow-sm transition-all flex items-center gap-2 border-0">
                <i class="fas fa-file-excel"></i>
                <span class="hidden sm:inline">Ekspor Excel</span>
            </button>
            <!-- Add New Product Link -->
            <a href="<?= base_url('owner/product/create') ?>" class="bg-indigo-600 hover:bg-indigo-700 text-white font-semibold text-sm rounded-xl px-4 py-2.5 shadow-sm hover:shadow-md transition-all flex items-center gap-2 decoration-none no-underline">
                <i class="fas fa-plus"></i>
                <span>Tambah Barang</span>
            </a>
        </div>
    </div>

    <!-- Mini Metric Cards Dashboard -->
    <div class="row g-4 mb-6">
        <!-- Metric: Total Products -->
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="product-card p-4 flex items-center gap-4 bg-white">
                <div class="w-12 h-12 bg-indigo-50 dark:bg-indigo-950/30 text-indigo-600 dark:text-indigo-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-boxes-stacked"></i>
                </div>
                <div>
                    <span class="text-xs font-semibold text-slate-400 uppercase tracking-wider block">Total Jenis Barang</span>
                    <h3 id="statTotalItems" class="text-xl font-extrabold text-slate-900 mb-0">0</h3>
                </div>
            </div>
        </div>

        <!-- Metric: Low Stock Warnings -->
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="product-card p-4 flex items-center gap-4 bg-white">
                <div id="alertStockIconBox" class="w-12 h-12 bg-rose-50 dark:bg-rose-950/30 text-rose-600 dark:text-rose-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-triangle-exclamation"></i>
                </div>
                <div>
                    <span class="text-xs font-semibold text-slate-400 uppercase tracking-wider block">Stok Menipis (<10)</span>
                    <h3 id="statLowStock" class="text-xl font-extrabold text-rose-600 mb-0">0</h3>
                </div>
            </div>
        </div>

        <!-- Metric: Total Valuation -->
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="product-card p-4 flex items-center gap-4 bg-white">
                <div class="w-12 h-12 bg-emerald-50 dark:bg-emerald-950/30 text-emerald-600 dark:text-emerald-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-sack-dollar"></i>
                </div>
                <div>
                    <span class="text-xs font-semibold text-slate-400 uppercase tracking-wider block">Valuasi Modal Stok</span>
                    <h3 id="statValuation" class="text-xl font-extrabold text-slate-900 mb-0">Rp 0</h3>
                </div>
            </div>
        </div>

        <!-- Metric: Custom Products Ratio -->
        <div class="col-12 col-sm-6 col-lg-3">
            <div class="product-card p-4 flex items-center gap-4 bg-white">
                <div class="w-12 h-12 bg-amber-50 dark:bg-amber-950/30 text-amber-600 dark:text-amber-400 rounded-xl flex items-center justify-center text-xl">
                    <i class="fas fa-screwdriver-wrench"></i>
                </div>
                <div>
                    <span class="text-xs font-semibold text-slate-400 uppercase tracking-wider block">Fabrikasi CNC Kustom</span>
                    <h3 id="statCustomCount" class="text-xl font-extrabold text-slate-900 mb-0">0</h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Core Database Catalog Table Section -->
    <div class="bg-white dark:bg-slate-800 rounded-2xl border border-slate-200 dark:border-slate-700 shadow-sm overflow-hidden mb-6">
        
        <!-- Search & Control Header -->
        <div class="p-4 border-b border-slate-100 dark:border-slate-700 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4 bg-slate-50/50 dark:bg-slate-900/30">
            <div>
                <h4 class="text-base font-bold text-slate-900 dark:text-slate-100 flex items-center gap-2">
                    <i class="fas fa-list-ul text-slate-500"></i>
                    Daftar Inventaris Terdaftar
                </h4>
                <p class="text-xs text-slate-500 mt-0.5">Disinkronkan secara presisi dengan skema database server internal.</p>
            </div>
            <!-- Live Client-side Searching -->
            <div class="relative w-full sm:w-80">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
                    <i class="fas fa-magnifying-glass text-slate-400 text-sm"></i>
                </span>
                <input type="text" id="catalogSearch" onkeyup="filterCatalogTable()" placeholder="Cari nama, SKU, supplier, barcode..." class="w-full pl-9 pr-4 py-2 text-xs bg-white dark:bg-slate-900 dark:text-slate-100 border border-slate-200 dark:border-slate-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-indigo-500 transition-all shadow-xs">
            </div>
        </div>

        <!-- Master Responsive Table -->
        <div class="table-responsive">
            <table class="w-full text-left border-collapse" id="productsTable">
                <thead>
                    <tr class="bg-slate-50 dark:bg-slate-900/50 text-slate-500 dark:text-slate-400 font-bold text-xs uppercase tracking-wider border-b border-slate-200 dark:border-slate-700">
                        <th class="py-3.5 px-4 text-center" width="60">No</th>
                        <th class="py-3.5 px-4" width="80">Gambar</th>
                        <th class="py-3.5 px-4" width="280">Detil Produk</th>
                        <th class="py-3.5 px-4">Kategori & Supplier</th>
                        <th class="py-3.5 px-4" width="130">Jenis Produk</th>
                        <th class="py-3.5 px-4 text-center" width="120">Stok</th>
                        <th class="py-3.5 px-4 text-right" width="150">Harga Modal</th>
                        <th class="py-3.5 px-4 text-right" width="150">Harga Jual</th>
                        <th class="py-3.5 px-4 text-center" width="110">Margin</th>
                        <th class="py-3.5 px-4 text-center" width="180">Aksi</th>
                    </tr>
                </thead>
                <tbody class="text-xs text-slate-600 dark:text-slate-300 divide-y divide-slate-100 dark:divide-slate-700">
                    <?php $no = 1; ?>
                    <?php if(!empty($products)): ?>
                        <?php foreach($products as $row): ?>
                            <!-- Calculating percentage markup dynamic fallback to avoid zero division -->
                            <?php 
                                $modal = floatval($row['harga_modal']);
                                $jual = floatval($row['harga']);
                                $margin_percent = 0;
                                if ($modal > 0) {
                                    $margin_percent = (($jual - $modal) / $modal) * 100;
                                }
                                $isPoProduct = strtolower((string) ($row['stock_type'] ?? 'ready')) === 'po';
                            ?>
                            <tr class="hover:bg-slate-50/50 dark:hover:bg-slate-900/10 transition-all product-row-element"
                                data-name="<?= esc(strtolower($row['nama_product'])) ?>"
                                data-sku="<?= esc(strtolower($row['sku'] ?? '')) ?>"
                                data-barcode="<?= esc(strtolower($row['barcode'] ?? '')) ?>"
                                data-supplier="<?= esc(strtolower($row['nama_supplier'] ?? '')) ?>"
                                data-category="<?= esc(strtolower($row['nama_kategori'] ?? '')) ?>"
                                data-stok="<?= intval($row['stok']) ?>"
                                data-modal="<?= $modal ?>"
                                data-custom="<?= intval($row['is_custom']) ?>">
                                
                                <!-- No. -->
                                <td class="py-3.5 px-4 text-center font-semibold text-slate-400"><?= $no++ ?></td>
                                
                                <!-- Product Image with robust fallback -->
                                <td class="py-3.5 px-4">
                                    <div class="relative w-12 h-12 bg-slate-100 dark:bg-slate-700 rounded-xl overflow-hidden shadow-xs border border-slate-200 dark:border-slate-600">
                                        <?php if(!empty($row['product_photo'])): ?>
                                            <img src="<?= base_url('uploads/products/'.$row['product_photo']) ?>" 
                                                 onerror="this.onerror=null; this.src='https://placehold.co/100x100/cbd5e1/1e293b?text=<?= urlencode(substr($row['nama_product'], 0, 2)) ?>';" 
                                                 class="w-full h-full object-cover" 
                                                 alt="<?= esc($row['nama_product']) ?>">
                                        <?php else: ?>
                                            <div class="w-full h-full flex items-center justify-center font-bold text-slate-500 dark:text-slate-400 text-sm">
                                                <?= strtoupper(substr($row['nama_product'], 0, 2)) ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </td>

                                <!-- Detil Produk (Nama, Barcode, SKU) -->
                                <td class="py-3.5 px-4">
                                    <div class="font-bold text-slate-800 dark:text-slate-100 text-sm leading-tight hover:text-indigo-600 transition-colors">
                                        <?= esc($row['nama_product']) ?>
                                    </div>
                                    <div class="flex flex-col gap-0.5 mt-1 text-[10px] text-slate-400 font-medium">
                                        <?php if(!empty($row['sku'])): ?>
                                            <span>SKU: <span class="font-mono text-slate-500 dark:text-slate-300"><?= esc($row['sku']) ?></span></span>
                                        <?php endif; ?>
                                        <?php if(!empty($row['barcode'])): ?>
                                            <span>Barcode: <span class="font-mono text-slate-500 dark:text-slate-300"><?= esc($row['barcode']) ?></span></span>
                                        <?php endif; ?>
                                    </div>
                                    <!-- Tooltip Indicator if technical notes or descriptions are present -->
                                    <?php if(!empty($row['technical_notes']) || !empty($row['description'])): ?>
                                        <div class="mt-1 flex gap-1.5">
                                            <?php if(!empty($row['technical_notes'])): ?>
                                                <span class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-amber-50 dark:bg-amber-950/20 text-amber-600 dark:text-amber-400 text-[9px] font-semibold" title="Ada Catatan Teknis">
                                                    <i class="fas fa-microchip"></i> Notes
                                                </span>
                                            <?php endif; ?>
                                            <?php if(!empty($row['description'])): ?>
                                                <span class="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-300 text-[9px] font-semibold" title="<?= esc(strip_tags($row['description'])) ?>">
                                                    <i class="fas fa-file-text"></i> Deskripsi
                                                </span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                </td>

                                <!-- Kategori & Supplier -->
                                <td class="py-3.5 px-4">
                                    <span class="font-semibold text-slate-700 dark:text-slate-200 block text-xs">
                                        <?= esc($row['nama_kategori'] ?? 'Tidak Ada Kategori') ?>
                                    </span>
                                    <span class="text-[11px] text-slate-400 block mt-0.5">
                                        <i class="far fa-building mr-1"></i><?= esc($row['nama_supplier'] ?? 'Tanpa Supplier') ?>
                                    </span>
                                </td>

                                <!-- Jenis Produk (Custom vs Standard) -->
                                <td class="py-3.5 px-4">
                                    <?php if(intval($row['is_custom']) == 1): ?>
                                        <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-bold badge-cnc-custom">
                                            <i class="fas fa-screwdriver-wrench"></i> Custom CNC
                                        </span>
                                    <?php else: ?>
                                        <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[10px] font-bold badge-standard">
                                            <i class="fas fa-box"></i> Standard
                                        </span>
                                    <?php endif; ?>
                                </td>

                                <!-- Stok with interactive warnings -->
                                <td class="py-3.5 px-4 text-center">
                                    <?php if($isPoProduct): ?>
                                        <span class="inline-flex flex-col items-center">
                                            <span class="inline-flex items-center gap-1 px-2 py-1 rounded-full text-[10px] font-extrabold bg-amber-50 text-amber-700 border border-amber-200">
                                                <i class="fas fa-hourglass-half"></i> PO
                                            </span>
                                            <span class="text-[9px] font-semibold text-amber-600 mt-1 uppercase tracking-wide">Pre-Order</span>
                                        </span>
                                    <?php elseif(intval($row['stok']) < 10): ?>
                                        <span class="inline-flex flex-col items-center">
                                            <span class="inline-flex items-center gap-1 px-2 py-1 rounded-full text-[10px] font-extrabold badge-stock-alert">
                                                <i class="fas fa-triangle-exclamation"></i> <?= intval($row['stok']) ?>
                                            </span>
                                            <span class="text-[9px] font-semibold text-rose-500 mt-1 uppercase tracking-wide">Kritis</span>
                                        </span>
                                    <?php else: ?>
                                        <span class="font-extrabold text-slate-800 dark:text-slate-200 text-sm">
                                            <?= intval($row['stok']) ?>
                                        </span>
                                        <span class="text-[10px] text-slate-400 block mt-0.5 font-medium">unit</span>
                                    <?php endif; ?>
                                </td>

                                <!-- Harga Modal -->
                                <td class="py-3.5 px-4 text-right font-semibold text-slate-700 dark:text-slate-200">
                                    Rp <?= number_format($modal, 0, ',', '.') ?>
                                </td>

                                <!-- Harga Jual -->
                                <td class="py-3.5 px-4 text-right font-extrabold text-slate-900 dark:text-slate-100">
                                    Rp <?= number_format($jual, 0, ',', '.') ?>
                                </td>

                                <!-- Profit Markup Margin Percentage -->
                                <td class="py-3.5 px-4 text-center">
                                    <?php if($margin_percent > 40): ?>
                                        <span class="inline-flex px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-100 text-emerald-800 dark:bg-emerald-900/20 dark:text-emerald-400">
                                            +<?= number_format($margin_percent, 1) ?>%
                                        </span>
                                    <?php else: ?>
                                        <span class="inline-flex px-2 py-0.5 rounded text-[10px] font-bold bg-indigo-50 dark:bg-indigo-950/20 text-indigo-600 dark:text-indigo-400">
                                            +<?= number_format($margin_percent, 1) ?>%
                                        </span>
                                    <?php endif; ?>
                                </td>

                                <!-- Action Buttons -->
                                <td class="py-3.5 px-4 text-center">
                                    <div class="flex items-center justify-center gap-1.5">
                                        <!-- Detail Button -->
                                        <a href="<?= base_url('owner/product/detail/'.$row['id_product']) ?>" 
                                           class="btn bg-slate-100 hover:bg-slate-200 dark:bg-slate-700 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200 btn-sm rounded-lg px-2.5 py-1.5 text-[11px] border-0 transition-colors flex items-center gap-1" title="Lihat Spesifikasi Lengkap">
                                            <i class="fas fa-eye text-slate-400"></i> Detail
                                        </a>
                                        <!-- Edit Button -->
                                        <a href="<?= base_url('owner/product/edit/'.$row['id_product']) ?>" 
                                           class="btn bg-amber-50 hover:bg-amber-100 dark:bg-amber-950/20 dark:hover:bg-amber-900/30 text-amber-700 dark:text-amber-400 btn-sm rounded-lg px-2.5 py-1.5 text-[11px] border-0 transition-colors flex items-center gap-1" title="Edit Data">
                                            <i class="fas fa-pen"></i> Edit
                                        </a>
                                        <!-- Custom Delete Trigger - Replaces the forbidden Native Confirm window -->
                                        <button onclick="requestSecureDelete('<?= base_url('owner/product/delete/'.$row['id_product']) ?>', '<?= esc(addslashes($row['nama_product'])) ?>')" 
                                                class="btn bg-rose-50 hover:bg-rose-100 dark:bg-rose-950/20 dark:hover:bg-rose-900/30 text-rose-600 dark:text-rose-400 btn-sm rounded-lg px-2.5 py-1.5 text-[11px] border-0 transition-colors flex items-center gap-1" title="Hapus Permanen">
                                            <i class="fas fa-trash-can"></i> Hapus
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <!-- Table Empty Fallback -->
                        <tr>
                            <td colspan="10" class="py-12 text-center">
                                <div class="flex flex-col items-center justify-center text-slate-400">
                                    <i class="fas fa-cubes text-4xl mb-3 opacity-30"></i>
                                    <span class="text-sm font-semibold">Katalog Produk Kosong</span>
                                    <p class="text-xs text-slate-400 mt-1">Belum ada barang terintegrasi dengan database. Silakan klik Tambah Barang.</p>
                                </div>
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- CUSTOM CONFIRMATION OVERLAY MODAL (Replaces the forbidden window.confirm) -->
<div id="secureDeleteModal" class="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/60 backdrop-blur-xs hidden opacity-0 transition-all duration-300">
    <div class="bg-white dark:bg-slate-800 rounded-2xl max-w-md w-full overflow-hidden shadow-2xl transform scale-95 transition-transform duration-300 border border-slate-200 dark:border-slate-700">
        <!-- Danger top alert accent -->
        <div class="h-1.5 bg-rose-600 w-full"></div>
        <div class="p-6">
            <div class="w-12 h-12 rounded-full bg-rose-50 dark:bg-rose-950/30 text-rose-600 dark:text-rose-400 flex items-center justify-center text-xl mb-4">
                <i class="fas fa-triangle-exclamation"></i>
            </div>
            <h3 class="text-lg font-bold text-slate-900 dark:text-slate-100 mb-2">Hapus Produk Permanen?</h3>
            <p class="text-xs text-slate-500 leading-relaxed">
                Anda akan menghapus produk <span id="deleteItemName" class="font-extrabold text-slate-800 dark:text-slate-200"></span>. Tindakan ini akan menghapus entri dari database katalog, stok, dan tidak dapat dibatalkan.
            </p>
        </div>
        <div class="p-4 bg-slate-50 dark:bg-slate-900/40 border-t border-slate-100 dark:border-slate-700 flex justify-end gap-2">
            <!-- Dismiss action -->
            <button onclick="dismissSecureDelete()" class="px-4 py-2 text-xs font-semibold text-slate-500 dark:text-slate-300 bg-transparent hover:bg-slate-100 dark:hover:bg-slate-700/50 rounded-xl transition-all border-0">
                Batalkan
            </button>
            <!-- Proceed to secure anchor link action -->
            <a id="deleteAnchorConfirm" href="#" class="px-4 py-2 text-xs font-semibold text-white bg-rose-600 hover:bg-rose-700 rounded-xl shadow-sm transition-all text-center decoration-none no-underline flex items-center">
                Ya, Hapus Produk
            </a>
        </div>
    </div>
</div>

<!-- SheetJS Library for dynamic pure XLSX output -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

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

    // ==========================================
    // INVENTARIS INTELLIGENT METRICS ENGINE
    // ==========================================
    function calculateProductTelemetry() {
        const rows = document.querySelectorAll('.product-row-element');
        let totalItems = rows.length;
        let lowStockCount = 0;
        let totalValuation = 0;
        let customCount = 0;

        rows.forEach(row => {
            const stok = parseInt(row.getAttribute('data-stok')) || 0;
            const modal = parseFloat(row.getAttribute('data-modal')) || 0;
            const isCustom = parseInt(row.getAttribute('data-custom')) || 0;

            // Increment Low stock alerts (under 10 items)
            if (stok < 10) {
                lowStockCount++;
            }

            // Valuation accumulation (Stok * Modal per item)
            totalValuation += (stok * modal);

            // Fabrication counter
            if (isCustom === 1) {
                customCount++;
            }
        });

        // Set text properties inside layout UI
        document.getElementById('statTotalItems').innerText = totalItems;
        document.getElementById('statLowStock').innerText = lowStockCount;
        document.getElementById('statCustomCount').innerText = customCount;
        
        // Setup low stock animation visual hazard
        const alertIconBox = document.getElementById('alertStockIconBox');
        if (lowStockCount > 0) {
            alertIconBox.className = "w-12 h-12 bg-rose-100 dark:bg-rose-950/50 text-rose-600 dark:text-rose-400 rounded-xl flex items-center justify-center text-xl animate-pulse";
        } else {
            alertIconBox.className = "w-12 h-12 bg-slate-100 dark:bg-slate-800 text-slate-400 dark:text-slate-500 rounded-xl flex items-center justify-center text-xl";
        }

        // Beautiful format Currency Rupiah output
        document.getElementById('statValuation').innerText = new Intl.NumberFormat('id-ID', {
            style: 'currency',
            currency: 'IDR',
            maximumFractionDigits: 0
        }).format(totalValuation);
    }
    // Calculate once telemetry load completes
    calculateProductTelemetry();

    // ==========================================
    // CLIENT SEARCH FILTER ENGINE
    // ==========================================
    window.filterCatalogTable = function() {
        const query = document.getElementById('catalogSearch').value.toLowerCase().trim();
        const rows = document.querySelectorAll('.product-row-element');

        rows.forEach(row => {
            const name = row.getAttribute('data-name') || '';
            const sku = row.getAttribute('data-sku') || '';
            const barcode = row.getAttribute('data-barcode') || '';
            const supplier = row.getAttribute('data-supplier') || '';
            const category = row.getAttribute('data-category') || '';

            const matchesQuery = name.includes(query) || 
                                 sku.includes(query) || 
                                 barcode.includes(query) || 
                                 supplier.includes(query) || 
                                 category.includes(query);

            if (matchesQuery) {
                row.style.display = "";
            } else {
                row.style.display = "none";
            }
        });
    };

    // ==========================================
    // EXPORT DATABASE CATALOG TO EXCEL (SheetJS)
    // ==========================================
    window.exportProductsExcel = function() {
        const rows = document.querySelectorAll('.product-row-element');
        const exportData = [
            ["LAPORAN MASTER DATA BARANG & INVENTARIS"],
            ["Pusat Kontrol Finansial & Operasional Owner"],
            ["Waktu Ekspor Laporan", new Date().toLocaleString('id-ID')],
            [],
            ["NO", "NAMA PRODUK", "SKU", "BARCODE", "KATEGORI", "SUPPLIER", "STATUS PRODUK", "STOK", "MODAL (IDR)", "HARGA JUAL (IDR)", "MARGIN (%)"]
        ];

        let itemCounter = 1;
        rows.forEach(row => {
            const name = row.querySelector('.font-bold.text-slate-800').innerText.trim();
            const sku = row.getAttribute('data-sku').toUpperCase();
            const barcode = row.getAttribute('data-barcode').toUpperCase();
            const category = row.querySelector('td:nth-child(4) span').innerText.trim();
            const supplier = row.querySelector('td:nth-child(4) span:nth-child(2)').innerText.replace('...', '').trim();
            
            const isCustom = parseInt(row.getAttribute('data-custom')) === 1 ? "Custom CNC" : "Standard";
            const stok = parseInt(row.getAttribute('data-stok')) || 0;
            const modal = parseFloat(row.getAttribute('data-modal')) || 0;
            const markupPercentage = row.querySelector('td:nth-child(9) span').innerText.replace('+', '').trim();
            
            // Raw text fallback extraction for selling price index
            const sellingText = row.querySelector('td:nth-child(8)').innerText.replace(/[^\d]/g, '');
            const jual = parseFloat(sellingText) || 0;

            exportData.push([
                itemCounter++,
                name,
                sku || "-",
                barcode || "-",
                category,
                supplier,
                isCustom,
                stok,
                modal,
                jual,
                markupPercentage
            ]);
        });

        // Initialize Worksheet & Workbook structure
        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.aoa_to_sheet(exportData);

        // Styling Columns size
        ws['!cols'] = [
            { wch: 5 },  // No
            { wch: 30 }, // Name
            { wch: 15 }, // SKU
            { wch: 15 }, // Barcode
            { wch: 18 }, // Category
            { wch: 22 }, // Supplier
            { wch: 15 }, // Status
            { wch: 8 },  // Stok
            { wch: 16 }, // Modal
            { wch: 16 }, // Jual
            { wch: 12 }  // Margin
        ];

        XLSX.utils.book_append_sheet(wb, ws, "Katalog Produk");
        XLSX.writeFile(wb, "Data_Katalog_Inventaris_Owner.xlsx");
    };

    // ==========================================
    // SECURE CUSTOM DELETE SYSTEM OVERLAY MODAL
    // ==========================================
    const modalOverlay = document.getElementById('secureDeleteModal');
    const deleteTextEl = document.getElementById('deleteItemName');
    const deleteAnchor = document.getElementById('deleteAnchorConfirm');

    window.requestSecureDelete = function(deleteUrl, productName) {
        deleteTextEl.innerText = `"${productName}"`;
        deleteAnchor.setAttribute('href', deleteUrl);

        // Show smooth fade and pop animation
        modalOverlay.classList.remove('hidden');
        setTimeout(() => {
            modalOverlay.classList.remove('opacity-0');
            modalOverlay.querySelector('.scale-95').classList.remove('scale-95');
        }, 30);
    };

    window.dismissSecureDelete = function() {
        modalOverlay.classList.add('opacity-0');
        modalOverlay.querySelector('.transform').classList.add('scale-95');
        setTimeout(() => {
            modalOverlay.classList.add('hidden');
        }, 300);
    };

    // Handle background click dismissal
    modalOverlay.addEventListener('click', function(e) {
        if (e.target === modalOverlay) {
            dismissSecureDelete();
        }
    });

    // ==========================================
    // 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 animate-spin-slow";
        }
    };

    // Persist Dark Mode states on Page reload
    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 animate-spin-slow";
    }
});
</script>

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