jQuery(document).ready(function($) {
// --- UTILITY FUNCTION: Read Game ID from URL (Fallback) ---
function getGameIdFromUrl() {
var urlParams = new URLSearchParams(window.location.search);
var gameId = parseInt(urlParams.get('sk_game_id'));
return isNaN(gameId) ? 0 : gameId;
}
// --- CRITICAL FIX: Get reliable Game ID and Host Token from the DOM (HTML) ---
// Read directly from the hidden fields placed in sk-admin-page.php
var sk_current_game_id = parseInt($('#sk-current-game-id-hidden').val()) || getGameIdFromUrl();
var sk_host_auth_token = $('#sk-host-auth-token-hidden').val() || '';
if (sk_current_game_id === 0) {
console.warn("No game ID found. Scoring functions disabled.");
}
// --- End Critical Fix Section ---
// --- 1. On-the-Fly Score Update Logic (Admin) ---
$(document).on('blur', '.score-input', function() {
var $input = $(this);
var teamId = $input.data('team-id');
var roundCol = $input.data('round-col');
var newScore = $input.val();
var gameId = sk_current_game_id;
var hostAuth = sk_host_auth_token;
if (teamId === undefined || roundCol === undefined || newScore === '' || gameId === 0) {
console.error('Missing data for update. Team ID:', teamId, 'Round:', roundCol, 'Game ID:', gameId);
if (gameId === 0) {
alert('Please ensure you have selected or created a Scoreboard Location before adding scores.');
}
return;
}
$input.css('background-color', '#fffbe0');
$.ajax({
url: sk_vars.ajaxurl,
type: 'POST',
data: {
action: 'update_score',
nonce: sk_vars.nonce,
sk_host_auth: hostAuth,
game_id: gameId,
team_id: teamId,
round_col: roundCol,
new_score: newScore
},
success: function(response) {
if (response.success) {
if (typeof response.data.new_total !== 'undefined') {
var newTotal = response.data.new_total;
$('.team-total[data-team-id="' + teamId + '"]').text(newTotal);
$input.css('background-color', '#e0ffec');
setTimeout(function() {
$input.css('background-color', '');
sortTableByTotal();
}, 500);
} else {
alert('Error saving score: ' + response.data.message);
$input.css('background-color', '#ffe0e0');
}
} else {
alert('Error saving score: ' + response.data.message);
$input.css('background-color', '#ffe0e0');
}
},
error: function() {
alert('An unexpected AJAX error occurred. Check browser console.');
$input.css('background-color', '#ffe0e0');
}
});
});
// --- 2. Table Sorting Logic (Admin) ---
function sortTableByTotal() {
var $tableBody = $('#the-list');
var $rows = $tableBody.find('tr').get();
$rows.sort(function(a, b) {
var keyA = parseInt($(a).find('.team-total').text());
var keyB = parseInt($(b).find('.team-total').text());
if (keyA < keyB) return 1;
if (keyA > keyB) return -1;
return 0;
});
$.each($rows, function(index, row) {
$tableBody.append(row);
});
}
// --- 3. Publish Scores Button (Admin) ---
$(document).on('click', '#update-public-scores', function() {
var $btn = $(this);
var gameId = $btn.data('game-id');
var hostAuth = sk_host_auth_token;
$btn.text('Publishing...').prop('disabled', true);
$.ajax({
url: sk_vars.ajaxurl,
type: 'POST',
data: {
action: 'publish_scores',
nonce: sk_vars.nonce,
sk_host_auth: hostAuth,
game_id: gameId
},
success: function(response) {
if (response.success) {
var locationName = $btn.closest('.sk-add-team-section').find('select[name="sk_game_id"] option:selected').text();
$btn.text('Published! (' + locationName + ')');
} else {
alert('Error publishing scores: ' + response.data.message);
$btn.text('Error Publishing');
}
},
complete: function() {
setTimeout(function() {
$btn.text('Publish Latest Scores');
$btn.prop('disabled', false);
}, 3000);
}
});
});
// --- 4. Reset Game Button Handler (Final AJAX POST Flow) ---
$(document).on('click', '#reset-current-game', function(e) {
var $btn = $(this);
var gameId = $btn.data('game-id');
var locationName = $btn.closest('.sk-scorekeeper-wrap').find('select[name="sk_game_id"] option:selected').text();
var hostAuth = sk_host_auth_token;
var confirmed = confirm(
"DANGER: Are you absolutely sure you want to delete ALL TEAMS and SCORES for the board: " +
locationName +
"?\n\nThis action cannot be undone."
);
if (confirmed) {
$btn.text('Resetting...');
$.ajax({
url: sk_vars.ajaxurl,
type: 'POST',
data: {
action: 'perform_reset', // Call the new AJAX handler
nonce: sk_vars.nonce, // Send the standard nonce
game_id: gameId,
sk_host_auth: hostAuth
},
success: function(response) {
if (response.success) {
alert('Board successfully reset!');
window.location.reload(); // Force browser reload
} else {
alert('Error resetting board: ' + response.data.message);
$btn.text('⚠️ Reset/Clear Current Board Scores');
}
},
error: function() {
alert('AJAX error during reset request. Reset aborted.');
$btn.text('⚠️ Reset/Clear Current Board Scores');
}
});
}
});
// --- 5. Public Scoreboard Polling Logic ---
if (typeof sk_public_game_id !== 'undefined') {
var last_timestamp = sk_initial_timestamp;
var gameId = sk_public_game_id;
setInterval(function() {
$.post(sk_vars.ajaxurl, {
action: 'get_current_timestamp',
nonce: sk_vars.nonce,
game_id: gameId
}, function(response) {
if (response.success && response.data.timestamp > last_timestamp) {
var containerId = '#sk-public-scoreboard-container-' + gameId;
$(containerId).load(window.location.href + ' ' + containerId + ' > *', function() {
last_timestamp = response.data.timestamp;
var date = new Date(last_timestamp * 1000);
var timeString = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
$('#sk-timestamp-' + gameId).text(timeString);
sk_public_game_id = gameId;
sk_initial_timestamp = last_timestamp;
console.log('Scoreboard updated for Game ID ' + gameId + ' at ' + timeString);
});
}
});
}, 10000);
}
// Initial sort when the admin page loads
if (typeof sk_current_game_id !== 'undefined') {
sortTableByTotal();
}
});
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/heateg.com/httpdocs/tools/wp-content/plugins/custom-scorekeeper/includes/sk-ajax-handler.php:1) in /var/www/vhosts/heateg.com/httpdocs/tools/wp-includes/rest-api/class-wp-rest-server.php on line 1902
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/heateg.com/httpdocs/tools/wp-content/plugins/custom-scorekeeper/includes/sk-ajax-handler.php:1) in /var/www/vhosts/heateg.com/httpdocs/tools/wp-includes/rest-api/class-wp-rest-server.php on line 1902
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/heateg.com/httpdocs/tools/wp-content/plugins/custom-scorekeeper/includes/sk-ajax-handler.php:1) in /var/www/vhosts/heateg.com/httpdocs/tools/wp-includes/rest-api/class-wp-rest-server.php on line 1902
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/heateg.com/httpdocs/tools/wp-content/plugins/custom-scorekeeper/includes/sk-ajax-handler.php:1) in /var/www/vhosts/heateg.com/httpdocs/tools/wp-includes/rest-api/class-wp-rest-server.php on line 1902
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/heateg.com/httpdocs/tools/wp-content/plugins/custom-scorekeeper/includes/sk-ajax-handler.php:1) in /var/www/vhosts/heateg.com/httpdocs/tools/wp-includes/rest-api/class-wp-rest-server.php on line 1902
Warning: Cannot modify header information - headers already sent by (output started at /var/www/vhosts/heateg.com/httpdocs/tools/wp-content/plugins/custom-scorekeeper/includes/sk-ajax-handler.php:1) in /var/www/vhosts/heateg.com/httpdocs/tools/wp-includes/rest-api/class-wp-rest-server.php on line 1902
{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":401}}