// =========================================================================
// MEDICATION CALCULATION ENGINE JS
// Fixed SPA Event Delegation to prevent Native Form Redirects
// =========================================================================

const apiEngine = '/rimax/application/dripend/systemSetup/product/processMedicationCalculation.php';
let dtRules = null;
let dtFreqs = null;

// Expose initialization to the System Setup Router
window.initMedicationCalculation = function() {
    loadEngineDependencies();
    initRulesTable();
    initFreqsTable();
};

window.showAppResponse = function(title, msg, type = 'success') {
    if ($('#appResponseModal').length === 0) return;

    if(type === 'success') {
        $('#appResIcon').attr('class', 'fa-solid fa-circle-check text-success fa-4x mb-3');
        $('#appResBtn').attr('class', 'btn btn-success fw-bold px-4 mt-2');
    } else {
        $('#appResIcon').attr('class', 'fa-solid fa-triangle-exclamation text-danger fa-4x mb-3');
        $('#appResBtn').attr('class', 'btn btn-dark fw-bold px-4 mt-2');
    }
    $('#appResTitle').text(title);
    $('#appResMsg').text(msg);
    $('#appResponseModal').modal('show');
};

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

    if (tabName === 'rules' && dtRules) dtRules.columns.adjust();
    if (tabName === 'freqs' && dtFreqs) dtFreqs.columns.adjust();
};

function loadEngineDependencies() {
    $.post(apiEngine, { action: 'fetch_dependencies' }, function(res) {
        if (res && res.status === 'success') {
            let mOpts = ''; res.data.modes.forEach(m => mOpts += `<option value="${m.id}">${m.mode_name}</option>`);
            let fOpts = ''; res.data.formulas.forEach(f => fOpts += `<option value="${f.id}">${f.formula_name}</option>`);
            let rOpts = ''; res.data.rounding.forEach(r => rOpts += `<option value="${r.id}">${r.rule_name}</option>`);

            $('#f_mode_id').html(mOpts);
            $('#f_formula_id').html(fOpts);
            $('#f_rounding_id').html(rOpts);
            refreshSandboxRules();
        }
    }, 'json');
}

function refreshSandboxRules() {
    $.post(apiEngine, { action: 'fetch_calc_rules' }, function(res) {
        if (res && res.status === 'success') {
            let sOpts = '<option value="">-- Select Rule to Simulate --</option>';
            res.data.forEach(r => sOpts += `<option value="${r.id}">${r.rule_name}</option>`);
            $('#sb_rule').html(sOpts);
        }
    }, 'json');
}

function initRulesTable() {
    if (dtRules !== null) { dtRules.destroy(); }
    
    dtRules = $('#tblRules').DataTable({
        ajax: { url: apiEngine, type: 'POST', data: { action: 'fetch_calc_rules' }, dataSrc: function (json) { return json.data || []; } },
        pageLength: 10,
        order: [[ 1, 'asc' ]],
        columnDefs: [{ searchable: false, orderable: false, targets: 0 }],
        columns: [
            { data: null, defaultContent: '', className: 'fw-bold text-muted text-center' },
            { data: 'rule_name', className: 'fw-bold text-primary' },
            { data: null, render: r => `<span class="small fw-bold text-dark">${r.formula_name}</span><br><code class="text-muted" style="font-size:11px;">${r.math_expression}</code>` },
            { data: 'mode_name', render: d => `<span class="badge bg-dark bg-opacity-10 text-dark border px-2 py-1">${d}</span>` },
            { data: 'rounding_name', className: 'small fw-bold text-success' },
            { data: null, className: 'text-end', render: function(r) {
                let payload = btoa(unescape(encodeURIComponent(JSON.stringify(r))));
                return `<button class="btn btn-sm btn-light border text-primary px-3 py-1 shadow-sm rounded-pill" onclick="editRule('${payload}')">Edit</button>`;
            }}
        ]
    });
    dtRules.on('order.dt search.dt', function () { let i = 1; dtRules.cells(null, 0, { search: 'applied', order: 'applied' }).every(function (cell) { this.data(i++); }); }).draw();
}

window.openRuleModal = function() {
    $('#frmRule')[0].reset();
    $('#f_rule_id').val('');
    $('#ruleModal').modal('show');
};

window.editRule = function(payloadBase64) {
    let r = JSON.parse(decodeURIComponent(escape(atob(payloadBase64))));
    $('#frmRule')[0].reset();
    $('#f_rule_id').val(r.id);
    $('#f_rule_name').val(r.rule_name);
    $('#f_base_unit').val(r.base_inventory_unit);
    $('#f_mode_id').val(r.mode_id);
    $('#f_formula_id').val(r.formula_id);
    $('#f_rounding_id').val(r.rounding_id);
    $('#ruleModal').modal('show');
};

// USING DELEGATED EVENT LISTENER FOR DYNAMIC DOM
$(document).off('submit', '#frmRule').on('submit', '#frmRule', function(e) {
    e.preventDefault();
    let btn = $('#btnRuleSubmit'); let orig = btn.html();
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');

    $.post(apiEngine, $(this).serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if (res && res.status === 'success') {
            $('#ruleModal').modal('hide');
            showAppResponse("Saved", res.message, "success");
            dtRules.ajax.reload();
            refreshSandboxRules();
        } else {
            showAppResponse("Failed", res.message, "error");
        }
    }, 'json');
});

function initFreqsTable() {
    if (dtFreqs !== null) { dtFreqs.destroy(); }
    
    dtFreqs = $('#tblFreqs').DataTable({
        ajax: { url: apiEngine, type: 'POST', data: { action: 'fetch_frequencies' }, dataSrc: function (json) { return json.data || []; } },
        pageLength: 10,
        order: [[ 3, 'desc' ]],
        columnDefs: [{ searchable: false, orderable: false, targets: 0 }],
        columns: [
            { data: null, defaultContent: '', className: 'fw-bold text-muted text-center' },
            { data: 'freq_code', className: 'fw-bold text-dark' },
            { data: 'description', className: 'small text-muted fw-bold' },
            { data: 'multiplier', render: d => `<span class="badge bg-primary px-3 py-1 fs-6 rounded-pill shadow-sm">x ${d}</span>` },
            { data: null, className: 'text-end', render: function(r) {
                let payload = btoa(unescape(encodeURIComponent(JSON.stringify(r))));
                return `<button class="btn btn-sm btn-light border text-primary px-3 py-1 shadow-sm rounded-pill" onclick="editFreq('${payload}')">Edit</button>`;
            }}
        ]
    });
    dtFreqs.on('order.dt search.dt', function () { let i = 1; dtFreqs.cells(null, 0, { search: 'applied', order: 'applied' }).every(function (cell) { this.data(i++); }); }).draw();
}

window.openFreqModal = function() {
    $('#frmFreq')[0].reset();
    $('#f_freq_id').val('');
    $('#freqModal').modal('show');
};

window.editFreq = function(payloadBase64) {
    let r = JSON.parse(decodeURIComponent(escape(atob(payloadBase64))));
    $('#frmFreq')[0].reset();
    $('#f_freq_id').val(r.id);
    $('#f_freq_code').val(r.freq_code);
    $('#f_freq_desc').val(r.description);
    $('#f_freq_mult').val(r.multiplier);
    $('#freqModal').modal('show');
};

// USING DELEGATED EVENT LISTENER FOR DYNAMIC DOM
$(document).off('submit', '#frmFreq').on('submit', '#frmFreq', function(e) {
    e.preventDefault();
    let btn = $('#btnFreqSubmit'); let orig = btn.html();
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');

    $.post(apiEngine, $(this).serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if (res && res.status === 'success') {
            $('#freqModal').modal('hide');
            showAppResponse("Saved", res.message, "success");
            dtFreqs.ajax.reload();
        } else {
            showAppResponse("Failed", res.message, "error");
        }
    }, 'json');
});

// -------------------------------------------------------------
// SANDBOX SIMULATOR (SAFE DELEGATED BINDING)
// -------------------------------------------------------------
$(document).off('submit', '#frmSandbox').on('submit', '#frmSandbox', function(e) {
    e.preventDefault(); // Absolute guarantee it won't redirect
    
    let btn = $('#btnTest'); let orig = btn.html();
    btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Simulating...');

    $.post(apiEngine, $(this).serialize(), function(res) {
        btn.prop('disabled', false).html(orig);
        if (res && res.status === 'success') {
            $('#sandbox_result').slideDown();
            $('#res_equation').text(res.expression);
            $('#res_raw').text(res.raw_result);
            $('#res_final').text(res.final_dispense_qty);
            $('#res_unit').text(res.unit || 'Units');
            $('#res_mode').text(res.mode);
            
            $('#res_final').fadeOut(100).fadeIn(100).fadeOut(100).fadeIn(100);
        } else {
            showAppResponse("Simulation Error", res.message, "error");
        }
    }, 'json').fail(function() {
        btn.prop('disabled', false).html(orig);
        showAppResponse("Network Error", "Failed to communicate with the calculation engine.", "error");
    });
});