function toggleExportDropdown(btn) {
    const dropdown = btn.parentElement.querySelector('.export-dropdown');
    if (!dropdown) {
        return;
    }
    document.querySelectorAll('.export-dropdown').forEach(d => {
        if (d !== dropdown) {
            d.classList.add('hidden');
            d.style.display = 'none';
        }
    });
    dropdown.classList.toggle('hidden');
    if (dropdown.classList.contains('hidden')) {
        dropdown.style.display = 'none';
    } else {
        dropdown.style.display = 'block';
    }
}

function toggleImportDropdown(btn) {
    const dropdown = btn.parentElement.querySelector('.import-dropdown');
    if (!dropdown) {
        return;
    }
    document.querySelectorAll('.import-dropdown').forEach(d => {
        if (d !== dropdown) {
            d.classList.add('hidden');
            d.style.display = 'none';
        }
    });
    dropdown.classList.toggle('hidden');
    if (dropdown.classList.contains('hidden')) {
        dropdown.style.display = 'none';
    } else {
        dropdown.style.display = 'block';
    }
}

document.addEventListener('click', function(e) {
    if (!e.target.closest('.dropdown-container') && !e.target.closest('.export-dropdown-container')) {
        document.querySelectorAll('.export-dropdown').forEach(d => d.classList.add('hidden'));
    }
    if (!e.target.closest('.dropdown-container') && !e.target.closest('.import-dropdown-container')) {
        document.querySelectorAll('.import-dropdown').forEach(d => d.classList.add('hidden'));
    }
});

function exportData(table, filters = {}) {
    const tableMap = {
        'items': 'items_master',
        'orders': 'orders',
        'grv': 'grv',
        'transactions': 'inventory_transaction',
        'suppliers': 'suppliers',
        'users': 'users',
        'supplier_forecast': 'supplier_forecast',
        'valuation': 'inventory_valuation'
    };
    const apiTable = tableMap[table] || table;
    const params = new URLSearchParams({ type: apiTable, ...filters });
    window.location.href = '../api/export_import.php?' + params.toString();
}

function exportToCSV(table, filters = {}) {
    const tableMap = {
        'items': 'items_master',
        'orders': 'orders',
        'grv': 'grv',
        'transactions': 'inventory_transaction',
        'suppliers': 'suppliers',
        'users': 'users',
        'supplier_forecast': 'supplier_forecast',
        'valuation': 'inventory_valuation'
    };
    const apiTable = tableMap[table] || table;
    const params = new URLSearchParams({ type: apiTable, format: 'csv', ...filters });
    window.location.href = '../api/export_import.php?' + params.toString();
}

function showImportModal(table, format = 'xlsx') {
    const modal = document.getElementById('importModal');
    if (!modal) {
        alert('Error: Import modal not found');
        return;
    }
    const tableMap = {
        'items': 'items_master',
        'orders': 'orders',
        'grv': 'grv',
        'transactions': 'inventory_transaction',
        'suppliers': 'suppliers',
        'users': 'users',
        'supplier_forecast': 'supplier_forecast',
        'valuation': 'inventory_valuation'
    };
    const apiTable = tableMap[table] || table;
    
    const tableEl = document.getElementById('importTable');
    const formatEl = document.getElementById('importFormat');
    const fileEl = document.getElementById('importFile');
    const statusEl = document.getElementById('importStatus');

    if (tableEl) tableEl.value = apiTable;
    if (formatEl) formatEl.value = format;
    if (fileEl) {
        fileEl.value = '';
        fileEl.accept = format === 'csv' ? '.csv' : '.xlsx,.xls';
    }
    if (statusEl) statusEl.innerHTML = '';
    modal.classList.remove('hidden');
    modal.style.display = 'flex';
}

function closeImportModal() {
    const modal = document.getElementById('importModal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

async function handleFileImport(event, table) {
    const file = event.target.files[0];
    if (!file) return;

    const tableMap = {
        'items': 'items_master',
        'orders': 'orders',
        'grv': 'grv',
        'transactions': 'inventory_transaction',
        'suppliers': 'suppliers',
        'users': 'users',
        'supplier_forecast': 'supplier_forecast',
        'valuation': 'inventory_valuation'
    };
    const apiTable = tableMap[table] || table;

    const formData = new FormData();
    formData.append('file', file);
    formData.append('table', apiTable);
    const formatEl = document.getElementById('importFormat');
    const fmt = formatEl ? formatEl.value : (file.name.endsWith('.csv') ? 'csv' : 'xlsx');
    formData.append('format', fmt);

    try {
        const response = await fetch('../api/export_import.php', {
            method: 'POST',
            body: formData
        });
        const result = await response.json();
        console.log('Import result:', result);

        if (result.success !== undefined) {
            let message = `Import complete: ${result.success} records imported`;
            if (result.invalid_dates?.length) {
                message += `\nInvalid dates found: ${result.invalid_dates.length} record(s) skipped. Check console for details.`;
                console.warn('Invalid dates (needs correction):', result.invalid_dates);
            }
            if (result.errors?.length) {
                message += `\nErrors: ${result.errors.length}`;
                console.error('Import errors:', result.errors);
            }
            alert(message);
            closeImportModal();
            if (typeof window.refreshData === 'function') {
                window.refreshData();
            }
            location.reload();
        } else if (result.error) {
            alert('Import failed: ' + result.error);
        }
    } catch (err) {
        alert('Import error: ' + err.message);
    }

    event.target.value = '';
}
