// Global variables
let allData = [];
let filteredData = [];

// Format Rupiah
function formatRupiah(angka) {
    return new Intl.NumberFormat('id-ID', {
        style: 'currency',
        currency: 'IDR',
        minimumFractionDigits: 0
    }).format(angka);
}

// Load Data
function loadData() {
    fetch('../api/get_inventory.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                allData = data.data;
                filteredData = allData;
                
                // Populate filters
                populateFilters();
                
                // Render table
                renderTable();
                
                // Update stats
                updateStats();
            } else {
                showError(data.message || 'Gagal memuat data');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('Terjadi kesalahan saat memuat data');
        });
}

// Populate Filters
function populateFilters() {
    const filterKantor = document.getElementById('filterKantor');
    const kantorSet = new Set(allData.map(item => item.kantor));
    
    // Clear existing options except first
    filterKantor.innerHTML = '<option value="">Semua Kantor</option>';
    
    // Add unique kantor options
    kantorSet.forEach(kantor => {
        const option = document.createElement('option');
        option.value = kantor;
        option.textContent = kantor;
        filterKantor.appendChild(option);
    });
}

// Render Table
function renderTable() {
    const tbody = document.getElementById('tableBody');
    
    if (filteredData.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="8" class="no-data">
                    <i class="fas fa-inbox"></i>
                    <div>Tidak ada data ditemukan</div>
                </td>
            </tr>
        `;
        return;
    }
    
    const userType = '<?php echo $_SESSION["user_type"] ?? ""; ?>';
    const isAdmin = userType === 'A';
    
    tbody.innerHTML = filteredData.map(item => `
        <tr>
            <td>${item.no}</td>
            <td>${item.tanggal_perolehan}</td>
            <td>
                <span class="badge badge-${item.kategori.toLowerCase()}">${item.kategori}</span>
            </td>
            <td>${item.sumber_dana}</td>
            <td>${item.kantor}</td>
            <td><strong>${item.jenis_barang}</strong></td>
            <td class="price-cell">${formatRupiah(item.harga_perolehan)}</td>
            ${isAdmin ? `
            <td>
                <div class="actions">
                    <button class="btn-icon btn-edit" onclick="editItem(${item.id})" title="Edit">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn-icon btn-delete" onclick="deleteItem(${item.id})" title="Hapus">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </td>
            ` : ''}
        </tr>
    `).join('');
}

// Update Stats
function updateStats() {
    const itemCount = document.getElementById('itemCount');
    const totalItems = document.getElementById('totalItems');
    const totalPrice = document.getElementById('totalPrice');
    
    itemCount.textContent = filteredData.length;
    totalItems.textContent = allData.length;
    
    const total = filteredData.reduce((sum, item) => sum + parseFloat(item.harga_perolehan), 0);
    totalPrice.textContent = formatRupiah(total);
}

// Filter Data
function filterData() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const kantorFilter = document.getElementById('filterKantor').value;
    const kategoriFilter = document.getElementById('filterKategori').value;
    
    filteredData = allData.filter(item => {
        const matchSearch = 
            item.jenis_barang.toLowerCase().includes(searchTerm) ||
            item.kantor.toLowerCase().includes(searchTerm) ||
            item.jenis_inventory.toLowerCase().includes(searchTerm) ||
            item.sumber_dana.toLowerCase().includes(searchTerm);
        
        const matchKantor = !kantorFilter || item.kantor === kantorFilter;
        const matchKategori = !kategoriFilter || item.kategori === kategoriFilter;
        
        return matchSearch && matchKantor && matchKategori;
    });
    
    renderTable();
    updateStats();
}

// Edit Item
function editItem(id) {
    window.location.href = `inventory_form.php?action=edit&id=${id}`;
}

// Delete Item
function deleteItem(id) {
    if (!confirm('Apakah Anda yakin ingin menghapus item ini?')) {
        return;
    }
    
    fetch('../api/delete_inventory.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: `id=${id}`
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Data berhasil dihapus');
            loadData();
        } else {
            alert(data.message || 'Gagal menghapus data');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Terjadi kesalahan saat menghapus data');
    });
}

// Export CSV
function exportCSV() {
    window.location.href = '../api/export_csv.php';
}

// Show Error
function showError(message) {
    const tbody = document.getElementById('tableBody');
    tbody.innerHTML = `
        <tr>
            <td colspan="8" class="no-data">
                <i class="fas fa-exclamation-triangle" style="color: #f56565;"></i>
                <div>${message}</div>
            </td>
        </tr>
    `;
}

// Event Listeners
document.addEventListener('DOMContentLoaded', function() {
    // Load initial data
    loadData();
    
    // Search input
    document.getElementById('searchInput').addEventListener('input', filterData);
    
    // Filter selects
    document.getElementById('filterKantor').addEventListener('change', filterData);
    document.getElementById('filterKategori').addEventListener('change', filterData);
});

// Auto refresh every 30 seconds
setInterval(loadData, 30000);