/**
 * POS Settings Manager
 * Handles saving and loading POS settings to/from database
 */

// Save POS setting to database
function savePOSSetting(settingKey, settingValue, callback) {
    $.ajax({
        url: '../api/save-pos-settings.php',
        type: 'POST',
        data: {
            setting_key: settingKey,
            setting_value: settingValue
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                console.log('Setting saved:', settingKey, '=', settingValue);
                if (callback && typeof callback === 'function') {
                    callback(true, response);
                }
            } else {
                console.error('Failed to save setting:', response.message);
                if (callback && typeof callback === 'function') {
                    callback(false, response);
                }
            }
        },
        error: function(xhr, status, error) {
            console.error('Error saving setting:', error);
            if (callback && typeof callback === 'function') {
                callback(false, { message: error });
            }
        }
    });
}

// Get specific POS setting from database
function getPOSSetting(settingKey, callback) {
    $.ajax({
        url: '../api/get-pos-settings.php',
        type: 'GET',
        data: {
            setting_key: settingKey
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                console.log('Setting retrieved:', settingKey, '=', response.setting_value);
                if (callback && typeof callback === 'function') {
                    callback(true, response.setting_value);
                }
            } else {
                console.warn('Setting not found:', settingKey);
                if (callback && typeof callback === 'function') {
                    callback(false, null);
                }
            }
        },
        error: function(xhr, status, error) {
            console.error('Error retrieving setting:', error);
            if (callback && typeof callback === 'function') {
                callback(false, null);
            }
        }
    });
}

// Get all POS settings from database
function getAllPOSSettings(callback) {
    $.ajax({
        url: '../api/get-pos-settings.php',
        type: 'GET',
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                console.log('All settings retrieved:', response.settings);
                if (callback && typeof callback === 'function') {
                    callback(true, response.settings);
                }
            } else {
                console.error('Failed to retrieve settings:', response.message);
                if (callback && typeof callback === 'function') {
                    callback(false, {});
                }
            }
        },
        error: function(xhr, status, error) {
            console.error('Error retrieving settings:', error);
            if (callback && typeof callback === 'function') {
                callback(false, {});
            }
        }
    });
}

// Initialize POS settings when document is ready
$(document).ready(function() {
    // Load barcode scan mode setting
    loadBarcodeScanModeSetting();
    
    // Note: Language setting is loaded by translations.js loadLanguagePreference()
    // which is called earlier in index.php
    
    // Save barcode scan mode when changed
    $('#barcodeScanMode').on('change', function() {
        const isEnabled = $(this).is(':checked');
        const modeValue = isEnabled ? 'enabled' : 'disabled';
        const label = $(this).next('label').find('span');
        
        // Update UI immediately
        if (isEnabled) {
            label.text('Auto Scan').attr('data-translate', 'autoScan');
            showNotification('Barcode Auto-Scan Mode: ENABLED', 'success');
        } else {
            label.text('Manual Qty').attr('data-translate', 'manualQty');
            showNotification('Barcode Auto-Scan Mode: DISABLED - Manual Quantity Entry', 'info');
        }
        
        // Save to database
        savePOSSetting('barcode_scan_mode', modeValue, function(success, response) {
            if (success) {
                console.log('Barcode scan mode saved to database:', modeValue);
            } else {
                console.error('Failed to save barcode scan mode:', response.message);
                // Optionally show error notification
                // showNotification('Failed to save setting', 'error');
            }
        });
        
        // Focus back to product code
        $('#productCode').focus();
    });
});

// Load barcode scan mode setting from database
function loadBarcodeScanModeSetting() {
    getPOSSetting('barcode_scan_mode', function(success, value) {
        if (success && value) {
            const isEnabled = (value === 'enabled');
            
            // Update checkbox state
            $('#barcodeScanMode').prop('checked', isEnabled);
            
            // Update label
            const label = $('#barcodeScanMode').next('label').find('span');
            if (isEnabled) {
                label.text('Auto Scan').attr('data-translate', 'autoScan');
            } else {
                label.text('Manual Qty').attr('data-translate', 'manualQty');
            }
            
            console.log('Barcode scan mode loaded from database:', value);
        } else {
            // Default to enabled if not found
            $('#barcodeScanMode').prop('checked', true);
            $('#barcodeScanMode').next('label').find('span').text('Auto Scan').attr('data-translate', 'autoScan');
            
            // Save default setting to database
            savePOSSetting('barcode_scan_mode', 'enabled');
        }
    });
}
