jQuery(function() {
    pwlparaBindMembersTable();

    jQuery('#pwlpara-section-members-search-form').on('submit', function(e) {
        pwlparaLoadMembers();

        e.preventDefault();
        return false;
    });

    pwlparaHandleFormSubmission('#pwlpara-member-edit-form');

    jQuery('#pwlpara-member-edit-add-transaction-button').on('click', function(e) {
        var points = prompt(pwlpara.i18n.promptForPointsAdjustment);
        if (points !== null) {
            var note = prompt(pwlpara.i18n.promptForNote);
            if (note !== null) {
                pwlparaMemberEditAdjustBalance(points, note);
            }
        }

        e.preventDefault();
        return false;
    });

    jQuery('.pwlpara-delete-transaction-button').on('click', function(e) {
        if (confirm(pwlpara.i18n.deleteTransaction)) {
            var transactionRow = jQuery(this).closest('tr');
            pwlparaDeleteTransaction(transactionRow);
        }

        e.preventDefault();
        return false;
    });

    jQuery('.pwlpara-delete-reward-button').on('click', function(e) {
        if (confirm(pwlpara.i18n.deleteReward)) {
            var rewardRow = jQuery(this).closest('tr');
            pwlparaDeleteReward(rewardRow);
        }

        e.preventDefault();
        return false;
    });

    jQuery('#pwlpara-member-edit-reward-status-filter').on('change', function() {
        var status = jQuery(this).val();

        if (status != '') {
            jQuery('.pwlpara-member-rewards-table-reward').hide();
            jQuery('.pwlpara-member-rewards-table-reward[data-status="' + status + '"]').show();
        } else {
            jQuery('.pwlpara-member-rewards-table-reward').show();
        }

        e.preventDefault();
        return false;

    });
});

function pwlparaLoadMembers() {
    var container = jQuery('#pwlpara-members-table-container');
    container.html(pwlpara.i18n.loading);

    var search = jQuery('#pwlpara-members-search-input').val();

    jQuery.post(ajaxurl, {'action': 'pwlpar-load_members', 'search': search, 'security': pwlpara.nonces.loadMembers }, function(result) {
        container.html(result.data.html);
        pwlparaBindMembersTable();
    }).fail(function(xhr, textStatus, errorThrown) {
        container.html(pwlpara.i18n.error + ': ' + errorThrown);
    });
}

function pwlparaBindMembersTable() {
    jQuery('.pwlpara-members-table-add-points-button').on('click', function(e) {
        var userId = jQuery(this).closest('tr').attr('data-user-id');
        var points = prompt(pwlpara.i18n.promptForPoints);
        if (points !== null) {
            var note = prompt(pwlpara.i18n.promptForNote);
            if (note !== null) {
                var userId = jQuery(this).closest('tr').attr('data-user-id');
                var balanceElement = jQuery(this).closest('tr').find('.pwlpara-members-table-balance');
                pwlparaMembersTableAdjustBalance(userId, points, note, balanceElement);
            }
        }

        e.preventDefault();
        return false;
    });

    jQuery('.pwlpara-members-table-subtract-points-button').on('click', function(e) {
        var userId = jQuery(this).closest('tr').attr('data-user-id');
        var points = prompt(pwlpara.i18n.promptForPoints);
        if (points !== null) {
            var note = prompt(pwlpara.i18n.promptForNote);
            if (note !== null) {
                var userId = jQuery(this).closest('tr').attr('data-user-id');
                var balanceElement = jQuery(this).closest('tr').find('.pwlpara-members-table-balance');
                pwlparaMembersTableAdjustBalance(userId, -points, note, balanceElement);
            }
        }

        e.preventDefault();
        return false;
    });
}

function pwlparaMembersTableAdjustBalance(userId, amount, note, balanceElement) {
    var originalBalance = balanceElement.text();
    balanceElement.html(pwlpara.i18n.loading);

    jQuery.post(ajaxurl, {'action': 'pwlpar-adjust_balance', 'user_id': userId, 'amount': amount, 'note': note, 'security': pwlpara.nonces.adjustBalance }, function(result) {
        if (result.success) {
            balanceElement.text(result.data.balance);
        } else {
            balanceElement.text(originalBalance);
            alert(result.data.message);
        }
    }).fail(function(xhr, textStatus, errorThrown) {
        balanceElement.text(originalBalance);
        if (errorThrown) {
            alert(errorThrown);
        } else {
            alert(pwlpara.i18n.error + ' pwlparaMembersTableAdjustBalance');
        }
    });
}

function pwlparaMemberEditLoadTransactions() {
    var userId = jQuery('#pwlpara-member-edit-user-id').val();
    var transactions = jQuery('#pwlpara-member-edit-transactions');
    transactions.html(pwlpara.i18n.loading);

    jQuery.post(ajaxurl, {'action': 'pwlpar-view_transactions', 'user_id': userId, 'security': pwlpara.nonces.viewTransactions }, function(result) {
        if (result.success) {
            transactions.html(result.data.html);
        } else {
            transactions.text('');
            alert(result.data.message);
        }
    }).fail(function(xhr, textStatus, errorThrown) {
        transactions.text('');
        if (errorThrown) {
            alert(errorThrown);
        } else {
            alert(pwlpara.i18n.error + ' pwlparaMemberEditAdjustBalance');
        }
    });
}

function pwlparaMemberEditAdjustBalance(amount, note) {
    var userId = jQuery('#pwlpara-member-edit-user-id').val();
    var savingIcon = jQuery('<span>' + pwlpara.i18n.saving + '</span>');
    jQuery('#pwlpara-section-member-edit-actions').append(savingIcon);

    jQuery.post(ajaxurl, {'action': 'pwlpar-adjust_balance', 'user_id': userId, 'amount': amount, 'note': note, 'security': pwlpara.nonces.adjustBalance }, function(result) {
        savingIcon.remove();
        if (result.success) {
            jQuery('#pwlpara-member-edit-balance').text(result.data.balance);
            pwlparaMemberEditLoadTransactions();
        } else {
            alert(result.data.message);
        }
    }).fail(function(xhr, textStatus, errorThrown) {
        savingIcon.remove();
        if (errorThrown) {
            alert(errorThrown);
        } else {
            alert(pwlpara.i18n.error + ' pwlparaMemberEditAdjustBalance');
        }
    });
}

function pwlparaDeleteTransaction(transactionRow) {
    transactionRow.fadeOut('600');

    var transactionId = transactionRow.attr('data-id');
    jQuery.post(ajaxurl, {'action': 'pwlpar-delete_transaction', 'transaction_id': transactionId, 'security': pwlpara.nonces.deleteTransaction }, function(result) {
        if (result.success) {
            transactionRow.remove();
        } else {
            transactionRow.show();
            alert(result.data.message);
        }
    }).fail(function(xhr, textStatus, errorThrown) {
        transactionRow.show();
        if (errorThrown) {
            alert(errorThrown);
        } else {
            alert(pwlpara.i18n.error + ' pwlparaDeleteTransaction');
        }
    });
}

function pwlparaDeleteReward(rewardRow) {
    rewardRow.fadeOut('600');

    var rewardId = rewardRow.attr('data-id');
    jQuery.post(ajaxurl, {'action': 'pwlpar-delete_reward', 'reward_id': rewardId, 'security': pwlpara.nonces.deleteReward }, function(result) {
        if (result.success) {
            rewardRow.remove();
        } else {
            rewardRow.show();
            alert(result.data.message);
        }
    }).fail(function(xhr, textStatus, errorThrown) {
        rewardRow.show();
        if (errorThrown) {
            alert(errorThrown);
        } else {
            alert(pwlpara.i18n.error + ' pwlparaDeleteReward');
        }
    });
}
