// =========================================================================
// UNIFIED PRODUCT ATTRIBUTES JS CONTROLLER
// Dynamically manages 8 dictionaries with SPA-safe memory handling
// =========================================================================

const apiAttr = '/rimax/application/dripend/systemSetup/product/processProductAttributes.php';
let attrTables = {};

const tableConfigs = {
    'brand': { cols: [
        { data: null, defaultContent: '', className: 'text-center text-muted fw-bold' },
        { data: 'brand_name', className: 'fw-bold text-primary' },
        { data: 'is_active', render: renderStatus },
        { data: null, className: 'text-end', render: r => renderActions('brand', r) }
    ]},
    'manufacturer': { cols: [
        { data: null, defaultContent: '', className: 'text-center text-muted fw-bold' },
        { data: 'manufacturer_name', className: 'fw-bold text-primary' },
        { data: 'country_of_origin', className: 'text-muted' },
        { data: 'is_active', render: renderStatus },
        { data: null, className: 'text-end', render: r => renderActions('manufacturer', r) }
    ]},
    'type': { cols: [
        { data: null, defaultContent: '', className: 'text-center text-muted fw-bold' },
        { data: 'type_name', className: 'fw-bold text-primary' },
        { data: 'is_active', render: renderStatus },
        { data: null, className: 'text-end', render: r => renderActions('type', r) }
    ]},
    'category': { cols: [
        { data: null, defaultContent: '', className: 'text-center text-muted fw-bold' },
        { data: 'category_name', className: 'fw-bold text-primary' },
        { data: 'description', className: 'text-muted small' },
        { data: 'is_active', render: renderStatus },
        { data: null, className: 'text-end', render: r => renderActions('category', r) }
    ]},
    'uom': { cols: [
        { data: null, defaultContent: '', className: 'text-center text-muted fw-bold' },
        { data: 'unit_name', className: 'fw-bold text-primary' },
        { data: 'unit_symbol', className: 'text-muted fw-bold' },
        { data: 'is_active', render: renderStatus },
        { data: null, className: 'text-end', render: r => renderActions('uom', r) }
    ]},
    'therapeutic': { cols: [
        { data: null, defaultContent: '', className: 'text-center text-muted fw-bold' },
        { data: 'class_name', className: 'fw-bold text-primary' },
        { data: 'is_active', render: renderStatus },
        { data: null, className: 'text-end', render: r => renderActions('therapeutic', r) }
    ]},
    'formulation': { cols: [
        { data: null, defaultContent: '', className: 'text-center text-muted fw-bold' },
        { data: 'formulation_name', className: 'fw-bold text-primary' },
        { data: 'formulation_symbol', className: 'text-muted fw-bold' },
        { data: 'description', className: 'text-muted small' },
        { data: 'is_active', render: renderStatus },
        { data: null, className: 'text-end', render: r => renderActions('formulation', r) }
    ]},
    'prescribing': { cols: [
        { data: null, defaultContent: '', className: 'text-center text-muted fw-bold' },
        { data: 'level_code', className: 'fw-bold text-primary' },
        { data: 'description', className: 'text-muted small' },
        { data: 'is_active', render: renderStatus },
        { data: null, className: 'text-end', render: r => renderActions('prescribing', r) }
    ]}
};

// EXPLICIT INITIALIZATION FOR SPA
window.initProductAttributes = function() {
    attrTables = {}; // Clear memory references on SPA load
    loadAttrTab('brand'); // Trigger default tab load
};

window.loadAttrTab = function(type) {
    $('.custom-tabs .tab-link').removeClass('active');
    $(`button[onclick="loadAttrTab('${type}')"]`).addClass('active');
    $('.attr-pane').hide();
    $('#tab_' + type).fadeIn(200);

    buildAttrTable(type);
};

function buildAttrTable(type) {
    let conf = tableConfigs[type];
    if (!conf) return;

    // DESTROY ANY GHOST INSTANCE TO PREVENT SPA CORRUPTION
    if ($.fn.DataTable.isDataTable(`#tbl_${type}`)) {
        $(`#tbl_${type}`).DataTable().clear().destroy();
    }

    attrTables[type] = $(`#tbl_${type}`).DataTable({
        ajax: { 
            url: apiAttr, 
            type: 'POST', 
            data: { action: 'fetch', type: type }, 
            dataSrc: function (json) { return json.data || []; } 
        },
        pageLength: 10,
        order: [[ 1, 'asc' ]],
        columnDefs: [{ searchable: false, orderable: false, targets: 0 }],
        columns: conf.cols,
        destroy: true // Force DataTables to overwrite safely
    });

    attrTables[type].on('order.dt search.dt', function () {
        let i = 1;
        attrTables[type].cells(null, 0, { search: 'applied', order: 'applied' }).every(function () {
            this.data(i++);
        });
    }).draw();
}

function renderStatus(data) {
    return data == 1 ? '<span class="badge bg-success bg-opacity-10 text-success border px-2 py-1 rounded-pill">Active</span>' 
                     : '<span class="badge bg-danger bg-opacity-10 text-danger border px-2 py-1 rounded-pill">Inactive</span>';
}

function renderActions(type, r) {
    let payload = btoa(unescape(encodeURIComponent(JSON.stringify(r))));
    let statusIcon = r.is_active == 1 ? 'fa-toggle-on text-success' : 'fa-toggle-off text-danger';
    return `
        <button class="btn btn-sm btn-light border text-primary px-3 py-1 shadow-sm rounded-pill me-1" onclick="editAttr('${type}', '${payload}')"><i class="fa-solid fa-pen"></i></button>
        <button class="btn btn-sm btn-light border shadow-sm rounded-pill px-3 py-1" onclick="toggleAttrStatus('${type}', ${r.id})"><i class="fa-solid ${statusIcon}"></i></button>
    `;
}

// -------------------------------------------------------------
// DYNAMIC CRUD OPERATIONS
// -------------------------------------------------------------
window.openAttrModal = function(type) {
    let frm = $(`#frm_${type}`);
    frm[0].reset();
    frm.find('input[name="id"]').val('');
    $(`#mdl_${type}`).modal('show');
};

window.editAttr = function(type, payloadStr) {
    let r = JSON.parse(decodeURIComponent(escape(atob(payloadStr))));
    let frm = $(`#frm_${type}`);
    frm[0].reset();
    
    $.each(r, function(key, value) {
        frm.find(`[name="${key}"]`).val(value);
    });
    
    $(`#mdl_${type}`).modal('show');
};

$(document).off('submit', '.attr-form').on('submit', '.attr-form', function(e) {
    e.preventDefault();
    let form = $(this);
    let type = form.data('type');
    let btn = form.find('button[type="submit"]'); 
    let orig = btn.html();
    
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');

    let formData = form.serialize() + `&action=save&type=${type}`;
    
    $.post(apiAttr, formData, function(res) {
        btn.prop('disabled', false).html(orig);
        if (res && res.status === 'success') {
            $(`#mdl_${type}`).modal('hide');
            showAppResponse("Saved", res.message, "success");
            attrTables[type].ajax.reload(null, false);
        } else {
            showAppResponse("Failed", res.message || "An error occurred.", "error");
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        showAppResponse("Error", "Failed to communicate with the server.", "error");
    });
});

window.toggleAttrStatus = function(type, id) {
    appConfirm("Change Status", "Are you sure you want to toggle the status of this record?", function() {
        $.post(apiAttr, { action: 'toggle_status', type: type, id: id }, function(res) {
            if (res && res.status === 'success') {
                attrTables[type].ajax.reload(null, false);
            } else {
                showAppResponse("Error", res.message, "error");
            }
        }, 'json');
    });
};