<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aktivitas - Teratory SaaS</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;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: 'Plus Jakarta Sans', sans-serif; background-color: #E2E4E5; }
        .modal-enter { animation: fadeIn 0.2s ease-out forwards; }
        @keyframes fadeIn { from { opacity: 0; transform: scale(0.95); } to { opacity: 1; transform: scale(1); } }
        .custom-scrollbar::-webkit-scrollbar { height: 6px; width: 6px; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 10px; }
    </style>
</head>
<body class="min-h-screen text-gray-800 pb-32 relative">

    <div class="max-w-7xl mx-auto p-6">
        
        <!-- HEADER -->
        <div class="flex justify-between items-center mb-8">
            <h1 class="text-4xl lg:text-5xl font-extrabold text-[#5B8C5A] tracking-tight">Aktivitas</h1>
            <div class="flex items-center gap-6">
                <div class="text-[#5B8C5A] text-2xl cursor-pointer hover:scale-110 transition-transform"><i class="fa-solid fa-bell"></i></div>
                <a href="/profile" class="bg-white rounded-full pl-6 pr-2 py-2 shadow-sm flex items-center gap-4 hover:shadow-md transition-shadow cursor-pointer">
                    <div class="text-right leading-tight">
                        <p id="store-name" class="text-[#5B8C5A] font-bold text-sm">Memuat...</p>
                        <p id="user-name" class="text-[#5B8C5A] text-xs opacity-70">...</p>
                        <p id="user-role" class="text-[#5B8C5A] font-bold text-[10px] uppercase tracking-wider">...</p>
                    </div>
                    <img id="user-avatar" src="https://ui-avatars.com/api/?background=5B8C5A&color=fff" alt="Profile" class="w-12 h-12 rounded-full object-cover">
                </a>
            </div>
        </div>

        <!-- MAIN CONTENT GRID -->
        <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
            <!-- KIRI -->
            <div class="lg:col-span-8 flex flex-col gap-4">
                <div class="bg-white rounded-3xl p-6 shadow-sm flex items-center justify-between mb-2 border border-gray-100 relative overflow-hidden">
                    <div class="absolute right-0 top-0 w-40 h-40 bg-[#5B8C5A]/5 rounded-full -mr-10 -mt-10 blur-xl"></div>
                    <div class="flex items-center gap-5 relative z-10">
                        <div class="bg-[#5B8C5A] w-14 h-14 rounded-2xl flex items-center justify-center text-white shadow-md transform rotate-3">
                            <i class="fa-solid fa-book text-2xl -rotate-3"></i>
                        </div>
                        <div>
                            <h2 class="text-2xl font-extrabold text-gray-800 tracking-tight">Buku Besar</h2>
                            <p class="text-sm text-gray-500 font-semibold mt-0.5">Pantau seluruh arus kas dan jurnal transaksi</p>
                        </div>
                    </div>
                    <button onclick="openModal('modal-buku-besar')" class="relative z-10 bg-gray-50 text-[#5B8C5A] hover:text-white hover:bg-[#5B8C5A] px-6 py-3 rounded-xl font-bold shadow-sm transition-all duration-300 border border-gray-200 hover:border-transparent">Lihat Jurnal</button>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <button onclick="openModal('modal-bahan-baku')" class="bg-[#5B8C5A] text-white rounded-2xl p-5 flex items-center gap-4 shadow-sm hover:scale-[1.02] transition-transform w-full text-left"><i class="fa-regular fa-clipboard text-3xl"></i><span class="text-xl font-bold">Daftar Bahan Baku</span></button>
                    <button onclick="openFormBiaya()" class="bg-white text-[#5B8C5A] rounded-2xl p-5 flex items-center gap-4 shadow-sm hover:scale-[1.02] transition-transform w-full text-left"><i class="fa-solid fa-plus text-3xl"></i><span class="text-xl font-bold">Tambah Biaya</span></button>
                    <button onclick="openModal('modal-sub-bahan')" class="bg-[#5B8C5A] text-white rounded-2xl p-5 flex items-center gap-4 shadow-sm hover:scale-[1.02] transition-transform w-full text-left"><i class="fa-regular fa-clipboard text-3xl"></i><span class="text-xl font-bold">Daftar Sub Bahan</span></button>
                    <button onclick="openModal('modal-tambah-baru')" class="bg-white text-[#5B8C5A] rounded-2xl p-5 flex items-center gap-4 shadow-sm hover:scale-[1.02] transition-transform w-full text-left"><i class="fa-solid fa-plus text-3xl"></i><span class="text-xl font-bold">Tambah Baru</span></button>
                    <button onclick="openModal('modal-produk')" class="bg-[#5B8C5A] text-white rounded-2xl p-5 flex items-center gap-4 shadow-sm hover:scale-[1.02] transition-transform w-full text-left"><i class="fa-regular fa-clipboard text-3xl"></i><span class="text-xl font-bold">Daftar Produk</span></button>
                    <button onclick="openModal('modal-stok-opname')" class="bg-white text-[#5B8C5A] rounded-2xl p-5 flex items-center gap-4 shadow-sm hover:scale-[1.02] transition-transform w-full text-left"><i class="fa-solid fa-pen text-3xl"></i><span class="text-xl font-bold">Stok Opname</span></button>
                    <button onclick="openModal('modal-resep')" class="bg-[#5B8C5A] text-white rounded-2xl p-5 flex items-center gap-4 shadow-sm hover:scale-[1.02] transition-transform w-full text-left"><i class="fa-regular fa-clipboard text-3xl"></i><span class="text-xl font-bold">Daftar Resep</span></button>
                    <button onclick="openModal('modal-aktivitas-baru')" class="bg-white text-[#5B8C5A] rounded-2xl p-5 flex items-center gap-4 shadow-sm hover:scale-[1.02] transition-transform w-full text-left"><i class="fa-solid fa-plus text-3xl"></i><span class="text-xl font-bold">Aktivitas Baru</span></button>
                </div>
            </div>

            <!-- KANAN -->
            <div class="lg:col-span-4">
                <div class="bg-white rounded-3xl p-6 shadow-sm h-full">
                    <p class="text-gray-800 font-semibold mb-6">Tim Kami</p>
                    <div id="team-list" class="space-y-4">
                        <div class="flex items-center justify-end gap-4 border-b border-[#5B8C5A]/30 pb-4">
                            <div class="text-right"><p class="text-[#5B8C5A] font-bold text-lg">Sena</p><p class="text-[#5B8C5A] text-xs opacity-70">Planner</p></div>
                            <img src="https://ui-avatars.com/api/?name=Sena&background=5B8C5A&color=fff" class="w-12 h-12 rounded-full object-cover">
                        </div>
                        <div class="flex items-center justify-end gap-4 border-b border-[#5B8C5A]/30 pb-4">
                            <div class="text-right"><p class="text-[#5B8C5A] font-bold text-lg">Arya</p><p class="text-[#5B8C5A] text-xs opacity-70">Consultant</p></div>
                            <img src="https://ui-avatars.com/api/?name=Arya&background=5B8C5A&color=fff" class="w-12 h-12 rounded-full object-cover">
                        </div>
                        <div class="flex items-center justify-end gap-4 border-b border-[#5B8C5A]/30 pb-4">
                            <div class="text-right"><p class="text-[#5B8C5A] font-bold text-lg">Edwin</p><p class="text-[#5B8C5A] text-xs opacity-70">Owner</p></div>
                            <img src="https://ui-avatars.com/api/?name=Edwin&background=5B8C5A&color=fff" class="w-12 h-12 rounded-full object-cover">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- NAVBAR TIMBUL -->
    <nav class="fixed bottom-6 left-1/2 transform -translate-x-1/2 z-40">
        <div class="bg-[#5B8C5A] rounded-full flex items-center p-1.5 shadow-[0_10px_25px_rgba(0,0,0,0.2)] gap-2">
            <a href="/dashboard" class="flex items-center justify-center px-7 py-3 rounded-full hover:bg-white/10 opacity-50 hover:opacity-100 transition-all"><i class="fa-solid fa-chart-simple text-white text-2xl"></i></a>
            <a href="/aktivitas" class="flex items-center justify-center px-7 py-3 rounded-full bg-[#5B8C5A] shadow-[4px_4px_12px_rgba(0,0,0,0.3),-2px_-2px_8px_rgba(255,255,255,0.15)] opacity-100 transition-all"><i class="fa-solid fa-plus text-white text-3xl"></i></a>
            <a href="/settings" class="flex items-center justify-center px-7 py-3 rounded-full hover:bg-white/10 opacity-50 hover:opacity-100 transition-all"><i class="fa-solid fa-gear text-white text-2xl"></i></a>
        </div>
    </nav>

    <!-- Watermark Teratory -->
    <div class="fixed bottom-6 left-6 bg-white shadow-md rounded-full px-4 py-2 flex items-center gap-2 z-40">
        <img src="<?php echo e(asset('images/icon_teratory.png')); ?>" alt="T" class="w-6 h-6 object-contain">
        <span class="text-[#5B8C5A] font-bold text-sm">Teratory V.1.0.0.1</span>
    </div>

    <!-- ========================================== -->
    <!-- KUMPULAN MODAL POP-UP -->
    <!-- ========================================== -->

    <!-- Modal Buku Besar -->
    <div id="modal-buku-besar" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-5xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Jurnal Buku Besar</h3>
                <button onclick="closeModal('modal-buku-besar')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div class="flex justify-between items-center mb-4 gap-4">
                <div class="relative w-1/3">
                    <i class="fa-solid fa-magnifying-glass absolute left-3 top-2.5 text-gray-400 text-sm"></i>
                    <input type="text" placeholder="Cari transaksi..." class="w-full pl-9 pr-4 py-2 border border-gray-300 rounded-xl text-sm focus:outline-none focus:border-[#5B8C5A]">
                </div>
                <button onclick="closeModal('modal-buku-besar'); openFormBiaya();" class="bg-[#5B8C5A] hover:bg-[#487547] text-white px-5 py-2 rounded-xl text-sm font-bold shadow-sm transition-colors flex items-center gap-2">
                    <i class="fa-solid fa-plus"></i> Jurnal Manual
                </button>
            </div>
            <div class="overflow-y-auto custom-scrollbar border border-gray-200 rounded-xl flex-grow h-64">
                <table class="w-full text-left text-sm whitespace-nowrap">
                    <thead class="bg-gray-50 border-b border-gray-200 text-gray-600 sticky top-0 z-10">
                        <tr><th class="p-4 font-bold">Tanggal</th><th class="p-4 font-bold">Kategori</th><th class="p-4 font-bold">Deskripsi</th><th class="p-4 font-bold text-center">Tipe</th><th class="p-4 font-bold text-right">Jumlah (IDR)</th><th class="p-4 font-bold text-center">Aksi</th></tr>
                    </thead>
                    <tbody id="buku-besar-body" class="divide-y divide-gray-100"></tbody>
                </table>
            </div>
            <div id="buku-besar-pagination" class="flex justify-between items-center mt-6"></div>
        </div>
    </div>

    <!-- Modal Daftar Bahan Baku -->
    <div id="modal-bahan-baku" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-4xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-6 shrink-0">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Daftar Bahan Baku</h3>
                <button onclick="closeModal('modal-bahan-baku')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div id="container-bahan-baku" class="bg-gray-50 rounded-xl flex-grow overflow-hidden flex flex-col items-center justify-center border border-dashed border-gray-300">
                <i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i>
                <p class="text-gray-500 font-semibold">Memuat data...</p>
            </div>
        </div>
    </div>

    <!-- Modal Daftar Sub Bahan -->
    <div id="modal-sub-bahan" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-4xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-6 shrink-0">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Daftar Sub Bahan</h3>
                <button onclick="closeModal('modal-sub-bahan')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div id="container-sub-bahan" class="bg-gray-50 rounded-xl flex-grow overflow-hidden flex flex-col items-center justify-center border border-dashed border-gray-300">
                <i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i>
                <p class="text-gray-500 font-semibold">Memuat data...</p>
            </div>
        </div>
    </div>

    <!-- Modal Daftar Produk -->
    <div id="modal-produk" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-4xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-6 shrink-0">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Daftar Produk</h3>
                <button onclick="closeModal('modal-produk')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div id="container-produk" class="bg-gray-50 rounded-xl flex-grow overflow-hidden flex flex-col items-center justify-center border border-dashed border-gray-300">
                <i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i>
                <p class="text-gray-500 font-semibold">Memuat data...</p>
            </div>
        </div>
    </div>

    <!-- Modal Daftar Resep -->
    <div id="modal-resep" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-4xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-6 shrink-0">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Daftar Resep & Komposisi</h3>
                <button onclick="closeModal('modal-resep')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div id="container-resep" class="bg-gray-50 rounded-xl flex-grow overflow-hidden flex flex-col items-center justify-center border border-dashed border-gray-300">
                <i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i>
                <p class="text-gray-500 font-semibold">Memuat data...</p>
            </div>
        </div>
    </div>

    <!-- Modal Tambah/Edit Biaya -->
    <div id="modal-tambah-biaya" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-lg mx-4 shadow-2xl modal-enter">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-2xl font-bold text-[#5B8C5A]" id="title-modal-biaya">Tambah Biaya</h3>
                <button type="button" onclick="cancelFormBiaya()" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <form id="form-tambah-biaya" class="space-y-4 text-left">
                <div>
                    <label class="text-sm font-bold text-gray-700">Deskripsi</label>
                    <input type="text" id="expense-desc" placeholder="Cth: Tagihan Listrik PLN" class="w-full border border-gray-300 rounded-xl p-3 mt-1 focus:outline-none focus:border-[#5B8C5A] focus:ring-1 focus:ring-[#5B8C5A]">
                </div>
                <div class="grid grid-cols-2 gap-4" id="container-qty">
                    <div>
                        <label class="text-sm font-bold text-gray-700">Kuantitas</label>
                        <input type="number" id="expense-qty" value="1" min="1" class="w-full border border-gray-300 rounded-xl p-3 mt-1 focus:outline-none focus:border-[#5B8C5A] focus:ring-1 focus:ring-[#5B8C5A]">
                    </div>
                    <div>
                        <label class="text-sm font-bold text-gray-700">Harga Satuan (IDR)</label>
                        <input type="number" id="expense-amount" placeholder="0" min="0" class="w-full border border-gray-300 rounded-xl p-3 mt-1 focus:outline-none focus:border-[#5B8C5A] focus:ring-1 focus:ring-[#5B8C5A]">
                    </div>
                </div>
                <div>
                    <label class="text-sm font-bold text-gray-700">Kategori Pengeluaran</label>
                    <input list="category-options" id="expense-category" placeholder="Ketik atau pilih kategori..." class="w-full border border-gray-300 rounded-xl p-3 mt-1 focus:outline-none focus:border-[#5B8C5A] bg-white">
                    <datalist id="category-options"></datalist>
                </div>
                <div>
                    <label class="text-sm font-bold text-gray-700">Keterangan <span class="text-gray-400 font-normal">(Opsional)</span></label>
                    <textarea id="expense-notes" rows="2" class="w-full border border-gray-300 rounded-xl p-3 mt-1 focus:outline-none focus:border-[#5B8C5A] focus:ring-1 focus:ring-[#5B8C5A]"></textarea>
                </div>
                <button type="button" id="btn-simpan-biaya" onclick="submitExpense()" class="w-full bg-[#5B8C5A] text-white font-bold py-3.5 rounded-xl mt-2 hover:bg-[#487547] transition-colors shadow-md">Simpan Biaya</button>
            </form>
        </div>
    </div>

    <!-- Modal Tambah Baru (DIPERBAIKI: Kalkulator HPP & UI Kontras) -->
    <div id="modal-tambah-baru" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-lg mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-6 shrink-0">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Tambah Data Baru</h3>
                <button onclick="closeModal('modal-tambah-baru')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            
            <div class="overflow-y-auto custom-scrollbar pr-2 flex-grow space-y-5 text-left">
                <!-- UI Kontras Pilihan Tab -->
                <div class="grid grid-cols-3 gap-2 bg-gray-100 p-1.5 rounded-xl">
                    <button type="button" id="btn-type-bahan_baku" onclick="switchItemType('bahan_baku')" class="bg-[#5B8C5A] shadow-md text-white py-2 rounded-lg font-bold text-sm transition-all duration-300">Bahan Baku</button>
                    <button type="button" id="btn-type-sub_bahan" onclick="switchItemType('sub_bahan')" class="text-gray-500 hover:bg-white/50 py-2 rounded-lg font-bold text-sm transition-all duration-300">Sub Bahan</button>
                    <button type="button" id="btn-type-produk" onclick="switchItemType('produk')" class="text-gray-500 hover:bg-white/50 py-2 rounded-lg font-bold text-sm transition-all duration-300">Produk</button>
                </div>

                <div>
                    <label class="text-sm font-bold text-gray-700">Nama Data Baru</label>
                    <input type="text" id="new-item-name" placeholder="Cth: Biji Kopi Arabica" class="w-full border border-gray-300 rounded-xl p-3 mt-1 focus:outline-none focus:border-[#5B8C5A]">
                </div>

                <div class="grid grid-cols-2 gap-4 items-start">
                    <div>
                        <label class="text-sm font-bold text-gray-700">Satuan (UOM)</label>
                        <input type="text" id="new-item-uom" placeholder="Cth: Gram" class="w-full border border-gray-300 rounded-xl p-3 mt-1 focus:outline-none focus:border-[#5B8C5A]">
                    </div>
                    <div id="container-harga-jual" style="display: none;">
                        <label class="text-sm font-bold text-gray-700">Harga Jual (Opsional)</label>
                        <input type="number" id="new-item-price" placeholder="0" class="w-full border border-gray-300 rounded-xl p-3 mt-1 focus:outline-none focus:border-[#5B8C5A]">
                    </div>
                </div>

                <!-- Kalkulator Harga Beli / HPP Awal -->
                <div id="container-harga-beli" class="bg-gray-50 p-4 rounded-xl border border-gray-200 block">
                    <p class="text-sm font-bold text-[#5B8C5A] mb-3 border-b border-gray-200 pb-2">Setup Harga Beli / HPP Awal</p>
                    <div class="grid grid-cols-12 gap-3 items-end">
                        <div class="col-span-12 md:col-span-5">
                            <label class="text-xs font-bold text-[#5B8C5A]">Metode Input</label>
                            <select id="new-item-metode-hpp" onchange="toggleHppMaster()" class="w-full border border-[#5B8C5A]/30 rounded-lg p-2 text-sm mt-1 text-[#5B8C5A] font-semibold focus:outline-none bg-white">
                                <option value="manual">Harga per UOM</option>
                                <option value="kalkulator">Kalkulator Total</option>
                            </select>
                        </div>
                        <div class="col-span-6 md:col-span-3" id="new-item-qty-container" style="display: none;">
                            <label class="text-xs font-bold text-gray-700">Kuantitas</label>
                            <input type="number" id="new-item-qty" oninput="hitungHppMaster()" value="1" min="1" class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-[#5B8C5A] focus:outline-none bg-white">
                        </div>
                        <div class="col-span-6 md:col-span-4">
                            <label class="text-xs font-bold text-gray-700 truncate" id="new-item-label-harga">Nominal (IDR)</label>
                            <input type="number" id="new-item-harga-input" oninput="hitungHppMaster()" placeholder="0" min="0" class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-[#5B8C5A] focus:outline-none bg-white">
                        </div>
                    </div>
                    <div class="mt-3 text-right">
                        <p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">Hasil HPP / UOM Dasar</p>
                        <p class="text-lg font-extrabold text-[#5B8C5A] leading-none" id="new-item-hasil-hpp">Rp 0</p>
                    </div>
                </div>

                <div class="border-t border-gray-200 pt-4 mt-2" id="section-resep" style="display: none;">
                    <div class="flex justify-between items-center mb-2">
                        <label class="text-sm font-bold text-gray-700">Resep Pembentuk <span class="text-gray-400 font-normal">(Opsional)</span></label>
                        <button type="button" onclick="addKomposisiRow()" class="text-xs font-bold text-[#5B8C5A] bg-[#5B8C5A]/10 px-3 py-1 rounded-full hover:bg-[#5B8C5A]/20 transition-colors"><i class="fa-solid fa-plus mr-1"></i>Tambah Komposisi</button>
                    </div>
                    <div id="empty-resep" class="bg-gray-50 p-4 rounded-xl border border-dashed border-gray-300 text-center text-sm text-gray-500">
                        Belum ada komposisi resep yang ditambahkan.
                    </div>
                    <div id="komposisi-container" class="space-y-2 mt-2 max-h-32 overflow-y-auto custom-scrollbar"></div>
                    
                    <!-- KUNCI MUTLAK: Kalkulator Hasil Jadi (Yield) -->
                    <div id="kalkulator-sub-bahan" class="mt-4 bg-[#5B8C5A]/5 p-4 rounded-xl border border-[#5B8C5A]/20 hidden">
                        <div class="grid grid-cols-2 gap-4 items-center mb-3 border-b border-[#5B8C5A]/20 pb-3">
                            <div>
                                <label class="text-xs font-bold text-[#5B8C5A]">Hasil Jadi (Output)</label>
                                <div class="flex items-center mt-1 shadow-sm">
                                    <input type="number" id="resep-hasil-jadi" oninput="hitungHppResep()" placeholder="Cth: 1500" min="1" class="w-full border border-[#5B8C5A]/30 rounded-l-lg p-2 text-sm focus:outline-none focus:border-[#5B8C5A] bg-white">
                                    <span class="bg-[#5B8C5A]/10 text-[#5B8C5A] border border-l-0 border-[#5B8C5A]/30 rounded-r-lg p-2 text-sm font-bold truncate max-w-[80px]" id="label-uom-hasil">UOM</span>
                                </div>
                            </div>
                            <div class="text-right">
                                <p class="text-[10px] font-bold text-gray-500 uppercase tracking-wider">Total Modal Panci</p>
                                <p class="text-lg font-bold text-gray-800" id="resep-total-modal">Rp 0</p>
                            </div>
                        </div>
                        <div class="text-right">
                            <p class="text-[10px] font-bold text-[#5B8C5A] uppercase tracking-wider mb-1">HASIL HPP / UOM DASAR</p>
                            <p class="text-2xl font-extrabold text-[#5B8C5A] leading-none" id="resep-hpp-akhir">Rp 0</p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="mt-4 pt-4 border-t border-gray-200 shrink-0">
                <button type="button" onclick="submitNewItem()" class="w-full bg-[#5B8C5A] text-white font-bold py-3.5 rounded-xl hover:bg-[#487547] transition-colors shadow-md">Simpan Data Baru</button>
            </div>
        </div>
    </div>

    <!-- Modal Stok Opname -->
    <div id="modal-stok-opname" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-3xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-4 shrink-0">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Stok Opname</h3>
                <button type="button" onclick="closeModal('modal-stok-opname')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            
            <!-- TABS NAVIGATION -->
            <div class="flex border-b border-gray-200 mb-4 shrink-0">
                <button type="button" id="tab-btn-sisa" onclick="switchOpnameTab('sisa')" class="py-2.5 px-4 border-b-2 border-[#5B8C5A] text-[#5B8C5A] font-bold text-sm w-1/3 transition-colors">Sisa Stok</button>
                <button type="button" id="tab-btn-lakukan" onclick="switchOpnameTab('lakukan')" class="py-2.5 px-4 border-b-2 border-transparent text-gray-500 font-semibold hover:text-[#5B8C5A] text-sm w-1/3 transition-colors">Lakukan</button>
                <button type="button" id="tab-btn-riwayat" onclick="switchOpnameTab('riwayat')" class="py-2.5 px-4 border-b-2 border-transparent text-gray-500 font-semibold hover:text-[#5B8C5A] text-sm w-1/3 transition-colors">Riwayat</button>
            </div>

            <!-- CONTENT AREA -->
            <div class="overflow-y-auto custom-scrollbar flex-grow pr-2">
                
                <!-- TAB 1: SISA STOK -->
                <div id="opname-tab-sisa" class="block">
                    <div class="bg-gray-50 rounded-xl w-full min-h-[250px] flex flex-col items-center justify-center border border-dashed border-gray-300 p-6" id="opname-sisa-container">
                        <i class="fa-solid fa-boxes-stacked text-4xl text-gray-300 mb-3"></i>
                        <p class="text-gray-500 font-semibold">Klik tab 'Lakukan' untuk memulai opname.</p>
                    </div>
                </div>

                <!-- TAB 2: LAKUKAN OPNAME -->
                <div id="opname-tab-lakukan" class="hidden space-y-4 text-left">
                    <div class="bg-blue-50 border border-blue-100 rounded-2xl p-5">
                        <p class="text-xs text-blue-700 font-bold mb-4"><i class="fa-solid fa-circle-info mr-1"></i> Input fisik gudang pada kolom yang tersedia. Selisih dan nominal uang akan terhitung otomatis.</p>
                        
                        <!-- TABEL INPUT MASAL -->
                        <div class="overflow-x-auto bg-white rounded-xl border border-gray-200 custom-scrollbar max-h-[40vh]">
                            <table class="w-full text-left text-sm whitespace-nowrap">
                                <thead class="bg-gray-100 border-b sticky top-0 z-10">
                                    <tr>
                                        <th class="p-3 font-bold">Barang (UOM)</th>
                                        <th class="p-3 font-bold text-center text-gray-500">Sistem</th>
                                        <th class="p-3 font-bold text-center text-[#5B8C5A]">Fisik Gudang</th>
                                        <th class="p-3 font-bold text-center">Selisih</th>
                                        <th class="p-3 font-bold text-right">Nilai Uang (Rp)</th>
                                    </tr>
                                </thead>
                                <tbody id="opname-lakukan-tbody" class="divide-y divide-gray-100">
                                    <!-- Baris di-generate via JS -->
                                </tbody>
                            </table>
                        </div>

                        <div class="mt-4">
                            <input list="alasan-opname-list" id="opname-global-notes" placeholder="Catatan global untuk opname ini (Opsional)" class="w-full border border-gray-300 rounded-lg p-2.5 text-sm focus:border-[#5B8C5A] focus:outline-none bg-white">
                            <datalist id="alasan-opname-list">
                                <option value="Barang Rusak / Expired">
                                <option value="Kesalahan Input Bulan Lalu">
                                <option value="Penyusutan Normal">
                            </datalist>
                        </div>
                        
                        <div class="mt-5 text-right border-t border-blue-100 pt-4">
                            <button type="button" onclick="submitOpname()" class="bg-[#5B8C5A] hover:bg-[#487547] text-white px-8 py-3 rounded-xl font-bold shadow-md transition-colors w-full md:w-auto">Simpan Hasil Opname</button>
                        </div>
                    </div>
                </div>

                <!-- TAB 3: RIWAYAT -->
                <div id="opname-tab-riwayat" class="hidden">
                    <div class="bg-gray-50 rounded-xl w-full min-h-[250px] flex flex-col items-center justify-center border border-dashed border-gray-300 p-6" id="opname-riwayat-container">
                        <i class="fa-solid fa-clock-rotate-left text-4xl text-gray-300 mb-3"></i>
                        <p class="text-gray-500 font-semibold">Riwayat opname sedang dibangun di backend.</p>
                    </div>
                </div>
                
            </div>
        </div>
    </div>

    <!-- Modal Aktivitas Baru -->
    <div id="modal-aktivitas-baru" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-md mx-4 shadow-2xl modal-enter">
            <div class="flex justify-between items-center mb-6">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Aktivitas Baru</h3>
                <button type="button" onclick="closeModal('modal-aktivitas-baru')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <p class="text-center text-gray-600 mb-6 font-medium">Pilih jenis aktivitas transaksi yang ingin Anda lakukan.</p>
            <div class="grid grid-cols-2 gap-4">
                <button type="button" onclick="event.preventDefault(); pindahModal('modal-aktivitas-baru', 'modal-stok-masuk');" class="bg-[#5B8C5A] text-white rounded-2xl p-6 flex flex-col items-center justify-center gap-3 shadow-md hover:scale-[1.03] transition-transform border-2 border-transparent">
                    <i class="fa-solid fa-arrow-right-to-bracket text-4xl"></i>
                    <span class="font-bold text-lg">Stok Masuk</span>
                </button>
                <button type="button" onclick="event.preventDefault(); pindahModal('modal-aktivitas-baru', 'modal-stok-keluar');" class="bg-white border-2 border-[#D32F2F] text-[#D32F2F] rounded-2xl p-6 flex flex-col items-center justify-center gap-3 shadow-md hover:scale-[1.03] hover:bg-red-50 transition-all">
                    <i class="fa-solid fa-arrow-right-from-bracket text-4xl"></i>
                    <span class="font-bold text-lg">Stok Keluar</span>
                </button>
            </div>
        </div>
    </div>

    <!-- Modal Stok Masuk -->
    <div id="modal-stok-masuk" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-3xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-2xl font-bold text-[#5B8C5A]">Input Stok Masuk</h3>
                <button type="button" onclick="closeModal('modal-stok-masuk')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div class="overflow-y-auto custom-scrollbar pr-2 flex-grow space-y-4" id="stok-masuk-container">
                <div class="bg-gray-50 border border-gray-200 rounded-2xl p-4 relative masuk-row" id="masuk-row-1">
                    <div class="grid grid-cols-12 gap-4 mb-3">
                        <div class="col-span-5">
                            <label class="text-xs font-bold text-gray-700">Pilih Barang</label>
                            <!-- KUNCI: Tambahkan onchange di sini -->
                            <select id="item-masuk-1" onchange="autoFillUomMasuk(1)" class="stok-item-select w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-[#5B8C5A] focus:outline-none bg-white">
                                <option value="">Pilih item...</option>
                            </select>
                        </div>
                        <div class="col-span-3">
                            <label class="text-xs font-bold text-gray-700">Kuantitas</label>
                            <input type="number" oninput="hitungHppMasuk(1)" id="qty-masuk-1" placeholder="0" class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-[#5B8C5A] focus:outline-none">
                        </div>
                        <div class="col-span-4">
                            <label class="text-xs font-bold text-gray-700">Satuan (UOM)</label>
                            <!-- KUNCI: Buat readonly dan berikan background abu-abu -->
                            <input type="text" id="uom-masuk-1" placeholder="Otomatis" class="w-full border border-gray-200 rounded-lg p-2 text-sm mt-1 bg-gray-100 text-gray-500 cursor-not-allowed focus:outline-none" readonly>
                        </div>
                    </div>
                    <div class="grid grid-cols-12 gap-4 items-end bg-white p-3 rounded-xl border border-gray-100">
                        <div class="col-span-5">
                            <label class="text-xs font-bold text-[#5B8C5A]">Metode Input HPP</label>
                            <select id="metode-hpp-1" onchange="toggleHppMasuk(1)" class="w-full border border-[#5B8C5A]/30 rounded-lg p-2 text-sm mt-1 text-[#5B8C5A] font-semibold focus:outline-none bg-white">
                                <option value="kalkulator">Kalkulator Total Harga</option>
                                <option value="manual">Input Harga per UOM</option>
                            </select>
                        </div>
                        <div class="col-span-4" id="container-input-harga-1">
                            <label class="text-xs font-bold text-gray-700" id="label-harga-1">Total Pembayaran (IDR)</label>
                            <input type="number" oninput="hitungHppMasuk(1)" id="harga-masuk-1" placeholder="0" class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-[#5B8C5A] focus:outline-none">
                        </div>
                        <div class="col-span-3 pb-2 text-right">
                            <p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">Hasil HPP / UOM</p>
                            <p class="text-lg font-extrabold text-[#5B8C5A] leading-none" id="hasil-hpp-1">Rp 0</p>
                        </div>
                    </div>
                </div>
            </div>
            <div class="mt-4 border-t border-gray-200 pt-4 flex justify-between gap-4">
                <button type="button" onclick="addStokMasukRow()" class="bg-[#5B8C5A]/10 text-[#5B8C5A] hover:bg-[#5B8C5A]/20 px-4 py-3 rounded-xl font-bold flex items-center transition-colors">
                    <i class="fa-solid fa-plus mr-2"></i> Tambah Item
                </button>
                <button type="button" onclick="submitStokMasuk()" class="bg-[#5B8C5A] hover:bg-[#487547] text-white px-8 py-3 rounded-xl font-bold shadow-md transition-colors flex-grow">
                    Simpan Stok Masuk
                </button>
            </div>
        </div>
    </div>

    <!-- Modal Stok Keluar -->
    <div id="modal-stok-keluar" class="fixed inset-0 bg-black/60 z-50 hidden flex items-center justify-center backdrop-blur-sm">
        <div class="bg-white rounded-3xl p-8 w-full max-w-2xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col">
            <div class="flex justify-between items-center mb-4">
                <h3 class="text-2xl font-bold text-[#D32F2F]">Input Stok Keluar</h3>
                <button type="button" onclick="closeModal('modal-stok-keluar')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
            </div>
            <div class="overflow-y-auto custom-scrollbar pr-2 flex-grow space-y-3" id="stok-keluar-container">
                <div class="bg-red-50 border border-red-100 rounded-2xl p-4 relative keluar-row" id="keluar-row-1">
                    <div class="grid grid-cols-12 gap-3">
                        <div class="col-span-5">
                            <label class="text-xs font-bold text-gray-700">Pilih Barang</label>
                            <select id="item-keluar-1" class="stok-item-select w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-red-400 focus:outline-none bg-white">
                                <option value="">Pilih item...</option>
                            </select>
                        </div>
                        <div class="col-span-3">
                            <label class="text-xs font-bold text-gray-700">Kuantitas</label>
                            <input type="number" id="qty-keluar-1" placeholder="0" class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-red-400 focus:outline-none">
                        </div>
                        <div class="col-span-4">
                            <label class="text-xs font-bold text-gray-700">Alasan Keluar</label>
                            <!-- KUNCI MUTLAK: Mengganti Select dengan Datalist -->
                            <input list="alasan-keluar-list" id="alasan-keluar-1" placeholder="Ketik atau Pilih..." class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-red-400 focus:outline-none bg-white">
                            <datalist id="alasan-keluar-list">
                                <option value="Rusak / Bocor">
                                <option value="Expired">
                                <option value="Konsumsi Karyawan">
                            </datalist>
                        </div>
                    </div>
                </div>
            </div>
            <div class="mt-4 border-t border-gray-200 pt-4 flex justify-between gap-4">
                <button type="button" onclick="addStokKeluarRow()" class="bg-red-50 text-[#D32F2F] hover:bg-red-100 px-4 py-3 rounded-xl font-bold flex items-center transition-colors">
                    <i class="fa-solid fa-plus mr-2"></i> Tambah Item
                </button>
                <button type="button" onclick="submitStokKeluar()" class="bg-[#D32F2F] hover:bg-red-800 text-white px-8 py-3 rounded-xl font-bold shadow-md transition-colors flex-grow">
                    Simpan Stok Keluar
                </button>
            </div>
        </div>
    </div>

    <!-- ========================================== -->
    <!-- JAVASCRIPT LOGIC (CLEAN & ANTI DOMINO ERROR) -->
    <!-- ========================================== -->
    <script>
        const token = localStorage.getItem('teratory_sso_token');
        const storeId = 1;
        
        // KUNCI MUTLAK: Tambahkan 2 baris ini yang sempat terhapus
        let masukRowCount = 1;
        let keluarRowCount = 1;
        
        let editLedgerId = null;
        let currentEditResepId = null;
        let newItemType = 'bahan_baku'; 
        let finalHppMaster = 0; 
        let komposisiCount = 0;
        let cacheBahanBaku = [];

        if (!token) { window.location.href = "/login"; }
        function formatIDR(val) { return new Intl.NumberFormat('id-ID').format(val); }

       function openModal(modalId) {
            const el = document.getElementById(modalId);
            if(el) el.classList.remove('hidden');
            
            // Trigger Load Data
            if (modalId === 'modal-buku-besar') loadBukuBesar(1);
            else if (modalId === 'modal-bahan-baku') loadDaftarBahanBaku();
            else if (modalId === 'modal-sub-bahan') loadDaftarDenganResep('sub_bahan', 'container-sub-bahan');
            else if (modalId === 'modal-produk') loadDaftarDenganResep('produk', 'container-produk');
            else if (modalId === 'modal-resep') loadSemuaResep();
            else if (modalId === 'modal-tambah-baru') fetchBahanBakuForResep(); 
            
            // KUNCI MUTLAK: Pisahkan jalur untuk Stok agar server lokal tidak macet!
            else if (modalId === 'modal-stok-masuk' || modalId === 'modal-stok-keluar') {
                fetchAllItemsForStok(); 
            }
            else if (modalId === 'modal-stok-opname') {
                switchOpnameTab('sisa'); 
            }
        }

        // FUNGSI KHUSUS TRANSISI MODAL
        // FUNGSI KHUSUS TRANSISI MODAL
        function pindahModal(modalTutup, modalBuka) {
            // Tutup modal pertama
            document.getElementById(modalTutup).classList.add('hidden');
            
            // Beri jeda 150 milidetik agar animasi tertutup selesai dulu, baru buka yang baru
            setTimeout(() => {
                const elemenBuka = document.getElementById(modalBuka);
                if (elemenBuka) {
                    elemenBuka.classList.remove('hidden');
                    
                    // KUNCI MUTLAK: Tembak API jika modal yang dibuka adalah urusan Stok
                    if (modalBuka === 'modal-stok-masuk' || modalBuka === 'modal-stok-keluar') {
                        if (typeof fetchAllItemsForStok === "function") {
                            fetchAllItemsForStok();
                        }
                    }
                } else {
                    console.warn("Modal target tidak ditemukan: " + modalBuka);
                }
            }, 150);
        }

        function closeModal(modalId) {
            const el = document.getElementById(modalId);
            if(el) el.classList.add('hidden');
        }

        async function fetchAPI(endpoint, method = 'GET', body = null) {
            const options = { method: method, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` } };
            if (body) options.body = JSON.stringify(body);
            const res = await fetch(`http://localhost:8000/api${endpoint}`, options);
            return await res.json();
        }

        document.addEventListener('DOMContentLoaded', async () => {
            try { await loadHeaderProfile(); } catch(e) {}
            try { await loadExpenseCategories(); } catch(e) {}
            try { await fetchBahanBakuForResep(); } catch(e) {}
        });

        async function loadHeaderProfile() {
            const res = await fetchAPI('/profile');
            if (res.status === 'success') {
                document.getElementById('store-name').innerText = res.data.store_name;
                document.getElementById('user-name').innerText = res.data.user_name;
                document.getElementById('user-role').innerText = res.data.role;
                document.getElementById('user-avatar').src = `https://ui-avatars.com/api/?name=${res.data.user_name}&background=5B8C5A&color=fff`;
            }
        }

        async function loadExpenseCategories() {
            const res = await fetchAPI(`/transactions/expense-categories?store_id=${storeId}`);
            if (res.status === 'success') {
                const datalist = document.getElementById('category-options');
                datalist.innerHTML = '';
                res.data.forEach(cat => { datalist.innerHTML += `<option value="${cat}">`; });
            }
        }

        // 1. TIMPA FUNGSI INI: Agar menarik Bahan Baku DAN Sub Bahan sekaligus
        async function fetchBahanBakuForResep() {
            try {
                // KUNCI MUTLAK: Menggunakan Promise.all agar 2 API ditarik bersamaan
                const [resBahan, resSub] = await Promise.all([
                    fetchAPI(`/master/items?store_id=${storeId}&type=bahan_baku`),
                    fetchAPI(`/master/items?store_id=${storeId}&type=sub_bahan`)
                ]);
                cacheBahanBaku = [];
                if(resBahan.status === 'success') cacheBahanBaku = cacheBahanBaku.concat(resBahan.data);
                if(resSub.status === 'success') cacheBahanBaku = cacheBahanBaku.concat(resSub.data);
            } catch (e) { console.warn("Gagal memuat daftar bahan."); }
        }

        // 2. TIMPA FUNGSI INI: Agar di dropdown terlihat bedanya mana Bahan Baku, mana Sub Bahan
        function buildKomposisiOptions(selectedId = '') {
            let html = '<option value="">Pilih bahan...</option>';
            cacheBahanBaku.forEach(b => {
                const sel = b.id == selectedId ? 'selected' : '';
                // Tambahkan penanda visual agar user tidak bingung
                const marker = b.type === 'sub_bahan' ? ' [Sub]' : ''; 
                html += `<option value="${b.id}" ${sel}>${b.name}${marker} (${b.uom})</option>`;
            });
            return html;
        }

        // ==========================================
        // FITUR: BUKU BESAR & BIAYA
        // ==========================================
        async function loadBukuBesar(page = 1) {
            const tbody = document.getElementById('buku-besar-body');
            tbody.innerHTML = '<tr><td colspan="6" class="p-4 text-center text-gray-500 font-semibold py-10"><i class="fa-solid fa-spinner fa-spin mr-2"></i>Memuat jurnal...</td></tr>';
            try {
                const res = await fetchAPI(`/transactions/ledger?store_id=${storeId}&page=${page}`);
                if (res.status === 'success') {
                    tbody.innerHTML = '';
                    if(res.data.data.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="6" class="p-4 text-center text-gray-500 font-semibold py-10">Belum ada transaksi.</td></tr>';
                        return;
                    }
                    res.data.data.forEach(item => {
                        const dateStr = new Date(item.transaction_date).toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' });
                        const isMasuk = item.type === 'income';
                        const typeBadge = isMasuk ? `<span class="bg-green-100 text-green-600 px-3 py-1 rounded-full text-xs font-bold">Masuk</span>` : `<span class="bg-red-100 text-red-600 px-3 py-1 rounded-full text-xs font-bold">Keluar</span>`;
                        const amountColor = isMasuk ? 'text-green-600' : 'text-red-600';
                        let cat = item.category || '-'; if (cat === 'sales_revenue') cat = 'Stok Keluar';
                        
                        tbody.innerHTML += `
                            <tr class="hover:bg-gray-50 transition-colors border-b border-gray-50">
                                <td class="p-4 text-gray-600">${dateStr}</td>
                                <td class="p-4 font-semibold text-gray-800">${cat}</td>
                                <td class="p-4 text-gray-600 truncate max-w-xs">${item.description || '-'}</td>
                                <td class="p-4 text-center">${typeBadge}</td>
                                <td class="p-4 text-right font-bold ${amountColor}">${formatIDR(item.amount)}</td>
                                <td class="p-4 text-center flex justify-center gap-3">
                                    <button onclick="prepareEditLedger(${item.id}, \`${item.description || ''}\`, ${item.amount}, \`${item.category || ''}\`)" class="text-blue-500 hover:text-blue-700 transition-colors"><i class="fa-solid fa-pen-to-square"></i></button>
                                    <button onclick="deleteLedger(${item.id})" class="text-red-500 hover:text-red-700 transition-colors"><i class="fa-solid fa-trash"></i></button>
                                </td>
                            </tr>
                        `;
                    });
                }
            } catch (e) { tbody.innerHTML = '<tr><td colspan="6" class="p-4 text-center text-red-500 font-bold">Gagal memuat.</td></tr>'; }
        }

        function openFormBiaya() {
            editLedgerId = null;
            document.getElementById('form-tambah-biaya').reset();
            document.getElementById('title-modal-biaya').innerText = "Tambah Biaya";
            document.getElementById('btn-simpan-biaya').innerText = "Simpan Biaya";
            document.getElementById('container-qty').classList.remove('hidden');
            openModal('modal-tambah-biaya');
        }

        function cancelFormBiaya() {
            closeModal('modal-tambah-biaya');
            document.getElementById('form-tambah-biaya').reset();
            if (editLedgerId) { openModal('modal-buku-besar'); editLedgerId = null; }
        }

        function prepareEditLedger(id, desc, amount, category) {
            editLedgerId = id;
            document.getElementById('expense-desc').value = desc;
            document.getElementById('expense-qty').value = 1;
            document.getElementById('expense-amount').value = amount; 
            document.getElementById('expense-category').value = category;
            document.getElementById('container-qty').classList.remove('hidden');
            document.getElementById('title-modal-biaya').innerText = "Update Jurnal";
            document.getElementById('btn-simpan-biaya').innerText = "Update Jurnal";
            closeModal('modal-buku-besar');
            openModal('modal-tambah-biaya');
        }

        async function submitExpense() {
            const desc = document.getElementById('expense-desc').value;
            const qty = document.getElementById('expense-qty').value || 1;
            const amount = document.getElementById('expense-amount').value;
            const category = document.getElementById('expense-category').value;

            if(!desc || !amount || !category) { alert("Harap isi lengkap!"); return; }

            const totalAmount = qty * amount;
            const endpoint = editLedgerId ? `/transactions/ledger/${editLedgerId}` : `/transactions/expense`;
            const method = editLedgerId ? 'PUT' : 'POST';

            try {
                const res = await fetchAPI(endpoint, method, { store_id: storeId, description: desc, qty: qty, amount: totalAmount, category: category });
                if (res.status === 'success') {
                    alert(res.message);
                    cancelFormBiaya();
                    loadExpenseCategories();
                } else alert("Gagal: " + res.message);
            } catch (e) { alert("Terjadi kesalahan."); }
        }

        async function deleteLedger(id) {
            if(!confirm("Hapus jurnal ini permanen?")) return;
            try {
                const res = await fetchAPI(`/transactions/ledger/${id}`, 'DELETE');
                if (res.status === 'success') { alert('Berhasil dihapus.'); loadBukuBesar(1); }
            } catch (e) {}
        }

        // ==========================================
        // FITUR: RENDER LIST MASTER & RESEP (Aman dari outerHTML)
        // ==========================================
        async function loadDaftarBahanBaku() {
            const container = document.getElementById('container-bahan-baku');
            container.innerHTML = '<i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i><p class="text-gray-500 font-semibold">Memuat data...</p>';
            try {
                const res = await fetchAPI(`/master/items?store_id=${storeId}&type=bahan_baku`);
                if (res.status === 'success' && res.data.length > 0) {
                    container.className = "bg-white border border-gray-200 rounded-xl flex-grow overflow-y-auto max-h-[60vh] custom-scrollbar";
                    let html = `<table class="w-full text-left text-sm whitespace-nowrap"><thead class="bg-gray-50 border-b sticky top-0"><tr><th class="p-4 font-bold">Nama Bahan</th><th class="p-4 font-bold text-center">UOM</th><th class="p-4 font-bold text-right">HPP Dasar</th><th class="p-4 font-bold text-center">Aksi</th></tr></thead><tbody class="divide-y divide-gray-100">`;
                    res.data.forEach(item => {
                        html += `<tr class="hover:bg-gray-50"><td class="p-4 font-bold text-gray-800">${item.name}</td><td class="p-4 text-center text-gray-600">${item.uom}</td><td class="p-4 text-right font-bold text-[#5B8C5A]">Rp ${formatIDR(item.price)}</td><td class="p-4 text-center"><button onclick="deleteMaster(${item.id}, 'bahan_baku')" class="text-red-500 hover:text-red-700 bg-red-50 p-2 rounded-lg"><i class="fa-solid fa-trash"></i></button></td></tr>`;
                    });
                    html += `</tbody></table>`;
                    container.innerHTML = html;
                } else {
                    container.className = "bg-gray-50 rounded-xl flex-grow overflow-hidden flex flex-col items-center justify-center border border-dashed border-gray-300";
                    container.innerHTML = '<i class="fa-solid fa-box-open text-4xl text-gray-300 mb-3"></i><p class="text-gray-500 font-semibold">Daftar kosong. Belum ada bahan baku.</p>';
                }
            } catch(e) { container.innerHTML = '<p class="text-red-500">Gagal memuat data.</p>'; }
        }

        async function loadDaftarDenganResep(type, containerId) {
            const container = document.getElementById(containerId);
            container.innerHTML = '<i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i><p class="text-gray-500 font-semibold">Memuat data...</p>';
            try {
                const res = await fetchAPI(`/master/items?store_id=${storeId}&type=${type}`);
                if (res.status === 'success' && res.data.length > 0) {
                    container.className = "w-full overflow-y-auto max-h-[60vh] custom-scrollbar space-y-4";
                    let html = '';
                    res.data.forEach(item => {
                        let rowResep = ''; let totalHpp = 0;
                        if (item.recipes && item.recipes.length > 0) {
                            item.recipes.forEach(r => {
                                const subTotal = r.qty * r.hpp_per_uom; totalHpp += subTotal;
                                rowResep += `<tr class="border-b border-gray-100 last:border-0"><td class="py-2 text-gray-700 text-xs">${r.material_name}</td><td class="py-2 text-center text-gray-700 text-xs">${r.qty} ${r.uom}</td><td class="py-2 text-right text-gray-700 text-xs font-semibold">Rp ${formatIDR(subTotal)}</td></tr>`;
                            });
                        } else rowResep = '<tr><td colspan="3" class="py-4 text-center text-xs text-gray-400 italic">Resep belum diatur.</td></tr>';
                        
                        let badgeHarga = type === 'produk' ? `<span class="bg-blue-100 text-blue-700 px-3 py-1 rounded-lg text-xs font-bold ml-2">Jual: Rp ${formatIDR(item.price)}</span>` : '';
                        
                        html += `
                            <div class="bg-white border border-gray-200 rounded-2xl overflow-hidden shadow-sm">
                                <div class="bg-gray-50 p-4 flex justify-between items-center border-b">
                                    <div><h4 class="font-extrabold text-gray-800 text-lg">${item.name} <span class="text-xs text-gray-500 font-normal">/ ${item.uom}</span></h4><p class="text-xs text-[#5B8C5A] font-bold mt-1">Total HPP: Rp ${formatIDR(totalHpp)} ${badgeHarga}</p></div>
                                    <div class="flex gap-2">
                                        <button onclick="injectModalEditResep(${item.id}, '${item.name}', '${type}')" class="bg-blue-50 text-blue-600 px-3 py-1.5 rounded-lg text-xs font-bold hover:bg-blue-100"><i class="fa-solid fa-pen mr-1"></i> Edit Resep</button>
                                        <button onclick="deleteMaster(${item.id}, '${type}')" class="bg-red-50 text-red-500 px-3 py-1.5 rounded-lg text-xs font-bold hover:bg-red-100"><i class="fa-solid fa-trash"></i></button>
                                    </div>
                                </div>
                                <div class="p-4"><table class="w-full text-left"><thead class="text-gray-400 text-[10px] uppercase border-b"><tr><th class="pb-2">Bahan</th><th class="pb-2 text-center">Qty</th><th class="pb-2 text-right">Subtotal HPP</th></tr></thead><tbody>${rowResep}</tbody></table></div>
                            </div>
                        `;
                    });
                    container.innerHTML = html;
                } else {
                    container.className = "bg-gray-50 rounded-xl flex-grow overflow-hidden flex flex-col items-center justify-center border border-dashed border-gray-300";
                    container.innerHTML = '<i class="fa-solid fa-box-open text-4xl text-gray-300 mb-3"></i><p class="text-gray-500 font-semibold">Daftar kosong.</p>';
                }
            } catch(e) { container.innerHTML = '<p class="text-red-500">Gagal memuat data.</p>'; }
        }

        async function loadSemuaResep() {
            const container = document.getElementById('container-resep');
            container.innerHTML = '<div class="text-center w-full py-10"><i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i><p class="text-gray-500 font-semibold">Memuat resep secepat kilat...</p></div>';
            try {
                const [resSub, resProd] = await Promise.all([
                    fetchAPI(`/master/items?store_id=${storeId}&type=sub_bahan`),
                    fetchAPI(`/master/items?store_id=${storeId}&type=produk`)
                ]);
                
                let allData = [];
                if(resSub.status === 'success') allData = allData.concat(resSub.data);
                if(resProd.status === 'success') allData = allData.concat(resProd.data);

                if (allData.length > 0) {
                    container.className = "w-full overflow-y-auto max-h-[60vh] custom-scrollbar space-y-4";
                    let html = '';
                    allData.forEach(item => {
                        let rowResep = ''; let totalHpp = 0;
                        if (item.recipes && item.recipes.length > 0) {
                            item.recipes.forEach(r => {
                                const subTotal = r.qty * r.hpp_per_uom; totalHpp += subTotal;
                                rowResep += `<tr class="border-b border-gray-100 last:border-0"><td class="py-2 text-gray-700 text-xs">${r.material_name}</td><td class="py-2 text-center text-gray-700 text-xs">${r.qty} ${r.uom}</td><td class="py-2 text-right text-gray-700 text-xs font-semibold">Rp ${formatIDR(subTotal)}</td></tr>`;
                            });
                        } else rowResep = '<tr><td colspan="3" class="py-4 text-center text-xs text-gray-400 italic">Resep belum diatur.</td></tr>';
                        
                        const badgeType = item.type === 'produk' ? '<span class="bg-blue-100 text-blue-700 px-2 py-0.5 rounded text-[10px] uppercase font-bold ml-2">Produk</span>' : '<span class="bg-orange-100 text-orange-700 px-2 py-0.5 rounded text-[10px] uppercase font-bold ml-2">Sub Bahan</span>';
                        html += `
                            <div class="bg-white border border-gray-200 rounded-2xl overflow-hidden shadow-sm">
                                <div class="bg-gray-50 p-4 flex justify-between items-center border-b">
                                    <div><h4 class="font-extrabold text-gray-800 text-lg">${item.name} ${badgeType}</h4><p class="text-xs text-[#5B8C5A] font-bold mt-1">Total HPP: Rp ${formatIDR(totalHpp)}</p></div>
                                    <button onclick="injectModalEditResep(${item.id}, '${item.name}', 'resep')" class="bg-blue-50 text-blue-600 px-3 py-1.5 rounded-lg text-xs font-bold hover:bg-blue-100"><i class="fa-solid fa-pen mr-1"></i> Edit Resep</button>
                                </div>
                                <div class="p-4"><table class="w-full text-left"><thead class="text-gray-400 text-[10px] uppercase border-b"><tr><th class="pb-2">Bahan</th><th class="pb-2 text-center">Qty</th><th class="pb-2 text-right">Subtotal</th></tr></thead><tbody>${rowResep}</tbody></table></div>
                            </div>
                        `;
                    });
                    container.innerHTML = html;
                } else {
                    container.className = "bg-gray-50 rounded-xl flex-grow overflow-hidden flex flex-col items-center justify-center border border-dashed border-gray-300";
                    container.innerHTML = '<i class="fa-solid fa-box-open text-4xl text-gray-300 mb-3"></i><p class="text-gray-500 font-semibold">Belum ada resep.</p>';
                }
            } catch(e) {}
        }

        async function deleteMaster(id, type) {
            if(!confirm("Yakin hapus data ini? Resep yang terhubung ikut terhapus.")) return;
            try {
                const res = await fetchAPI(`/master/items/${id}`, 'DELETE');
                if(res.status === 'success') {
                    if(type === 'bahan_baku') loadDaftarBahanBaku();
                    else if(type === 'sub_bahan') loadDaftarDenganResep('sub_bahan', 'container-sub-bahan');
                    else if(type === 'produk') loadDaftarDenganResep('produk', 'container-produk');
                } else alert("Gagal: " + res.message);
            } catch(e) {}
        }

        // ==========================================
        // FITUR BARU: MODAL EDIT RESEP MANDIRI
        // ==========================================
        async function injectModalEditResep(itemId, itemName, originMode) {
            currentEditResepId = itemId;
            
            // Buat HTML Modal Mandiri Jika Belum Ada
            if(!document.getElementById('modal-edit-resep-dinamis')) {
                const modalHtml = `
                <div id="modal-edit-resep-dinamis" class="fixed inset-0 bg-black/80 z-[60] flex items-center justify-center backdrop-blur-sm">
                    <div class="bg-white rounded-3xl p-8 w-full max-w-2xl mx-4 shadow-2xl modal-enter max-h-[90vh] flex flex-col text-left">
                        <div class="flex justify-between items-center mb-6 shrink-0">
                            <div><h3 class="text-2xl font-bold text-blue-600">Edit Resep</h3><p class="text-gray-500 text-sm font-semibold" id="edit-resep-title-name">Memuat...</p></div>
                            <button onclick="document.getElementById('modal-edit-resep-dinamis').classList.add('hidden')" class="text-gray-400 hover:text-red-500 text-2xl"><i class="fa-solid fa-xmark"></i></button>
                        </div>
                        <div class="overflow-y-auto custom-scrollbar pr-2 flex-grow text-left">
                            <div class="flex justify-between items-center mb-3">
                                <label class="text-sm font-bold text-gray-700">Komposisi Saat Ini</label>
                                <button type="button" onclick="addEditKomposisiRow()" class="text-xs font-bold text-blue-600 bg-blue-50 px-3 py-1 rounded-full hover:bg-blue-100 transition-colors"><i class="fa-solid fa-plus mr-1"></i>Tambah Komposisi</button>
                            </div>
                            <div id="edit-komposisi-container" class="space-y-3 mt-2"></div>
                        </div>
                        <div class="mt-4 pt-4 border-t border-gray-200 shrink-0">
                            <button type="button" onclick="submitEditResep('${originMode}')" class="w-full bg-blue-600 text-white font-bold py-3.5 rounded-xl hover:bg-blue-700 transition-colors shadow-md">Simpan Perubahan Resep</button>
                        </div>
                    </div>
                </div>`;
                document.body.insertAdjacentHTML('beforeend', modalHtml);
            }
            
            const modal = document.getElementById('modal-edit-resep-dinamis');
            modal.classList.remove('hidden');
            document.getElementById('edit-resep-title-name').innerText = itemName;
            const container = document.getElementById('edit-komposisi-container');
            container.innerHTML = '<p class="text-gray-500 text-sm italic">Memuat resep asli...</p>';
            
            closeModal('modal-sub-bahan'); closeModal('modal-produk'); closeModal('modal-resep');
            
            try {
                await fetchBahanBakuForResep(); // refresh cache
                const res = await fetchAPI(`/master/items/${itemId}/recipes`);
                container.innerHTML = '';
                if(res.status === 'success' && res.data.length > 0) {
                    res.data.forEach(r => addEditKomposisiRow(r.material_id, r.qty));
                } else addEditKomposisiRow();
            } catch(e) { container.innerHTML = '<p class="text-red-500 text-sm">Gagal memuat resep asli.</p>'; }
        }

        function addEditKomposisiRow(matId = '', qty = '') {
            const container = document.getElementById('edit-komposisi-container');
            const rowId = 'edit-row-' + Math.random().toString(36).substr(2, 9);
            const rowHtml = `
                <div class="flex items-center gap-2 mb-2" id="${rowId}">
                    <select class="edit-resep-bahan w-2/3 border border-gray-300 rounded-lg p-2 text-sm focus:border-blue-500 focus:outline-none bg-white">${buildKomposisiOptions(matId)}</select>
                    <input type="number" value="${qty}" placeholder="Qty" class="edit-resep-qty w-1/4 border border-gray-300 rounded-lg p-2 text-sm focus:border-blue-500 focus:outline-none">
                    <button type="button" onclick="document.getElementById('${rowId}').remove()" class="text-red-500 hover:bg-red-50 rounded-lg p-2"><i class="fa-solid fa-trash"></i></button>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', rowHtml);
        }

        async function submitEditResep(originMode) {
            const rows = document.getElementById('edit-komposisi-container').children;
            let recipes = [];
            for(let i=0; i<rows.length; i++) {
                const mId = rows[i].querySelector('.edit-resep-bahan').value;
                const qty = rows[i].querySelector('.edit-resep-qty').value;
                if(mId && qty) recipes.push({ material_id: mId, qty: qty });
            }
            try {
                const res = await fetchAPI(`/master/items/${currentEditResepId}/recipes`, 'PUT', { recipes: recipes });
                if(res.status === 'success') {
                    alert('Resep berhasil diperbarui!');
                    document.getElementById('modal-edit-resep-dinamis').classList.add('hidden');
                    if(originMode === 'sub_bahan') { openModal('modal-sub-bahan'); loadDaftarDenganResep('sub_bahan', 'container-sub-bahan'); }
                    else if(originMode === 'produk') { openModal('modal-produk'); loadDaftarDenganResep('produk', 'container-produk'); }
                    else { openModal('modal-resep'); loadSemuaResep(); }
                } else alert("Gagal: " + res.message);
            } catch(e) { alert("Terjadi kesalahan."); }
        }

        // ==========================================
        // FITUR: TAMBAH BARU (KALKULATOR & UI KONTRAS)
        // ==========================================
        function switchItemType(type) {
            newItemType = type;
            ['bahan_baku', 'sub_bahan', 'produk'].forEach(t => {
                document.getElementById(`btn-type-${t}`).className = "text-gray-500 hover:bg-white/50 py-2 rounded-lg font-bold text-sm transition-all duration-300";
            });
            document.getElementById(`btn-type-${type}`).className = "bg-[#5B8C5A] shadow-md text-white py-2 rounded-lg font-bold text-sm transition-all duration-300";

            if(type === 'bahan_baku') {
                document.getElementById('section-resep').style.display = 'none';
                document.getElementById('container-harga-beli').style.display = 'block';
                document.getElementById('container-harga-jual').style.display = 'none';
                document.getElementById('kalkulator-sub-bahan').classList.add('hidden');
            } else {
                document.getElementById('section-resep').style.display = 'block';
                document.getElementById('container-harga-beli').style.display = 'none';
                
                // Kalkulator Yield muncul untuk Sub Bahan & Produk
                document.getElementById('kalkulator-sub-bahan').classList.remove('hidden');
                
                if (type === 'produk') {
                    document.getElementById('container-harga-jual').style.display = 'block';
                } else {
                    document.getElementById('container-harga-jual').style.display = 'none';
                }
            }
        }

        function toggleHppMaster() {
            const method = document.getElementById('new-item-metode-hpp').value;
            const label = document.getElementById('new-item-label-harga');
            const containerQty = document.getElementById('new-item-qty-container');

            if (method === 'kalkulator') { label.innerText = 'Total Pembayaran (IDR)'; containerQty.style.display = 'block'; } 
            else { label.innerText = 'Harga per UOM (IDR)'; containerQty.style.display = 'none'; document.getElementById('new-item-qty').value = 1; }
            hitungHppMaster();
        }

        function hitungHppMaster() {
            const method = document.getElementById('new-item-metode-hpp').value;
            const qty = parseFloat(document.getElementById('new-item-qty').value) || 0;
            const harga = parseFloat(document.getElementById('new-item-harga-input').value) || 0;
            const hasilText = document.getElementById('new-item-hasil-hpp');

            if (method === 'kalkulator') finalHppMaster = qty > 0 ? (harga / qty) : 0;
            else finalHppMaster = harga;
            hasilText.innerText = 'Rp ' + formatIDR(finalHppMaster);
        }

        function addKomposisiRow() {
            komposisiCount++;
            document.getElementById('empty-resep').style.display = 'none';
            const container = document.getElementById('komposisi-container');
            const rowId = 'komposisi-row-' + Math.random().toString(36).substr(2, 9);
            // KUNCI: Tambahkan onchange dan oninput agar memicu hitungHppResep()
            const rowHtml = `
                <div class="flex items-center gap-2 mb-2" id="${rowId}">
                    <select onchange="hitungHppResep()" class="tambah-baru-bahan w-2/3 border border-gray-300 rounded-lg p-2 text-sm focus:outline-none focus:border-[#5B8C5A] bg-white">${buildKomposisiOptions()}</select>
                    <input type="number" oninput="hitungHppResep()" placeholder="Qty" class="tambah-baru-qty w-1/4 border border-gray-300 rounded-lg p-2 text-sm focus:outline-none focus:border-[#5B8C5A]">
                    <button type="button" onclick="document.getElementById('${rowId}').remove(); hitungHppResep();" class="text-red-500 hover:bg-red-50 rounded-lg p-2"><i class="fa-solid fa-trash"></i></button>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', rowHtml);
        }

        function hitungHppResep() {
            const rows = document.getElementById('komposisi-container').children;
            let totalModal = 0;

            // Loop untuk mengkalkulasi total uang yang masuk ke panci
            for(let i=0; i<rows.length; i++) {
                const matSelect = rows[i].querySelector('.tambah-baru-bahan');
                const qtyInput = rows[i].querySelector('.tambah-baru-qty');
                
                if (matSelect && qtyInput) {
                    const mId = matSelect.value;
                    const qty = parseFloat(qtyInput.value) || 0;
                    if (mId && qty > 0) {
                        const itemData = cacheBahanBaku.find(x => x.id == mId);
                        if (itemData) {
                            totalModal += (parseFloat(itemData.price) * qty);
                        }
                    }
                }
            }
            document.getElementById('resep-total-modal').innerText = 'Rp ' + formatIDR(totalModal);

            // Bagi dengan Hasil Jadi
            const hasilJadi = parseFloat(document.getElementById('resep-hasil-jadi').value) || 0;
            if (hasilJadi > 0) {
                finalHppResep = totalModal / hasilJadi;
            } else {
                finalHppResep = 0;
            }
            document.getElementById('resep-hpp-akhir').innerText = 'Rp ' + formatIDR(finalHppResep);
        }

        async function submitNewItem() {
            const name = document.getElementById('new-item-name').value;
            const uom = document.getElementById('new-item-uom').value;
            
            // KUNCI MUTLAK: Pengambilan harga cerdas sesuai tipe!
            let price = 0;
            if (newItemType === 'bahan_baku') {
                price = finalHppMaster;
            } else if (newItemType === 'sub_bahan') {
                price = finalHppResep; // Ambil dari kalkulator hasil jadi!
            } else {
                price = parseFloat(document.getElementById('new-item-price').value) || 0; // Produk pakai harga jual
            }

            if(!name || !uom) { alert("Nama dan Satuan (UOM) wajib diisi!"); return; }

            let recipes = [];
            if (newItemType !== 'bahan_baku') {
                const rows = document.getElementById('komposisi-container').children;
                for(let i=0; i<rows.length; i++) {
                    const mId = rows[i].querySelector('.tambah-baru-bahan').value;
                    const qty = rows[i].querySelector('.tambah-baru-qty').value;
                    if(mId && qty) recipes.push({ material_id: mId, qty: qty });
                }
            }

            try {
                const res = await fetchAPI('/master/items', 'POST', { store_id: storeId, type: newItemType, name: name, uom: uom, price: price, recipes: recipes });
                if(res.status === 'success') {
                    alert(res.message);
                    closeModal('modal-tambah-baru');
                    document.getElementById('new-item-name').value = '';
                    document.getElementById('new-item-uom').value = '';
                    document.getElementById('new-item-price').value = '';
                    document.getElementById('resep-hasil-jadi').value = ''; // Reset
                    document.getElementById('resep-total-modal').innerText = 'Rp 0';
                    document.getElementById('resep-hpp-akhir').innerText = 'Rp 0';
                    document.getElementById('komposisi-container').innerHTML = '';
                    document.getElementById('empty-resep').style.display = 'block';
                    fetchBahanBakuForResep(); 
                } else alert("Gagal: " + res.message);
            } catch(e) { alert("Kesalahan jaringan."); }
        }

        // ==========================================
        // FITUR STOK MASUK & KELUAR
        // ==========================================
        let cacheAllItems = [];

        // Kunci: Fungsi menarik semua data item untuk dropdown stok
        async function fetchAllItemsForStok() {
            try {
                const [resBahan, resSub, resProd] = await Promise.all([
                    fetchAPI(`/master/items?store_id=${storeId}&type=bahan_baku`),
                    fetchAPI(`/master/items?store_id=${storeId}&type=sub_bahan`),
                    fetchAPI(`/master/items?store_id=${storeId}&type=produk`)
                ]);
                
                cacheAllItems = [];
                if(resBahan.status === 'success') cacheAllItems = cacheAllItems.concat(resBahan.data);
                if(resSub.status === 'success') cacheAllItems = cacheAllItems.concat(resSub.data);
                if(resProd.status === 'success') cacheAllItems = cacheAllItems.concat(resProd.data);

                let optionsHtml = '<option value="">Pilih item...</option>';
                cacheAllItems.forEach(item => {
                    optionsHtml += `<option value="${item.id}">${item.name} (${item.uom})</option>`;
                });

                document.querySelectorAll('.stok-item-select').forEach(select => {
                    let prevVal = select.value;
                    select.innerHTML = optionsHtml;
                    if(prevVal) select.value = prevVal;
                });
            } catch (e) { console.warn("Gagal memuat item untuk stok."); }
        }

        // ==========================================
        // OVERRIDE OPEN MODAL (DIPERBARUI)
        // ==========================================
        function buildStokItemOptions() {
            let html = '<option value="">Pilih item...</option>';
            cacheAllItems.forEach(item => {
                html += `<option value="${item.id}">${item.name} (${item.uom})</option>`;
            });
            return html;
        }

        function toggleHppMasuk(id) {
            const method = document.getElementById(`metode-hpp-${id}`).value;
            const label = document.getElementById(`label-harga-${id}`);
            if (method === 'kalkulator') { label.innerText = 'Total Pembayaran (IDR)'; } 
            else { label.innerText = 'Harga per UOM (IDR)'; }
            hitungHppMasuk(id);
        }

        function hitungHppMasuk(id) {
            const method = document.getElementById(`metode-hpp-${id}`).value;
            const qty = parseFloat(document.getElementById(`qty-masuk-${id}`).value) || 0;
            const harga = parseFloat(document.getElementById(`harga-masuk-${id}`).value) || 0;
            const hasilText = document.getElementById(`hasil-hpp-${id}`);

            if (method === 'kalkulator') {
                const hpp = qty > 0 ? (harga / qty) : 0;
                hasilText.innerText = 'Rp ' + formatIDR(hpp);
            } else {
                hasilText.innerText = 'Rp ' + formatIDR(harga);
            }
        }

        function autoFillUomMasuk(rowId) {
            const selectEl = document.getElementById(`item-masuk-${rowId}`);
            const uomInput = document.getElementById(`uom-masuk-${rowId}`);
            if (selectEl && uomInput) {
                const itemId = selectEl.value;
                if (!itemId) { uomInput.value = ''; return; }
                const selectedItem = cacheAllItems.find(item => item.id == itemId);
                if (selectedItem) { uomInput.value = selectedItem.uom; }
            }
        }

        function addStokMasukRow() {
            masukRowCount++;
            const container = document.getElementById('stok-masuk-container');
            const rowHtml = `
                <div class="bg-gray-50 border border-gray-200 rounded-2xl p-4 relative masuk-row mt-4" id="masuk-row-${masukRowCount}">
                    <button type="button" onclick="removeRow('masuk-row-${masukRowCount}')" class="absolute -right-2 -top-2 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center shadow-md hover:bg-red-600"><i class="fa-solid fa-xmark text-xs"></i></button>
                    <div class="grid grid-cols-12 gap-4 mb-3">
                        <div class="col-span-5">
                            <label class="text-xs font-bold text-gray-700">Pilih Barang</label>
                            <select id="item-masuk-${masukRowCount}" onchange="autoFillUomMasuk(${masukRowCount})" class="stok-item-select w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-[#5B8C5A] focus:outline-none bg-white">
                                ${buildStokItemOptions()}
                            </select>
                        </div>
                        <div class="col-span-3">
                            <label class="text-xs font-bold text-gray-700">Kuantitas</label>
                            <input type="number" oninput="hitungHppMasuk(${masukRowCount})" id="qty-masuk-${masukRowCount}" placeholder="0" class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-[#5B8C5A] focus:outline-none">
                        </div>
                        <div class="col-span-4">
                            <label class="text-xs font-bold text-gray-700">Satuan (UOM)</label>
                            <input type="text" id="uom-masuk-${masukRowCount}" placeholder="Otomatis" class="w-full border border-gray-200 rounded-lg p-2 text-sm mt-1 bg-gray-100 text-gray-500 cursor-not-allowed focus:outline-none" readonly>
                        </div>
                    </div>
                    <div class="grid grid-cols-12 gap-4 items-end bg-white p-3 rounded-xl border border-gray-100">
                        <div class="col-span-5">
                            <label class="text-xs font-bold text-[#5B8C5A]">Metode Input HPP</label>
                            <select id="metode-hpp-${masukRowCount}" onchange="toggleHppMasuk(${masukRowCount})" class="w-full border border-[#5B8C5A]/30 rounded-lg p-2 text-sm mt-1 text-[#5B8C5A] font-semibold focus:outline-none bg-white">
                                <option value="kalkulator">Kalkulator Total Harga</option>
                                <option value="manual">Input Harga per UOM</option>
                            </select>
                        </div>
                        <div class="col-span-4" id="container-input-harga-${masukRowCount}">
                            <label class="text-xs font-bold text-gray-700" id="label-harga-${masukRowCount}">Total Pembayaran (IDR)</label>
                            <input type="number" oninput="hitungHppMasuk(${masukRowCount})" id="harga-masuk-${masukRowCount}" placeholder="0" class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-[#5B8C5A] focus:outline-none">
                        </div>
                        <div class="col-span-3 pb-2 text-right">
                            <p class="text-[10px] font-bold text-gray-400 uppercase tracking-wider mb-1">Hasil HPP / UOM</p>
                            <p class="text-lg font-extrabold text-[#5B8C5A] leading-none" id="hasil-hpp-${masukRowCount}">Rp 0</p>
                        </div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', rowHtml);
            container.scrollTop = container.scrollHeight;
        }

        function addStokKeluarRow() {
            keluarRowCount++;
            const container = document.getElementById('stok-keluar-container');
            const rowHtml = `
                <div class="bg-red-50 border border-red-100 rounded-2xl p-4 relative keluar-row mt-3" id="keluar-row-${keluarRowCount}">
                    <button type="button" onclick="removeRow('keluar-row-${keluarRowCount}')" class="absolute -right-2 -top-2 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center shadow-md hover:bg-red-600"><i class="fa-solid fa-xmark text-xs"></i></button>
                    <div class="grid grid-cols-12 gap-3">
                        <div class="col-span-5">
                            <label class="text-xs font-bold text-gray-700">Pilih Barang</label>
                            <select id="item-keluar-${keluarRowCount}" class="stok-item-select w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-red-400 focus:outline-none bg-white">
                                ${buildStokItemOptions()}
                            </select>
                        </div>
                        <div class="col-span-3">
                            <label class="text-xs font-bold text-gray-700">Kuantitas</label>
                            <input type="number" id="qty-keluar-${keluarRowCount}" placeholder="0" class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-red-400 focus:outline-none">
                        </div>
                        <div class="col-span-4">
                            <label class="text-xs font-bold text-gray-700">Alasan Keluar</label>
                            <input list="alasan-keluar-list" id="alasan-keluar-${keluarRowCount}" placeholder="Ketik atau Pilih..." class="w-full border border-gray-300 rounded-lg p-2 text-sm mt-1 focus:border-red-400 focus:outline-none bg-white">
                        </div>
                    </div>
                </div>
            `;
            container.insertAdjacentHTML('beforeend', rowHtml);
            container.scrollTop = container.scrollHeight;
        }

        function removeRow(rowId) {
            const el = document.getElementById(rowId);
            if(el) el.remove();
        }

        async function submitStokMasuk() {
            const rows = document.querySelectorAll('.masuk-row');
            let items = [];
            let isValid = true;

            rows.forEach(row => {
                const itemSelect = row.querySelector('.stok-item-select');
                const qtyInput = row.querySelector('[id^="qty-masuk-"]');
                const hargaInput = row.querySelector('[id^="harga-masuk-"]');
                const metodeSelect = row.querySelector('[id^="metode-hpp-"]');

                if (itemSelect && qtyInput) {
                    const itemId = itemSelect.value;
                    const qty = parseFloat(qtyInput.value) || 0;
                    const harga = hargaInput ? parseFloat(hargaInput.value) || 0 : 0;
                    const metode = metodeSelect ? metodeSelect.value : 'kalkulator';

                    let finalHpp = 0;
                    if (metode === 'kalkulator') finalHpp = qty > 0 ? (harga / qty) : 0;
                    else finalHpp = harga;

                    if (itemId && qty > 0) {
                        items.push({ item_id: itemId, qty: qty, hpp: finalHpp });
                    } else {
                        isValid = false;
                    }
                }
            });

            if (!isValid || items.length === 0) {
                alert("Peringatan: Harap pilih barang dan pastikan kuantitas minimal 1 pada setiap baris!");
                return;
            }

            try {
                const res = await fetchAPI('/inventories/add', 'POST', { store_id: storeId, items: items });
                
                if (res.status === 'success') {
                    alert("Stok Masuk berhasil dicatat!");
                    closeModal('modal-stok-masuk');
                    
                    document.querySelectorAll('.masuk-row').forEach((r, idx) => { if(idx > 0) r.remove(); });
                    document.getElementById('qty-masuk-1').value = '';
                    if(document.getElementById('harga-masuk-1')) document.getElementById('harga-masuk-1').value = '';
                    document.getElementById('item-masuk-1').value = '';
                    if(document.getElementById('hasil-hpp-1')) document.getElementById('hasil-hpp-1').innerText = 'Rp 0';
                    if(document.getElementById('uom-masuk-1')) document.getElementById('uom-masuk-1').value = '';
                    
                    loadBukuBesar(1); 
                } else {
                    alert("Gagal: " + (res.message || "Terjadi kesalahan di server."));
                }
            } catch(e) { alert("Gagal menghubungi server API."); }
        }

        async function submitStokKeluar() {
            const rows = document.querySelectorAll('.keluar-row');
            let items = [];
            let isValidQty = true;
            let isValidAlasan = true;

            rows.forEach(row => {
                const itemSelect = row.querySelector('.stok-item-select');
                const qtyInput = row.querySelector('[id^="qty-keluar-"]');
                const alasanInput = row.querySelector('[id^="alasan-keluar-"]');

                if (itemSelect && qtyInput && alasanInput) {
                    const itemId = itemSelect.value;
                    const qty = parseFloat(qtyInput.value) || 0;
                    
                    // Kunci peringatan Alasan
                    const alasan = alasanInput.value.trim(); 
                    if (alasan === "") isValidAlasan = false;

                    if (itemId && qty > 0) {
                        items.push({ item_id: itemId, qty: qty, notes: alasan });
                    } else {
                        isValidQty = false;
                    }
                }
            });

            if (!isValidQty || items.length === 0) {
                alert("Peringatan: Harap pilih barang dan pastikan kuantitas minimal 1 pada setiap baris!");
                return; 
            }

            if (!isValidAlasan) {
                alert("Peringatan: Harap isi Alasan Keluar! (Bisa diketik manual atau pilih dari daftar dropdown)");
                return; 
            }

            try {
                const res = await fetchAPI('/inventories/reduce', 'POST', { store_id: storeId, items: items });
                if (res.status === 'success') {
                    alert("Stok Keluar berhasil dicatat!");
                    closeModal('modal-stok-keluar');
                    
                    document.querySelectorAll('.keluar-row').forEach((r, idx) => { if(idx > 0) r.remove(); });
                    document.getElementById('qty-keluar-1').value = '';
                    document.getElementById('alasan-keluar-1').value = '';
                    document.getElementById('item-keluar-1').value = '';
                    
                    loadBukuBesar(1); 
                } else { alert("Gagal: " + (res.message || "Terjadi kesalahan di server.")); }
            } catch(e) { alert("Gagal menghubungi server API."); }
        }

        // ==========================================
        // FITUR STOK OPNAME
        // ==========================================
        // ==========================================
        // FITUR STOK OPNAME (TABEL MASAL & UPDATE)
        // ==========================================
        let cacheOpnameItems = [];

        function switchOpnameTab(tab) {
            ['sisa', 'lakukan', 'riwayat'].forEach(t => {
                document.getElementById(`tab-btn-${t}`).className = "py-2.5 px-4 border-b-2 border-transparent text-gray-500 font-semibold hover:text-[#5B8C5A] text-sm w-1/3 transition-colors";
                document.getElementById(`opname-tab-${t}`).classList.add('hidden');
            });
            document.getElementById(`tab-btn-${tab}`).className = "py-2.5 px-4 border-b-2 border-[#5B8C5A] text-[#5B8C5A] font-bold text-sm w-1/3 transition-colors";
            document.getElementById(`opname-tab-${tab}`).classList.remove('hidden');

            // Trigger API berdasarkan tab
            if(tab === 'sisa') loadSisaStok();
            else if(tab === 'lakukan') renderLakukanOpname();
            else if(tab === 'riwayat') loadRiwayatOpname(); // KUNCI: Panggil fungsi riwayat!
        }


        // 1. RENDER ULANG RIWAYAT DENGAN SISTEM ACCORDION (SESI)
        let cacheHistories = []; 

        async function loadRiwayatOpname() {
            const container = document.getElementById('opname-riwayat-container');
            if(!container) return;

            container.className = "bg-gray-50 rounded-xl w-full min-h-[250px] flex flex-col items-center justify-center border border-dashed border-gray-300 p-6";
            container.innerHTML = '<div class="text-center w-full py-10"><i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i><p class="text-gray-500 font-semibold">Memuat riwayat sesi...</p></div>';

            try {
                const res = await fetchAPI('/inventories/history', 'POST', { store_id: storeId });
                if (res.status === 'success' && res.data.length > 0) {
                    cacheHistories = res.data; 
                    
                    const grouped = {};
                    cacheHistories.forEach(log => {
                        const bId = log.batch_id;
                        if (!grouped[bId]) {
                            // KUNCI: Tambahkan 'Z' agar JS tahu ini UTC dan diconvert ke WIB otomatis
                            let validDate = log.created_at.endsWith('Z') ? log.created_at : log.created_at + 'Z';
                            grouped[bId] = { type: log.type, date: validDate, notes: log.notes, items: [] };
                        }
                        grouped[bId].items.push(log);
                    });

                    let html = `<div class="space-y-4 w-full px-1">`;
                    for (const [bId, data] of Object.entries(grouped)) {
                        const dateStr = new Date(data.date).toLocaleString('id-ID', {day: '2-digit', month: 'short', year:'numeric', hour: '2-digit', minute:'2-digit'});
                        
                        let badge = ''; let bgHeader = '';
                        if (data.type === 'masuk') { badge = '<span class="bg-green-100 text-green-700 px-3 py-1 rounded-lg text-xs font-bold">STOK MASUK</span>'; bgHeader = 'border-green-200'; } 
                        else if (data.type === 'keluar') { badge = '<span class="bg-red-100 text-red-700 px-3 py-1 rounded-lg text-xs font-bold">STOK KELUAR</span>'; bgHeader = 'border-red-200'; } 
                        else { badge = '<span class="bg-blue-100 text-blue-700 px-3 py-1 rounded-lg text-xs font-bold">STOK OPNAME</span>'; bgHeader = 'border-blue-200'; }

                        let rowItems = '';
                        data.items.forEach(itm => {
                            let stokFisik = parseFloat(itm.final_stock) || 0;
                            let selisih = parseFloat(itm.qty_change) || 0;
                            let stokSistem = stokFisik - selisih; // Kalkulasi mundur untuk dapat stok sistem
                            let price = parseFloat(itm.item_price) || 0;
                            let nilaiUang = selisih * price;

                            let changeColor = selisih > 0 ? 'text-green-600' : (selisih < 0 ? 'text-red-600' : 'text-gray-500');
                            let prefix = selisih > 0 ? '+' : '';
                            let stringUang = selisih > 0 ? `+Rp ${formatIDR(Math.abs(nilaiUang))}` : (selisih < 0 ? `-Rp ${formatIDR(Math.abs(nilaiUang))}` : 'Rp 0');

                            rowItems += `
                                <tr class="border-b border-gray-100 hover:bg-gray-50">
                                    <td class="p-3 font-bold text-gray-800">${itm.item_name} <span class="font-normal text-xs text-gray-400">(${itm.uom})</span></td>
                                    <td class="p-3 text-center text-gray-500 font-bold">${stokSistem}</td>
                                    <td class="p-3 text-center font-bold text-[#5B8C5A]">${stokFisik}</td>
                                    <td class="p-3 text-center font-extrabold ${changeColor}">${prefix}${selisih}</td>
                                    <td class="p-3 text-right font-bold ${changeColor}">${stringUang}</td>
                                </tr>
                            `;
                        });

                        html += `
                            <div class="bg-white border ${bgHeader} shadow-sm rounded-2xl overflow-hidden transition-all">
                                <div class="bg-gray-50 p-4 flex flex-col md:flex-row justify-between items-start md:items-center gap-4 cursor-pointer hover:bg-gray-100" onclick="toggleBatch('${bId}')">
                                    <div>
                                        <div class="flex items-center gap-3 mb-1">
                                            <h4 class="font-extrabold text-gray-800 text-lg">${bId}</h4> ${badge}
                                        </div>
                                        <p class="text-xs text-gray-500 font-semibold"><i class="fa-regular fa-calendar mr-1"></i> ${dateStr} &nbsp;|&nbsp; <i class="fa-regular fa-comment-dots mx-1"></i> ${data.notes || 'Tidak ada catatan'}</p>
                                    </div>
                                    <div class="flex items-center gap-2">
                                        <button onclick="event.stopPropagation(); printPdfBatch('${bId}')" class="bg-white border border-gray-200 text-gray-600 hover:text-[#5B8C5A] hover:border-[#5B8C5A] px-3 py-1.5 rounded-lg text-xs font-bold shadow-sm transition-all"><i class="fa-solid fa-print mr-1"></i> PDF</button>
                                        <button onclick="event.stopPropagation(); exportExcelBatch('${bId}')" class="bg-white border border-gray-200 text-gray-600 hover:text-[#5B8C5A] hover:border-[#5B8C5A] px-3 py-1.5 rounded-lg text-xs font-bold shadow-sm transition-all"><i class="fa-solid fa-file-excel mr-1"></i> Excel</button>
                                        <button onclick="event.stopPropagation(); deleteBatch('${bId}')" class="bg-red-50 text-red-500 hover:bg-red-500 hover:text-white border border-red-100 px-3 py-1.5 rounded-lg text-xs font-bold shadow-sm transition-all"><i class="fa-solid fa-trash"></i></button>
                                        <i class="fa-solid fa-chevron-down text-gray-400 ml-2"></i>
                                    </div>
                                </div>
                                <div id="batch-detail-${bId}" class="hidden p-4 border-t border-gray-100">
                                    <table class="w-full text-left text-sm whitespace-nowrap">
                                        <thead class="bg-gray-100 border-b">
                                            <tr><th class="p-3 font-bold text-gray-600">Barang (UOM)</th><th class="p-3 font-bold text-center text-gray-600">Stok Sistem</th><th class="p-3 font-bold text-center text-[#5B8C5A]">Fisik Gudang</th><th class="p-3 font-bold text-center text-gray-600">Selisih</th><th class="p-3 font-bold text-right text-gray-600">Nilai Uang (Rp)</th></tr>
                                        </thead>
                                        <tbody>${rowItems}</tbody>
                                    </table>
                                </div>
                            </div>
                        `;
                    }
                    html += `</div>`;
                    container.className = "w-full"; 
                    container.innerHTML = html;
                } else {
                    container.className = "bg-gray-50 rounded-xl w-full min-h-[250px] flex flex-col items-center justify-center border border-dashed border-gray-300 p-6";
                    container.innerHTML = '<i class="fa-solid fa-clock-rotate-left text-4xl text-gray-300 mb-3"></i><p class="text-gray-500 font-semibold">Belum ada riwayat pergerakan stok.</p>';
                }
            } catch (e) { container.innerHTML = '<p class="text-red-500 text-center font-bold mt-10">Gagal memuat API Riwayat.</p>'; }
        }

        function toggleBatch(bId) {
            const el = document.getElementById(`batch-detail-${bId}`);
            if(el) el.classList.toggle('hidden');
        }

        async function deleteBatch(bId) {
            if(!confirm(`Yakin hapus sesi ${bId}?`)) return;
            try {
                const res = await fetchAPI(`/inventories/history/${bId}`, 'DELETE');
                if(res.status === 'success') { alert(res.message); loadRiwayatOpname(); } 
                else { alert("Gagal: " + res.message); }
            } catch(e) { alert("Terjadi kesalahan."); }
        }

        function exportExcelBatch(bId) {
            const batchData = cacheHistories.filter(x => x.batch_id === bId);
            if(!batchData.length) return;
            
            let csv = "Kode Sesi,Tanggal,Catatan,Barang,UOM,Stok Sistem,Stok Fisik,Selisih,Nilai Uang (Rp)\n";
            batchData.forEach(x => {
                let dt = new Date(x.created_at.endsWith('Z') ? x.created_at : x.created_at + 'Z').toLocaleString('id-ID');
                let stokFisik = parseFloat(x.final_stock) || 0;
                let selisih = parseFloat(x.qty_change) || 0;
                let stokSistem = stokFisik - selisih;
                let nilaiUang = selisih * (parseFloat(x.item_price) || 0);
                csv += `"${bId}","${dt}","${x.notes || '-'}","${x.item_name}","${x.uom}","${stokSistem}","${stokFisik}","${selisih}","${nilaiUang}"\n`;
            });
            
            const blob = new Blob([csv], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.setAttribute('hidden', ''); a.setAttribute('href', url); a.setAttribute('download', `Opname_${bId}.csv`);
            document.body.appendChild(a); a.click(); document.body.removeChild(a);
        }

        function printPdfBatch(bId) {
            const batchData = cacheHistories.filter(x => x.batch_id === bId);
            if(!batchData.length) return;
            const bInfo = batchData[0];
            let dtInfo = new Date(bInfo.created_at.endsWith('Z') ? bInfo.created_at : bInfo.created_at + 'Z').toLocaleString('id-ID');
            
            let rows = '';
            batchData.forEach(x => {
                let stokFisik = parseFloat(x.final_stock) || 0;
                let selisih = parseFloat(x.qty_change) || 0;
                let stokSistem = stokFisik - selisih;
                let prefix = selisih > 0 ? '+' : '';
                let nilaiUang = selisih * (parseFloat(x.item_price) || 0);
                let stringUang = selisih > 0 ? `+Rp ${formatIDR(Math.abs(nilaiUang))}` : (selisih < 0 ? `-Rp ${formatIDR(Math.abs(nilaiUang))}` : 'Rp 0');

                rows += `<tr>
                    <td style="padding: 10px; border-bottom: 1px solid #eee;">${x.item_name} (${x.uom})</td>
                    <td style="padding: 10px; border-bottom: 1px solid #eee; text-align:center;">${stokSistem}</td>
                    <td style="padding: 10px; border-bottom: 1px solid #eee; text-align:center; font-weight:bold; color:#5B8C5A;">${stokFisik}</td>
                    <td style="padding: 10px; border-bottom: 1px solid #eee; text-align:center; font-weight:bold;">${prefix}${selisih}</td>
                    <td style="padding: 10px; border-bottom: 1px solid #eee; text-align:right; font-weight:bold;">${stringUang}</td>
                </tr>`;
            });

            let html = `
            <html><head><title>Laporan - ${bId}</title>
            <style>
                body { font-family: 'Arial', sans-serif; position: relative; color: #333; margin: 40px; }
                .watermark { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); opacity: 0.05; width: 400px; z-index: -1; pointer-events: none; }
                /* KUNCI: Flexbox untuk membagi area kiri (teks) dan kanan (logo) */
                .header { border-bottom: 3px solid #5B8C5A; padding-bottom: 20px; margin-bottom: 30px; display: flex; justify-content: space-between; align-items: flex-start; }
                .title { color: #5B8C5A; margin: 0 0 10px 0; font-size: 28px; text-transform: uppercase; }
                table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 14px; }
                th { background-color: #f8f9fa; padding: 12px 10px; text-align: left; border-bottom: 2px solid #ddd; color: #555; }
            </style>
            </head><body>
                <img src="/images/icon_teratory.png" class="watermark">
                
                <div class="header">
                    <div>
                        <h2 class="title">LAPORAN ${bInfo.type}</h2>
                        <p style="margin: 5px 0;"><strong>Kode Sesi:</strong> ${bId}</p>
                        <p style="margin: 5px 0;"><strong>Waktu Transaksi:</strong> ${dtInfo}</p>
                        <p style="margin: 5px 0;"><strong>Catatan Aktivitas:</strong> ${bInfo.notes || '-'}</p>
                    </div>
                    <!-- KUNCI: Logo Teratory di pojok kanan -->
                    <div>
                        <img src="/images/logo_teratory.png" alt="Teratory" style="max-height: 80px; object-fit: contain;">
                    </div>
                </div>

                <table>
                    <thead><tr><th>Barang (UOM)</th><th style="text-align:center;">Sistem</th><th style="text-align:center;">Fisik</th><th style="text-align:center;">Selisih</th><th style="text-align:right;">Nilai Uang</th></tr></thead>
                    <tbody>${rows}</tbody>
                </table>
                <div style="margin-top: 50px; text-align:right; font-size: 12px; color: #888;">Digenerate otomatis oleh Teratory System</div>
                
                <!-- KUNCI: Beri delay 500ms agar browser merender logo secara utuh sebelum nge-print -->
                <script>
                    setTimeout(() => { 
                        window.print(); 
                        setTimeout(() => window.close(), 1000); 
                    }, 500);
                <\/script>
            </body></html>
            `;
            let win = window.open('', '_blank');
            win.document.write(html); win.document.close();
        }

        async function loadSisaStok() {
            const container = document.getElementById('opname-sisa-container');
            if(!container) return;

            container.className = "bg-gray-50 rounded-xl w-full min-h-[250px] flex flex-col items-center justify-center border border-dashed border-gray-300 p-6";
            
            // KUNCI MUTLAK: Menggunakan backtick (`) BUKAN kutip satu (')
            container.innerHTML = `<div class="text-center w-full py-10"><i class="fa-solid fa-spinner fa-spin text-3xl text-[#5B8C5A] mb-3"></i><p class="text-gray-500 font-semibold">Mensinkronkan stok...</p></div>`;
            
            try {
                const res = await fetchAPI('/inventory', 'POST', { store_id: storeId });
                if (res.status === 'success' && res.data.length > 0) {
                    cacheOpnameItems = res.data; 

                    let html = `<div class="bg-white rounded-xl border border-gray-200 overflow-hidden custom-scrollbar max-h-[50vh] overflow-y-auto w-full"><table class="w-full text-left text-sm whitespace-nowrap"><thead class="bg-gray-100 border-b sticky top-0"><tr><th class="p-4 font-bold">Nama Barang</th><th class="p-4 font-bold text-center">Stok Sistem</th><th class="p-4 font-bold text-center">UOM</th></tr></thead><tbody class="divide-y divide-gray-100">`;
                    res.data.forEach(item => {
                        const stock = item.current_stock || 0;
                        const stokColor = stock <= 5 ? 'text-red-500' : 'text-[#5B8C5A]';
                        html += `<tr class="hover:bg-gray-50"><td class="p-4 font-bold text-gray-800">${item.name}</td><td class="p-4 text-center font-bold ${stokColor}">${stock}</td><td class="p-4 text-center text-gray-600">${item.uom}</td></tr>`;
                    });
                    html += `</tbody></table></div>`;
                    
                    container.className = "w-full"; 
                    container.innerHTML = html;
                } else {
                    container.className = "bg-gray-50 rounded-xl w-full min-h-[250px] flex flex-col items-center justify-center border border-dashed border-gray-300 p-6";
                    container.innerHTML = `<i class="fa-solid fa-box-open text-4xl text-gray-300 mb-3"></i><p class="text-gray-500 font-semibold">Data stok barang kosong.</p>`;
                }
            } catch (e) { 
                container.innerHTML = `<p class="text-red-500 text-center font-bold mt-10">Gagal memuat API Sisa Stok.</p>`; 
            }
        }

        async function renderLakukanOpname() {
            const tbody = document.getElementById('opname-lakukan-tbody');
            if(cacheOpnameItems.length === 0) {
                tbody.innerHTML = '<tr><td colspan="5" class="text-center p-6 text-gray-500 font-semibold">Data kosong. Tarik Sisa Stok terlebih dahulu.</td></tr>';
                return;
            }

            let html = '';
            cacheOpnameItems.forEach(item => {
                const sysStock = item.current_stock || 0;
                // KUNCI: Opname tinggal memanggil item.price karena sudah disiapkan dari awal!
                const truePrice = parseFloat(item.price) || 0; 

                html += `
                    <tr class="hover:bg-gray-50 opname-row" data-id="${item.id}" data-sys="${sysStock}" data-price="${truePrice}">
                        <td class="p-3 text-gray-800 font-bold">${item.name} <span class="text-xs text-gray-400 font-normal">(${item.uom})</span></td>
                        <td class="p-3 text-center text-gray-400 font-bold">${sysStock}</td>
                        <td class="p-3 text-center">
                            <input type="number" id="opname-fisik-${item.id}" oninput="hitungSelisihOpname(${item.id})" class="w-24 border-2 border-[#5B8C5A]/50 rounded-lg p-1.5 text-center font-bold focus:border-[#5B8C5A] focus:outline-none" placeholder="Isi fisik">
                        </td>
                        <td class="p-3 text-center font-bold text-gray-300" id="opname-selisih-${item.id}">-</td>
                        <td class="p-3 text-right font-bold text-gray-300" id="opname-nilai-${item.id}">-</td>
                    </tr>
                `;
            });
            tbody.innerHTML = html;
        }

        function hitungSelisihOpname(itemId) {
            const row = document.querySelector(`.opname-row[data-id="${itemId}"]`);
            if(!row) return;

            const sysStock = parseFloat(row.getAttribute('data-sys')) || 0;
            const price = parseFloat(row.getAttribute('data-price')) || 0;
            const fisikInput = document.getElementById(`opname-fisik-${itemId}`).value;

            const tdSelisih = document.getElementById(`opname-selisih-${itemId}`);
            const tdNilai = document.getElementById(`opname-nilai-${itemId}`);

            if(fisikInput === '') {
                tdSelisih.innerText = '-'; tdNilai.innerText = '-';
                tdSelisih.className = "p-3 text-center font-bold text-gray-300";
                tdNilai.className = "p-3 text-right font-bold text-gray-300";
                return;
            }

            const fisik = parseFloat(fisikInput);
            const diff = fisik - sysStock;
            const nominal = diff * price;

            // Visual Hijau (Surplus), Merah (Defisit), atau Abu-abu (Sama)
            let colorClass = diff > 0 ? 'text-green-500' : (diff < 0 ? 'text-red-500' : 'text-gray-500');
            let prefix = diff > 0 ? '+' : '';

            tdSelisih.innerText = prefix + diff;
            tdSelisih.className = `p-3 text-center font-extrabold ${colorClass}`;

            tdNilai.innerText = prefix + 'Rp ' + formatIDR(nominal);
            tdNilai.className = `p-3 text-right font-extrabold ${colorClass}`;
        }

        async function submitOpname() {
            const rows = document.querySelectorAll('.opname-row');
            let itemsToUpdate = [];

            // Hanya ambil baris yang input fisiknya diisi oleh user
            rows.forEach(row => {
                const id = row.getAttribute('data-id');
                const fisikVal = document.getElementById(`opname-fisik-${id}`).value;
                if(fisikVal !== '') {
                    itemsToUpdate.push({
                        item_id: id,
                        physical_qty: parseFloat(fisikVal)
                    });
                }
            });

            if(itemsToUpdate.length === 0) {
                alert("Anda belum menginput fisik barang apapun!");
                return;
            }

            const notes = document.getElementById('opname-global-notes').value;

            try {
                const res = await fetchAPI('/inventory/opname', 'POST', { store_id: storeId, items: itemsToUpdate, notes: notes });
                if(res.status === 'success') {
                    alert(res.message);
                    document.getElementById('opname-global-notes').value = '';
                    switchOpnameTab('sisa'); // Otomatis refresh sisa stok dengan data terbaru!
                } else alert("Gagal: " + res.message);
            } catch(e) { alert("Gagal menghubungi server API."); }
        }

    </script>
</body>
</html><?php /**PATH C:\xampp\htdocs\teratory\resources\views/aktivitas.blade.php ENDPATH**/ ?>