var _importData = null;

$(function () {
    $('#btnPreviewImport').on('click', previewImport);
    $('#btnRunImport').on('click', runImport);
});

function previewImport() {
    var type = $('#importType').val();
    var file = $('#importFile')[0].files[0];
    if (!type || !file) { showToast('Select type and file', 'danger'); return; }

    var fd = new FormData();
    fd.append('file', file);

    $.ajax({
        url: 'api/data_import.php?type=' + type + '&action=preview',
        method: 'POST',
        data: fd,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function (res) {
            if (res.status !== 'success') { showToast(res.message, 'danger'); return; }
            _importData = { type: type, file: file };
            var rows = res.data || [];
            var thead = '', tbody = '';
            if (rows.length) {
                var keys = Object.keys(rows[0]);
                thead = '<tr>' + keys.map(function (k) { return '<th>' + escapeHtml(k) + '</th>'; }).join('') + '</tr>';
                rows.forEach(function (r) {
                    tbody += '<tr>' + keys.map(function (k) { return '<td>' + escapeHtml(r[k] || '') + '</td>'; }).join('') + '</tr>';
                });
            }
            $('#previewHead').html(thead);
            $('#previewBody').html(tbody);
            $('#previewCount').text('Showing first ' + rows.length + ' of ' + res.total + ' rows');
            $('#importPreview').removeClass('d-none');
            $('#btnRunImport').prop('disabled', false);
        },
        error: function () { showToast('Upload error', 'danger'); }
    });
}

function runImport() {
    if (!_importData) return;
    $('#btnRunImport').prop('disabled', true).text('Importing...');

    var fd = new FormData();
    fd.append('file', _importData.file);
    fd.append('type', _importData.type);
    fd.append('csrf_token', window.CSRF_TOKEN);

    $.ajax({
        url: 'api/data_import.php?action=import',
        method: 'POST',
        data: fd,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function (res) {
            if (res.status !== 'success') {
                $('#importResult').html('<div class="alert alert-danger">' + escapeHtml(res.message) + '</div>').removeClass('d-none');
                return;
            }
            var h = '<div class="alert alert-success">Imported ' + res.imported + ' records successfully!</div>';
            if (res.errors && res.errors.length) {
                h += '<div class="alert alert-warning small"><strong>' + res.errors.length + ' errors:</strong><br>' + res.errors.map(function (e) { return escapeHtml(e); }).join('<br>') + '</div>';
            }
            $('#importResult').html(h).removeClass('d-none');
            $('#btnRunImport').prop('disabled', true);
            showToast('Import complete!', 'success');
        },
        error: function () { showToast('Import failed', 'danger'); }
    }).always(function () { $('#btnRunImport').text('Import'); });
}

function showToast(m, t) {
    var e = document.createElement('div');
    e.className = 'position-fixed top-0 end-0 p-3';
    e.style.zIndex = '9999';
    e.innerHTML = '<div class="alert alert-' + t + ' alert-dismissible fade show" role="alert">' + escapeHtml(m) + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    document.body.appendChild(e);
    setTimeout(function () { e.remove(); }, 5000);
}

function escapeHtml(t) { return $('<div>').text(t || '').html(); }
