<?php require_once 'auth_check.php'; ?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Master Data - Penjualan Sabun Cair</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- jQuery CDN -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $('.datamenu').load("header_so.php");
    });
    </script>
</head>
<body class="bg-gray-50 text-gray-800">

    <div class="container mx-auto px-4 py-8 max-w-6xl">
        <!-- Navigasi Menu Atas -->
        <div class='datamenu mb-6'></div>

        <!-- TAB PRODUK -->
        <div id="section-products" class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-lg font-semibold text-gray-800"><i class="fa-solid fa-bottle-droplet mr-2 text-blue-600"></i> Daftar Produk Sabun Cair</h2>
                <button onclick="openProductModal()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition"><i class="fa-solid fa-plus mr-1"></i> Tambah Produk</button>
            </div>

            <!-- Filter Bar Produk: Tahun & Limit -->
            <div class="flex flex-col sm:flex-row justify-between items-center gap-4 mb-4 pb-4 border-b border-gray-100">
                <div class="flex items-center space-x-3 w-full sm:w-auto">
                    <label class="text-xs font-semibold text-gray-600 uppercase flex items-center space-x-1">
                        <i class="fa-regular fa-calendar text-blue-600 mr-1"></i> Tahun:
                    </label>
                    <input type="number" id="filter_year_prod" value="<?php echo date('Y'); ?>" placeholder="YYYY" onkeyup="handleProductSearch()" onchange="handleProductSearch()" class="w-28 border rounded-xl px-3 py-1.5 text-sm bg-gray-50 focus:ring-2 focus:ring-blue-500 font-semibold outline-none text-center">
                    <button onclick="loadProducts(1)" class="px-3 py-1.5 bg-blue-50 text-blue-600 border border-blue-200 rounded-xl text-xs font-medium hover:bg-blue-100 transition">
                        Filter
                    </button>
                </div>
                <div class="flex items-center space-x-2 w-full sm:w-auto justify-end">
                    <label class="text-xs font-semibold text-gray-600 uppercase">Tampilkan:</label>
                    <select id="filter_limit_prod" onchange="changeProductLimit(this.value)" class="border rounded-xl px-3 py-1.5 text-sm bg-gray-50 focus:ring-2 focus:ring-blue-500 outline-none">
                        <option value="10">10 data</option>
                        <option value="25">25 data</option>
                        <option value="50">50 data</option>
                        <option value="100">100 data</option>
                    </select>
                </div>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
					<thead>
						<tr class="border-b bg-gray-50 text-xs uppercase text-gray-500 font-semibold">
							<th class="p-3">Kode</th>
							<th class="p-3">Nama Produk</th>
							<th class="p-3">Satuan</th>
							<th class="p-3">Harga Jual</th>
							<th class="p-3 text-center">Aksi</th>
						</tr>
                        <!-- Baris Pencarian per-kolom Produk -->
                        <tr class="bg-gray-50 border-b">
                            <th class="p-2"><input type="text" id="col_prod_code" onkeyup="handleProductSearch()" placeholder="Cari Kode..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2"><input type="text" id="col_prod_name" onkeyup="handleProductSearch()" placeholder="Cari Nama..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2"><input type="text" id="col_prod_unit" onkeyup="handleProductSearch()" placeholder="Cari Satuan..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2"><input type="text" id="col_prod_price" onkeyup="handleProductSearch()" placeholder="Cari Harga..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2 text-center">
                                <button onclick="resetProductFilters()" title="Reset Filter" class="text-xs text-gray-400 hover:text-red-500"><i class="fa-solid fa-filter-circle-xmark"></i></button>
                            </th>
                        </tr>
					</thead>
					<tbody id="product-table-body" class="text-sm divide-y divide-gray-100">
						<!-- Loaded via JS -->
					</tbody>
				</table>
            </div>

            <!-- Footer Paging Produk -->
            <div class="flex flex-col sm:flex-row justify-between items-center gap-4 mt-4 pt-4 border-t border-gray-100 text-xs text-gray-500">
                <div id="pagination-info-prod">Menampilkan 0 data</div>
                <div id="pagination-buttons-prod" class="flex items-center space-x-1"></div>
            </div>
        </div>

        <!-- TAB CUSTOMERS -->
        <div id="section-customers" class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mt-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-lg font-semibold text-gray-800"><i class="fa-solid fa-users mr-2 text-blue-600"></i> Daftar Pelanggan / Toko</h2>
                <button onclick="openCustomerModal()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition"><i class="fa-solid fa-plus mr-1"></i> Tambah Pelanggan</button>
            </div>

            <!-- Filter Bar Pelanggan: Tahun & Limit -->
            <div class="flex flex-col sm:flex-row justify-between items-center gap-4 mb-4 pb-4 border-b border-gray-100">
                <div class="flex items-center space-x-3 w-full sm:w-auto">
                    <label class="text-xs font-semibold text-gray-600 uppercase flex items-center space-x-1">
                        <i class="fa-regular fa-calendar text-blue-600 mr-1"></i> Tahun:
                    </label>
                    <input type="number" id="filter_year_cust" value="<?php echo date('Y'); ?>" placeholder="YYYY" onkeyup="handleCustomerSearch()" onchange="handleCustomerSearch()" class="w-28 border rounded-xl px-3 py-1.5 text-sm bg-gray-50 focus:ring-2 focus:ring-blue-500 font-semibold outline-none text-center">
                    <button onclick="loadCustomers(1)" class="px-3 py-1.5 bg-blue-50 text-blue-600 border border-blue-200 rounded-xl text-xs font-medium hover:bg-blue-100 transition">
                        Filter
                    </button>
                </div>
                <div class="flex items-center space-x-2 w-full sm:w-auto justify-end">
                    <label class="text-xs font-semibold text-gray-600 uppercase">Tampilkan:</label>
                    <select id="filter_limit_cust" onchange="changeCustomerLimit(this.value)" class="border rounded-xl px-3 py-1.5 text-sm bg-gray-50 focus:ring-2 focus:ring-blue-500 outline-none">
                        <option value="10">10 data</option>
                        <option value="25">25 data</option>
                        <option value="50">50 data</option>
                        <option value="100">100 data</option>
                    </select>
                </div>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full text-left border-collapse">
                    <thead>
                        <tr class="border-b bg-gray-50 text-xs uppercase text-gray-500 font-semibold">
                            <th class="p-3">Kode</th>
                            <th class="p-3">Nama Pelanggan</th>
                            <th class="p-3">Kontak Person</th>
                            <th class="p-3">Telepon</th>
                            <th class="p-3">Limit Piutang</th>
                            <th class="p-3 text-center">Aksi</th>
                        </tr>
                        <!-- Baris Pencarian per-kolom Pelanggan -->
                        <tr class="bg-gray-50 border-b">
                            <th class="p-2"><input type="text" id="col_cust_code" onkeyup="handleCustomerSearch()" placeholder="Cari Kode..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2"><input type="text" id="col_cust_name" onkeyup="handleCustomerSearch()" placeholder="Cari Nama..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2"><input type="text" id="col_cust_contact" onkeyup="handleCustomerSearch()" placeholder="Cari Kontak..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2"><input type="text" id="col_cust_phone" onkeyup="handleCustomerSearch()" placeholder="Cari Telepon..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2"><input type="text" id="col_cust_limit" onkeyup="handleCustomerSearch()" placeholder="Cari Limit..." class="w-full text-xs font-normal border rounded-lg px-2 py-1 bg-white focus:ring-1 focus:ring-blue-500 outline-none"></th>
                            <th class="p-2 text-center">
                                <button onclick="resetCustomerFilters()" title="Reset Filter" class="text-xs text-gray-400 hover:text-red-500"><i class="fa-solid fa-filter-circle-xmark"></i></button>
                            </th>
                        </tr>
                    </thead>
                    <tbody id="customer-table-body" class="text-sm divide-y divide-gray-100">
                        <!-- Loaded via JS -->
                    </tbody>
                </table>
            </div>

            <!-- Footer Paging Pelanggan -->
            <div class="flex flex-col sm:flex-row justify-between items-center gap-4 mt-4 pt-4 border-t border-gray-100 text-xs text-gray-500">
                <div id="pagination-info-cust">Menampilkan 0 data</div>
                <div id="pagination-buttons-cust" class="flex items-center space-x-1"></div>
            </div>
        </div>
    </div>

    <!-- MODAL PRODUCT -->
    <div id="productModal" class="fixed inset-0 bg-black/50 hidden flex items-center justify-center p-4 z-50">
		<div class="bg-white rounded-xl max-w-md w-full p-6 shadow-xl">
			<h3 id="productModalTitle" class="text-lg font-bold mb-4">Tambah Produk Sabun</h3>
			<form id="productForm" onsubmit="saveProduct(event)">
				<input type="hidden" id="prod_id" name="id">
				<div class="space-y-4">
					<div>
						<label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Kode Produk</label>
						<input type="text" id="prod_code" name="product_code" required class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" placeholder="Cth: SBN-001">
					</div>
					<div>
						<label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Nama Produk Sabun</label>
						<input type="text" id="prod_name" name="product_name" required class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" placeholder="Cth: Sabun Cair Cuci Piring 1L">
					</div>
					<div class="grid grid-cols-2 gap-3">
						<div>
							<label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Satuan</label>
							<input type="text" id="prod_unit" name="unit" value="Botol" required class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
						</div>
						<div>
							<label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Harga Jual (Rp)</label>
							<input type="number" step="0.01" id="prod_price" name="selling_price" required class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none" placeholder="0">
						</div>
					</div>
				</div>
				<div class="mt-6 flex justify-end space-x-2">
					<button type="button" onclick="closeProductModal()" class="px-4 py-2 bg-gray-100 text-gray-600 rounded-lg text-sm font-medium hover:bg-gray-200">Batal</button>
					<button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700">Simpan</button>
				</div>
			</form>
		</div>
	</div>

    <!-- MODAL CUSTOMER -->
    <div id="customerModal" class="fixed inset-0 bg-black/50 hidden flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-xl max-w-md w-full p-6 shadow-xl">
            <h3 id="customerModalTitle" class="text-lg font-bold mb-4">Tambah Pelanggan Baru</h3>
            <form id="customerForm" onsubmit="saveCustomer(event)">
                <input type="hidden" id="cust_id" name="id">
                <div class="space-y-4">
                    <div>
                        <label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Kode Pelanggan</label>
                        <input type="text" id="cust_code" name="customer_code" required class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Nama Toko / Pelanggan</label>
                        <input type="text" id="cust_name" name="customer_name" required class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
                    </div>
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Kontak Person</label>
                            <input type="text" id="cust_contact" name="contact_person" class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
                        </div>
                        <div>
                            <label class="block text-xs font-semibold uppercase text-gray-600 mb-1">No. Telepon</label>
                            <input type="text" id="cust_phone" name="phone" class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
                        </div>
                    </div>
                    <div>
                        <label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Limit Piutang (Rp)</label>
                        <input type="number" step="0.01" id="cust_limit" name="credit_limit" value="0" class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold uppercase text-gray-600 mb-1">Alamat Lengkap</label>
                        <textarea id="cust_address" name="address" rows="2" class="w-full border rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-blue-500 outline-none"></textarea>
                    </div>
                </div>
                <div class="mt-6 flex justify-end space-x-2">
                    <button type="button" onclick="closeCustomerModal()" class="px-4 py-2 bg-gray-100 text-gray-600 rounded-lg text-sm font-medium hover:bg-gray-200">Batal</button>
                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700">Simpan</button>
                </div>
            </form>
        </div>
    </div>

    <!-- JavaScript Controller -->
    <script>
        let currentProdPage = 1;
        let currentProdLimit = 10;
        let prodSearchTimer = null;

        let currentCustPage = 1;
        let currentCustLimit = 10;
        let custSearchTimer = null;

        document.addEventListener("DOMContentLoaded", () => {
            loadProducts();
            loadCustomers();
        });

        // --- PRODUK CONTROLLER & PAGINATION ---
        async function loadProducts(page = currentProdPage) {
            currentProdPage = page;
            let year = document.getElementById('filter_year_prod').value || "";
            let sCode = document.getElementById('col_prod_code').value;
            let sName = document.getElementById('col_prod_name').value;
            let sUnit = document.getElementById('col_prod_unit').value;
            let sPrice = document.getElementById('col_prod_price').value;

            let queryParams = new URLSearchParams({
                action: 'get_products',
                year: year,
                page: currentProdPage,
                limit: currentProdLimit,
                search_code: sCode,
                search_name: sName,
                search_unit: sUnit,
                search_price: sPrice
            });

            let res = await fetch(`api_master.php?${queryParams.toString()}`);
            let json = await res.json();
            let tbody = document.getElementById('product-table-body');
            tbody.innerHTML = "";

            if (json.status !== 'success' || !json.data || json.data.length === 0) {
                tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-gray-400">Belum ada data produk.</td></tr>`;
                renderProductPagination(json.pagination);
                return;
            }

            json.data.forEach(p => {
                tbody.innerHTML += `
                    <tr class="hover:bg-gray-50 border-b border-gray-100">
                        <td class="p-3 font-mono text-xs">${p.product_code}</td>
                        <td class="p-3 font-medium">${p.product_name}</td>
                        <td class="p-3">${p.unit}</td>
                        <td class="p-3 text-blue-600 font-semibold">Rp ${Number(p.selling_price).toLocaleString('id-ID')}</td>
                        <td class="p-3 text-center space-x-2">
                            <button onclick='editProduct(${JSON.stringify(p)})' class="text-amber-600 hover:text-amber-800"><i class="fa-solid fa-pen-to-square"></i></button>
                            <button onclick='deleteProduct(${p.id})' class="text-red-600 hover:text-red-800"><i class="fa-solid fa-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
            renderProductPagination(json.pagination);
        }

        function renderProductPagination(p) {
            let info = document.getElementById('pagination-info-prod');
            let buttons = document.getElementById('pagination-buttons-prod');
            buttons.innerHTML = "";

            if (!p || p.total_records === 0) {
                info.innerText = `Menampilkan 0 data`;
                return;
            }

            let start = ((p.current_page - 1) * p.limit) + 1;
            let end = Math.min(p.current_page * p.limit, p.total_records);
            info.innerText = `Menampilkan ${start} - ${end} dari ${p.total_records} Produk`;

            let prevDisabled = p.current_page === 1 ? 'disabled class="px-2.5 py-1 border rounded-lg bg-gray-100 text-gray-400 cursor-not-allowed"' : `onclick="loadProducts(${p.current_page - 1})" class="px-2.5 py-1 border rounded-lg hover:bg-gray-100 text-gray-700 font-medium"`;
            buttons.innerHTML += `<button ${prevDisabled}><i class="fa-solid fa-chevron-left"></i></button>`;

            for (let i = 1; i <= p.total_pages; i++) {
                if (i === p.current_page) {
                    buttons.innerHTML += `<button class="px-3 py-1 border rounded-lg bg-blue-600 text-white font-semibold">${i}</button>`;
                } else {
                    buttons.innerHTML += `<button onclick="loadProducts(${i})" class="px-3 py-1 border rounded-lg hover:bg-gray-100 text-gray-700 font-medium">${i}</button>`;
                }
            }

            let nextDisabled = p.current_page >= p.total_pages ? 'disabled class="px-2.5 py-1 border rounded-lg bg-gray-100 text-gray-400 cursor-not-allowed"' : `onclick="loadProducts(${p.current_page + 1})" class="px-2.5 py-1 border rounded-lg hover:bg-gray-100 text-gray-700 font-medium"`;
            buttons.innerHTML += `<button ${nextDisabled}><i class="fa-solid fa-chevron-right"></i></button>`;
        }

        function changeProductLimit(lim) {
            currentProdLimit = lim;
            loadProducts(1);
        }

        function handleProductSearch() {
            clearTimeout(prodSearchTimer);
            prodSearchTimer = setTimeout(() => {
                loadProducts(1);
            }, 300);
        }

        function resetProductFilters() {
            document.getElementById('col_prod_code').value = "";
            document.getElementById('col_prod_name').value = "";
            document.getElementById('col_prod_unit').value = "";
            document.getElementById('col_prod_price').value = "";
            loadProducts(1);
        }

        // --- CUSTOMER CONTROLLER & PAGINATION ---
        async function loadCustomers(page = currentCustPage) {
            currentCustPage = page;
            let year = document.getElementById('filter_year_cust').value || "";
            let sCode = document.getElementById('col_cust_code').value;
            let sName = document.getElementById('col_cust_name').value;
            let sContact = document.getElementById('col_cust_contact').value;
            let sPhone = document.getElementById('col_cust_phone').value;
            let sLimit = document.getElementById('col_cust_limit').value;

            let queryParams = new URLSearchParams({
                action: 'get_customers',
                year: year,
                page: currentCustPage,
                limit: currentCustLimit,
                search_code: sCode,
                search_name: sName,
                search_contact: sContact,
                search_phone: sPhone,
                search_limit: sLimit
            });

            let res = await fetch(`api_master.php?${queryParams.toString()}`);
            let json = await res.json();
            let tbody = document.getElementById('customer-table-body');
            tbody.innerHTML = "";

            if (json.status !== 'success' || !json.data || json.data.length === 0) {
                tbody.innerHTML = `<tr><td colspan="6" class="p-4 text-center text-gray-400">Belum ada data pelanggan.</td></tr>`;
                renderCustomerPagination(json.pagination);
                return;
            }

            json.data.forEach(c => {
                tbody.innerHTML += `
                    <tr class="hover:bg-gray-50 border-b border-gray-100">
                        <td class="p-3 font-mono text-xs">${c.customer_code}</td>
                        <td class="p-3 font-medium">${c.customer_name}</td>
                        <td class="p-3">${c.contact_person ?? '-'}</td>
                        <td class="p-3">${c.phone ?? '-'}</td>
                        <td class="p-3 text-emerald-600 font-semibold">Rp ${Number(c.credit_limit).toLocaleString('id-ID')}</td>
                        <td class="p-3 text-center space-x-2">
                            <button onclick='editCustomer(${JSON.stringify(c)})' class="text-amber-600 hover:text-amber-800"><i class="fa-solid fa-pen-to-square"></i></button>
                            <button onclick='deleteCustomer(${c.id})' class="text-red-600 hover:text-red-800"><i class="fa-solid fa-trash"></i></button>
                        </td>
                    </tr>
                `;
            });
            renderCustomerPagination(json.pagination);
        }

        function renderCustomerPagination(p) {
            let info = document.getElementById('pagination-info-cust');
            let buttons = document.getElementById('pagination-buttons-cust');
            buttons.innerHTML = "";

            if (!p || p.total_records === 0) {
                info.innerText = `Menampilkan 0 data`;
                return;
            }

            let start = ((p.current_page - 1) * p.limit) + 1;
            let end = Math.min(p.current_page * p.limit, p.total_records);
            info.innerText = `Menampilkan ${start} - ${end} dari ${p.total_records} Pelanggan`;

            let prevDisabled = p.current_page === 1 ? 'disabled class="px-2.5 py-1 border rounded-lg bg-gray-100 text-gray-400 cursor-not-allowed"' : `onclick="loadCustomers(${p.current_page - 1})" class="px-2.5 py-1 border rounded-lg hover:bg-gray-100 text-gray-700 font-medium"`;
            buttons.innerHTML += `<button ${prevDisabled}><i class="fa-solid fa-chevron-left"></i></button>`;

            for (let i = 1; i <= p.total_pages; i++) {
                if (i === p.current_page) {
                    buttons.innerHTML += `<button class="px-3 py-1 border rounded-lg bg-blue-600 text-white font-semibold">${i}</button>`;
                } else {
                    buttons.innerHTML += `<button onclick="loadCustomers(${i})" class="px-3 py-1 border rounded-lg hover:bg-gray-100 text-gray-700 font-medium">${i}</button>`;
                }
            }

            let nextDisabled = p.current_page >= p.total_pages ? 'disabled class="px-2.5 py-1 border rounded-lg bg-gray-100 text-gray-400 cursor-not-allowed"' : `onclick="loadCustomers(${p.current_page + 1})" class="px-2.5 py-1 border rounded-lg hover:bg-gray-100 text-gray-700 font-medium"`;
            buttons.innerHTML += `<button ${nextDisabled}><i class="fa-solid fa-chevron-right"></i></button>`;
        }

        function changeCustomerLimit(lim) {
            currentCustLimit = lim;
            loadCustomers(1);
        }

        function handleCustomerSearch() {
            clearTimeout(custSearchTimer);
            custSearchTimer = setTimeout(() => {
                loadCustomers(1);
            }, 300);
        }

        function resetCustomerFilters() {
            document.getElementById('col_cust_code').value = "";
            document.getElementById('col_cust_name').value = "";
            document.getElementById('col_cust_contact').value = "";
            document.getElementById('col_cust_phone').value = "";
            document.getElementById('col_cust_limit').value = "";
            loadCustomers(1);
        }

        // --- MODAL FUNCTIONS (PRODUCT & CUSTOMER) ---
        function openProductModal(prod = null) {
			document.getElementById('productModal').classList.remove('hidden');
			if (prod) {
				document.getElementById('productModalTitle').innerText = "Edit Produk";
				document.getElementById('prod_id').value = prod.id;
				document.getElementById('prod_code').value = prod.product_code;
				document.getElementById('prod_name').value = prod.product_name;
				document.getElementById('prod_unit').value = prod.unit;
				document.getElementById('prod_price').value = prod.selling_price;
			} else {
				document.getElementById('productModalTitle').innerText = "Tambah Produk Baru";
				document.getElementById('productForm').reset();
				document.getElementById('prod_id').value = "";
			}
		}
		
        function closeProductModal() {
            document.getElementById('productModal').classList.add('hidden');
        }

        async function saveProduct(e) {
            e.preventDefault();
            let formData = new FormData(document.getElementById('productForm'));
            let res = await fetch('api_master.php?action=save_product', { method: 'POST', body: formData });
            let json = await res.json();
            if (json.status === 'success') {
                closeProductModal();
                loadProducts(currentProdPage);
            } else {
                alert(json.message);
            }
        }

        async function deleteProduct(id) {
            if(confirm("Yakin ingin menghapus produk ini?")) {
                let formData = new FormData();
                formData.append('id', id);
                let res = await fetch('api_master.php?action=delete_product', { method: 'POST', body: formData });
                let json = await res.json();
                if(json.status === 'success') loadProducts(currentProdPage);
                else alert(json.message);
            }
        }

        function editProduct(p) { openProductModal(p); }

        function openCustomerModal(cust = null) {
            document.getElementById('customerModal').classList.remove('hidden');
            if (cust) {
                document.getElementById('customerModalTitle').innerText = "Edit Pelanggan";
                document.getElementById('cust_id').value = cust.id;
                document.getElementById('cust_code').value = cust.customer_code;
                document.getElementById('cust_name').value = cust.customer_name;
                document.getElementById('cust_contact').value = cust.contact_person;
                document.getElementById('cust_phone').value = cust.phone;
                document.getElementById('cust_limit').value = cust.credit_limit;
                document.getElementById('cust_address').value = cust.address;
            } else {
                document.getElementById('customerModalTitle').innerText = "Tambah Pelanggan Baru";
                document.getElementById('customerForm').reset();
                document.getElementById('cust_id').value = "";
            }
        }

        function closeCustomerModal() {
            document.getElementById('customerModal').classList.add('hidden');
        }

        async function saveCustomer(e) {
            e.preventDefault();
            let formData = new FormData(document.getElementById('customerForm'));
            let res = await fetch('api_master.php?action=save_customer', { method: 'POST', body: formData });
            let json = await res.json();
            if (json.status === 'success') {
                closeCustomerModal();
                loadCustomers(currentCustPage);
            } else {
                alert(json.message);
            }
        }

        async function deleteCustomer(id) {
            if(confirm("Yakin ingin menghapus pelanggan ini?")) {
                let formData = new FormData();
                formData.append('id', id);
                let res = await fetch('api_master.php?action=delete_customer', { method: 'POST', body: formData });
                let json = await res.json();
                if(json.status === 'success') loadCustomers(currentCustPage);
                else alert(json.message);
            }
        }

        function editCustomer(c) { openCustomerModal(c); }
    </script>
</body>
</html>