/**
 * RiMax Dynamic POS Engine
 * Manages UI interactions for billing, offline calculations, and online API intercepts.
 */

$(document).ready(function() {
    // Inherit configurations securely injected from the backend view
    const balanceDue = window.PAYMENT_CONFIG.balanceDue || 0;
    const defaultApiName = window.PAYMENT_CONFIG.defaultApiName || 'Gateway';
    const currency = $('#sys_currency').val() || 'GHS';

    // 1. Initialize first active method on page load
    let firstActive = $('.payment-method-box.active');
    if(firstActive.length > 0) {
        $('#selected_method').val(firstActive.data('method'));
        $('#is_online_api').val(firstActive.data('online'));
        applyMethodRules(firstActive.data('method'), firstActive.data('online'));
    }

    // 2. Handle Dynamic Payment Method Selection
    $('.payment-method-box').click(function() {
        $('.payment-method-box').removeClass('active').removeClass('online-active');
        
        let method = $(this).data('method');
        let isOnline = parseInt($(this).data('online'));
        
        if (isOnline === 1) { 
            $(this).addClass('online-active'); 
        } else { 
            $(this).addClass('active'); 
        }
        
        $('#selected_method').val(method);
        $('#is_online_api').val(isOnline);
        
        applyMethodRules(method, isOnline);
    });

    // 3. Apply Interface Logic per Method Type
    function applyMethodRules(method, isOnline) {
        let btn = $('#btnSubmitPayment');
        
        if (isOnline === 1) {
            $('#reference_container').slideUp();
            $('#transaction_ref').prop('required', false).val('');
            $('#change_container').slideUp();
            btn.removeClass('btn-primary').addClass('btn-success').html(`<i class="fa-solid fa-globe me-2"></i> Initiate ${defaultApiName} Online API`);
        } else {
            $('#change_container').slideDown();
            btn.removeClass('btn-success').addClass('btn-primary').html(`<i class="fa-solid fa-lock me-2"></i> Confirm Payment`);
            
            if(method.toLowerCase().includes('cash')) {
                $('#reference_container').slideUp();
                $('#transaction_ref').prop('required', false).val('');
            } else {
                $('#reference_container').slideDown();
                $('#transaction_ref').prop('required', true);
            }
        }
        $('#amount_input').trigger('input');
    }

    // 4. Dynamic Full vs Partial Mode Handlers
    window.setMode = function(mode) {
        $('.mode-selector').removeClass('active');
        if(mode === 'full') {
            $('#mode_full').addClass('active');
            $('#amount_input').prop('readonly', true).val(balanceDue.toFixed(2)).trigger('input');
        } else {
            $('#mode_partial').addClass('active');
            $('#amount_input').prop('readonly', false).focus();
        }
    };

    // Global function to handle quick amount buttons generated from the database
    window.setAmt = function(val) {
        $('#amount_input').val(parseFloat(val).toFixed(2)).trigger('input');
    };

    // 5. Change Calculator & Overflow Prevention
    $('#amount_input').on('input', function() {
        let amt = parseFloat($(this).val()) || 0;
        let change = amt > balanceDue ? (amt - balanceDue) : 0;
        $('#change_display').text(currency + ' ' + change.toFixed(2));
        
        // Prevent overpayment for digital/online methods (Only Cash gives change)
        let method = $('#selected_method').val() || '';
        if (amt > balanceDue && !method.toLowerCase().includes('cash')) {
            $(this).val(balanceDue.toFixed(2));
            $('#change_display').text(currency + ' 0.00');
        }
    });

    // 6. Process Payment dynamically to Backend
    $('#frmProcessPayment').submit(function(e) {
        e.preventDefault();
        
        let amt = parseFloat($('#amount_input').val()) || 0;
        let method = $('#selected_method').val() || '';

        // Validation Traps
        if (amt <= 0 || amt > balanceDue) {
            if (method.toLowerCase().includes('cash') && amt >= balanceDue) {
                // Allow Cash to exceed for change
            } else {
                alert("Invalid amount specified based on payment method rules."); 
                return;
            }
        }

        let isOnline = parseInt($('#is_online_api').val());
        let btn = $('#btnSubmitPayment');
        let orig = btn.html();
        
        if(isOnline === 1) {
            btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-2"></i> Connecting to API Gateway...');
        } else {
            btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin me-2"></i> Processing Transaction...');
        }

        $.ajax({
            url: '/rimax/application/dripend/includes/account/processAddPayment.php',
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function(res) {
                if(res.status === 'success') {
                    // Reload UI to show Settled/Print Screen
                    window.location.reload();
                } else if (res.status === 'pending_online') {
                    // DYNAMIC ONLINE PAYMENT REDIRECT TRIGGER
                    btn.html('<i class="fa-solid fa-check me-2"></i> Redirecting to Gateway...');
                    alert(res.message);
                    if(res.redirect_url) { window.location.href = res.redirect_url; }
                } else {
                    alert("Error: " + res.message);
                    btn.prop('disabled', false).html(orig);
                }
            },
            error: function() {
                alert("A fatal server error occurred during payment routing.");
                btn.prop('disabled', false).html(orig);
            }
        });
    });
});