jQuery(document).ready(function($) {
var orderSelect = $('#form-field-ordini_utente');
var container = $('#prodotti-reso-container');
var hiddenField = $('#form-field-prodotti_selezionati');
// 1. Controllo la sessione e popolo la tendina appena la pagina si carica
orderSelect.html('Checking account...').prop('disabled', true);
$.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: { action: 'get_user_orders_dropdown' },
success: function(response) {
if (response.success) {
// Utente loggato con ordini -> Sblocco e popolo
orderSelect.html(response.data.html).prop('disabled', false);
} else {
// Utente non loggato o senza ordini -> Lascio bloccato e mostro l'errore
orderSelect.html('' + response.data.message + '');
}
},
error: function() {
orderSelect.html('Server connection error.');
}
});
// 2. Quando l'utente seleziona un ordine, carico i prodotti
orderSelect.on('change', function() {
var orderId = $(this).val();
if (orderId) {
container.html('
Loading products... ');
$.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: {
action: 'get_woo_order_items_logged_in',
order_id: orderId
},
success: function(response) {
if (response.success) {
var html = '
Select the products to return:
';
response.data.products.forEach(function(p) {
var val = p.name + ' (Qty: ' + p.qty + ')';
html += '
';
html += ' ' + val;
html += ' ';
});
container.html(html);
} else {
container.html('
' + response.data.message + ' ');
}
},
error: function() {
container.html('
Server communication error. Please try again. ');
}
});
} else {
container.html('Select an order to load its products.');
}
});
// 3. Aggiorno il campo nascosto da inviare via mail
$(document).on('change', '.reso-item', function() {
var selectedProducts = [];
$('.reso-item:checked').each(function() {
selectedProducts.push($(this).val());
});
hiddenField.val(selectedProducts.join(' | '));
});
});