jQuery(function() {
    jQuery('#pwlpara-offer-category-filter').on('change', function() {
        var categoryId = jQuery(this).val();

        if (categoryId != '') {
            jQuery('.pwlpar-offers-table-offer').hide();
            jQuery('.pwlpar-offers-table-offer[data-category-id="' + categoryId + '"]').show();
        } else {
            jQuery('.pwlpar-offers-table-offer').show();
        }

        e.preventDefault();
        return false;

    });

    pwlparaBindOffersTable();
    pwlparaBindOfferEdit();
});

function pwlparaBindOffersTable() {
    jQuery('#pwlpara-offer-category-filter').val('');

    jQuery('.pwlpara-delete-offer-button').off('click.pwlpar').on('click.pwlpar', function(e) {
        if (confirm(pwlpara.i18n.deleteOffer)) {
            var offerRow = jQuery(this).closest('tr');
            pwlparaDeleteOffer(offerRow);
        }

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

    jQuery('#pwlpara-offers-table > tbody').sortable({
        handle: '.pwlpar-sort-handle',
        tolerance: 'pointer',
        update: function() {
            var savingIcon = jQuery('<span>' + pwlpara.i18n.saving + '</span>');
            jQuery('#pwlpara-section-offers-actions').append(savingIcon);

            var offerIds = [];
            jQuery('#pwlpara-offers-table > tbody > tr').each(function() {
                offerIds.push(jQuery(this).attr('data-id'));
            });

            jQuery.post(ajaxurl, {'action': 'pwlpar-sort_offers', 'offer_ids': offerIds, 'security': pwlpara.nonces.sortOffers }, function(result) {
                savingIcon.remove();
                if (!result.success) {
                    alert(result.data.message);
                }
            }).fail(function(xhr, textStatus, errorThrown) {
                savingIcon.remove();
                if (errorThrown) {
                    alert(errorThrown);
                } else {
                    alert(pwlpara.i18n.error);
                }
            });
        },
        helper: function(e, tr) {
            // Set the columns to their specific widths so that drag and drop doesn't resize the table.
            jQuery('#pwlpara-offers-table td, #pwlpara-offers-table th').each(function(){
                jQuery(this).css('width', jQuery(this).width() +'px');
            });

            var $originals = tr.children();
            var $helper = tr.clone();
            $helper.children().each(function(index) {
                // Set helper cell sizes to match the original sizes
                jQuery(this).width($originals.eq(index).width());
            });
            return $helper;
        },
    });
}

function pwlparaBindOfferEdit() {
    if (jQuery('#pwlpara-offer-edit-form').length == 0) {
        return;
    }

    jQuery('.pwlpara-offer-edit-coupon-type-radio-button').on('change', function() {
        var couponType = jQuery(this).val();
        jQuery('.pwlpara-offer-edit-coupon-type').removeClass('pwlpara-offer-edit-coupon-type-active');
        jQuery(this).closest('.pwlpara-offer-edit-coupon-type').addClass('pwlpara-offer-edit-coupon-type-active');

        if (couponType == 'fixed_cart') {
            jQuery('#pwlpara-offer-coupon-settings').show();
            jQuery('#pwlpara-offer-pro-coupon-type').hide();
        } else {
            jQuery('#pwlpara-offer-pro-coupon-type').show();
            jQuery('#pwlpara-offer-coupon-settings').hide();
        }
    });

    // Disable the Claim button in the Offer preview window.
    jQuery('#pwlpara-offer-edit-preview .pwlpar-offer-button').off('click').on('click', function(e) {
        alert(pwlpara.i18n.notAvailableInPreview);
        e.preventDefault();
        return false;
    }).css('cursor', 'not-allowed');

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

    jQuery('#pwlpara-offer-edit-preview .pwlpar-offer-image').on('error', function() {
        jQuery(this).hide();
    });

    jQuery('#pwlpara-offer-edit-title').on('propertychange change keyup input paste', function() {
        var title = jQuery(this).val();

        if (!title) {
            title = jQuery(this).attr('placeholder');
        }

        jQuery('#pwlpara-offer-edit-preview .pwlpar-offer-title').text(title);
    });

    jQuery('#pwlpara-offer-edit-description').on('propertychange change keyup input paste', function() {
        var description = jQuery(this).val();
        jQuery('#pwlpara-offer-edit-preview .pwlpar-offer-description').text(description);
    });

    jQuery('#pwlpara-offer-edit-points').on('propertychange change keyup input paste', function() {
        var points = 0;
        var pointsString = jQuery(this).val();
        if (pointsString) {
            points = parseInt(pointsString);
        }

        if (points > 0) {
            jQuery('.pwlpara-offer-button-points').text(points.toLocaleString());
        } else {
            jQuery('.pwlpara-offer-button-points').text(pwlpara.i18n.free);
        }
    });

    jQuery(document.body).trigger('wc-enhanced-select-init');
    jQuery(document.body).trigger('init_tooltips');
}

function pwlparaLoadOffers() {
    var offersContainer = jQuery('#pwlpara-section-offers-table-container');
    offersContainer.html(pwlpara.i18n.loading);

    jQuery.post(ajaxurl, {'action': 'pwlpar-load_offers', 'security': pwlpara.nonces.loadOffers }, function(result) {
        offersContainer.html(result.data.html);
        pwlparaBindOffersTable();
    }).fail(function(xhr, textStatus, errorThrown) {
        offersContainer.html(pwlpara.i18n.error + ': ' + errorThrown);
    });
}

function pwlparaDeleteOffer(offerRow) {
    offerRow.fadeOut('600');

    var offerId = offerRow.attr('data-id');
    jQuery.post(ajaxurl, {'action': 'pwlpar-delete_offer', 'offer_id': offerId, 'security': pwlpara.nonces.deleteOffer }, function(result) {
        offerRow.remove();
    }).fail(function(xhr, textStatus, errorThrown) {
        offerRow.show();
        if (errorThrown) {
            alert(errorThrown);
        } else {
            alert(pwlpara.i18n.error + ' pwlparaDeleteOffer');
        }
    });
}
