<div class="separator"></div>
<div class="text_content">
    <h3>Add price rule</h3>
    <table>
        <tr id="affiliate_price_formula_add_form">
            <td>&nbsp;</td>
            <td>

                <select name="category" style="width:100%">
                    <option value="">Any category</option>
                    {% for category in categories %}
                    <option value="{{ category.term_id }}">{% for i in range(1, category.level) %}-{% endfor %}{{
                        category.name }}
                    </option>
                    {% endfor %}
                </select>
            </td>
            <td><input type="text" name="min_price" value="" placeholder="Min price" class="small"/></td>
            <td class="price_label"> < PRICE <</td>
            <td><input type="text" name="max_price" value="" placeholder="Max price" class="small"/></td>
            <td>
                <select name="sign">
                    <option value="="> =</option>
                    <option value="+"> +</option>
                    <option value="*"> *</option>
                </select>
            </td>
            <td><input type="text" name="value" class="small" value="" placeholder="Value"/></td>
            <td class="discount">
                Discount % <select name="discount1">
                <option value="">source %</option>
                <option value="0">0%</option>
                <option value="5">5%</option>
                <option value="10">10%</option>
                <option value="15">15%</option>
                <option value="20">20%</option>
                <option value="25">25%</option>
                <option value="30">30%</option>
                <option value="35">35%</option>
                <option value="40">40%</option>
                <option value="45">45%</option>
                <option value="50">50%</option>
                <option value="55">55%</option>
                <option value="60">60%</option>
                <option value="65">65%</option>
                <option value="70">70%</option>
                <option value="75">75%</option>
                <option value="80">80%</option>
                <option value="85">85%</option>
                <option value="90">90%</option>
                <option value="95">95%</option>
            </select>

                - <select name="discount2">
                <option value="">source %</option>
                <option value="0">0%</option>
                <option value="5">5%</option>
                <option value="10">10%</option>
                <option value="15">15%</option>
                <option value="20">20%</option>
                <option value="25">25%</option>
                <option value="30">30%</option>
                <option value="35">35%</option>
                <option value="40">40%</option>
                <option value="45">45%</option>
                <option value="50">50%</option>
                <option value="55">55%</option>
                <option value="60">60%</option>
                <option value="65">65%</option>
                <option value="70">70%</option>
                <option value="75">75%</option>
                <option value="80">80%</option>
                <option value="85">85%</option>
                <option value="90">90%</option>
                <option value="95">95%</option>
            </select>
            </td>
            <td>
                <button class="button-primary" id="affiliate_add_formula">Add</button>
            </td>
        </tr>
    </table>
    <div class="price_formula_description">Here you can configure your price modification algorithm.</div>
</div>
<div class="separator"></div>
<div class="text_content">
    <h3>Price rules list</h3>

    <table id="affiliate_price_formula" class="wp-list-table widefat fixed striped">
        <thead>
        <tr>
            <td class="manage-column column-pos">#
            </td>
            <td class="manage-column column-category">Category
            </td>
            <td class="manage-column column-price">Price
            </td>
            <td class="manage-column column-value">New Price
            </td>
            <td class="manage-column column-discount">Discount %
            </td>
            <td class="manage-column column-action">&nbsp;
            </td>
        </tr>
        </thead>
        <tbody>
        {% for formula in formulas %}
        <tr formula-id="{{ formula.getId() }}">
            <td>{{ formula.getPos() }}</td>
            <td>{{ formula.getCategoryName() }}</td>
            <td>{{ formula.getMinPrice() }} < PRICE < {{ formula.getMaxPrice() }}</td>
            <td>{% if formula.getSign() == '=' %} {{ formula.getValue() }} {% else %}PRICE {{ formula.getSign() }} {{
                formula.getValue() }}{% endif %}
            </td>
            <td>
                {% if formula.isDiscount1and2() %}
                {% if formula.getDiscount1() > formula.getDiscount2() %}
                {{ formula.getDiscount2() }} % &mdash; {{ formula.getDiscount1() }}
                {% else %}
                {{ formula.getDiscount1() }} % &mdash; {{ formula.getDiscount2() }}
                {% endif %}
                {% elseif formula.getDiscount1() != '' %}
                {{ formula.getDiscount1() }} %
                {% elseif formula.getDiscount2() != '' %}
                {{ formula.getDiscount2() }} %
                {% else %}
                source %
                {% endif %}
            </td>
            <td>
                <a class="button-primary affiliate_edit_formula">Edit</a>
                <a class="button-primary affiliate_del_formula">Delete</a>
            </td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>

<script type="text/javascript">
    jQuery(function () {
        jQuery("#affiliate_add_formula").click(function () {
            var this_row = jQuery(this).parents('tr');

            var data = {
                'action': '{{ prefix }}_price_formula_add',
                'type_name': jQuery('#affiliate_price_formula_add_form [name="type"] option:selected').text(),
                'category': jQuery('#affiliate_price_formula_add_form [name="category"]').val(),
                'category_name': jQuery('#affiliate_price_formula_add_form [name="category"] option:selected').text(),
                'min_price': jQuery('#affiliate_price_formula_add_form [name="min_price"]').val(),
                'max_price': jQuery('#affiliate_price_formula_add_form [name="max_price"]').val(),
                'sign': jQuery('#affiliate_price_formula_add_form [name="sign"]').val(),
                'value': jQuery('#affiliate_price_formula_add_form [name="value"]').val(),
                'discount1': jQuery('#affiliate_price_formula_add_form [name="discount1"]').val(),
                'discount2': jQuery('#affiliate_price_formula_add_form [name="discount2"]').val()
            };
            //console.log('data: ', data);

            if (isNaN(parseFloat(data.value))) {
                alert('Value is required');
                return false;
            }

            if (isNaN(parseFloat(data.min_price))) {
                data.min_price = 0;
            }

            if (isNaN(parseFloat(data.max_price))) {
                data.max_price = 0;
            }

            if (data.min_price < 0.001 && data.max_price < 0.001) {
                alert('Min price or Max price is required');
                return false;
            }

            jQuery('#affiliate_price_formula_add_form input').val('');
            jQuery("#affiliate_price_formula_add_form select").prop("selectedIndex", 0);

            jQuery(this_row).find('.button-primary').hide();
            var loaderContainer = jQuery('<span/>', {'class': 'loader-image-container'}).insertAfter(this);
            jQuery('<img/>', {
                src: WPURLS.siteurl + '/wp-admin/images/loading.gif',
                'class': 'loader-image'
            }).appendTo(loaderContainer);


            jQuery.post(ajaxurl, data, function (response) {
                //console.log('response: ', response);
                var json = jQuery.parseJSON(response);
                var discount_html = "";
                if (json.formula.discount1 && json.formula.discount2) {
                    if (parseInt(json.formula.discount1) > parseInt(json.formula.discount2)) {
                        discount_html = json.formula.discount2 + "% &mdash; " + json.formula.discount1 + "%";
                    } else {
                        discount_html = json.formula.discount1 + "% &mdash; " + json.formula.discount2 + "%";
                    }
                } else if (json.formula.discount1 || json.formula.discount2) {
                    discount_html = (json.formula.discount1 ? json.formula.discount1 : json.formula.discount2) + "%";
                }
                jQuery('#affiliate_price_formula').append('<tr formula-id="' + json.formula.id + '"><td>' + json.formula.pos + '</td><td>' + json.formula.category_name + '</td><td>' + json.formula.min_price + ' < PRICE < ' + json.formula.max_price + '</td><td>' + ((json.formula.sign == "=") ? (json.formula.value) : ("PRICE " + json.formula.sign + " " + json.formula.value)) + '</td><td>' + discount_html + '</td><td><button class="button-primary affiliate_edit_formula">Edit</button> <button class="button-primary affiliate_del_formula">Delete</button></td></tr>');

                jQuery('#affiliate_price_formula_add_form button').removeAttr('disabled');

                jQuery(this_row).find('.button-primary').show();
                loaderContainer.remove();
            });

            return false;
        });

        jQuery("#affiliate_price_formula").on("click", ".affiliate_edit_formula", function () {
            var this_row = jQuery(this).parents('tr');
            var data = {'action': '{{ prefix }}_price_formula_get', 'id': jQuery(this_row).attr('formula-id')};

            jQuery(this_row).find('.button-primary').hide();
            var loaderContainer = jQuery('<span/>', {'class': 'loader-image-container'}).insertAfter(this);
            jQuery('<img/>', {
                src: WPURLS.siteurl + '/wp-admin/images/loading.gif',
                'class': 'loader-image'
            }).appendTo(loaderContainer);

            jQuery.post(ajaxurl, data, function (response) {
                //console.log('response: ', response);
                var json = jQuery.parseJSON(response);
                console.log('response: ', json);

                var html = '<tr>';

                html += '<td><input type="text" name="pos" value="' + json.formula.pos + '"/></td>';

                html += '<td><select name="category">';
                html += '<option value="">Any category</option>';
                jQuery.each(json.categories_tree, function (key, value) {
                    if (json.formula.category == value.id) {
                        html += '<option value="' + value.id + '" selected>' + value.name + '</option>';
                    } else {
                        html += '<option value="' + value.id + '">' + value.name + '</option>';
                    }
                });
                html += '</select></td>';

                html += '<td class="price"><table><tr><td style="padding:0;vertical-align:middle;width:33%;"><input type="text" name="min_price" value="' + json.formula.min_price + '"/></td><td style="padding:0;vertical-align:middle;text-align: center;">< PRICE <</td><td style="padding:0;vertical-align:middle;width: 33%;"><input type="text" name="max_price" value="' + json.formula.max_price + '"/></td></tr></table></td>';

                html += '<td><table><tr>';
                html += '<td style="padding:0;width:45%;"><select name="sign">';
                jQuery.each(json.sign_list, function (key, value) {
                    if (json.formula.sign == value.id) {
                        html += '<option value="' + value.id + '" selected>' + value.name + '</option>';
                    } else {
                        html += '<option value="' + value.id + '">' + value.name + '</option>';
                    }
                });
                html += '</select></td>';
                html += '<td style="padding:0;width:55%;"><input type="text" name="value" value="' + json.formula.value + '"/></td>';
                html += '</tr></table></td>';

                html += '<td><table><tr>';
                html += '<td style="padding:0;width:45%;"><select name="discount1">';
                jQuery.each(json.discount_list, function (key, value) {
                    if (json.formula.discount1 == value.id) {
                        html += '<option value="' + value.id + '" selected>' + value.name + '</option>';
                    } else {
                        html += '<option value="' + value.id + '">' + value.name + '</option>';
                    }
                });
                html += '</select></td>';
                html += '<td style="padding:0;width:45%;"><select name="discount2">';
                jQuery.each(json.discount_list, function (key, value) {
                    if (json.formula.discount2 == value.id) {
                        html += '<option value="' + value.id + '" selected>' + value.name + '</option>';
                    } else {
                        html += '<option value="' + value.id + '">' + value.name + '</option>';
                    }
                });
                html += '</select></td>';
                html += '</tr></table></td>';

                html += '<td class="action"><a class="button-primary affiliate_save_formula">Save</a> <a class="button-primary affiliate_cancel_edit_formula">Cancel</a></td>';

                html += '</tr>';

                jQuery(this_row).after(html);
                jQuery(this_row).hide();

                jQuery(this_row).find('.button-primary').show();
                loaderContainer.remove();
            });

            return false;
        });

        jQuery("#affiliate_price_formula").on("click", ".affiliate_save_formula", function () {
            var this_row = jQuery(this).parents('tr');
            var data = {
                'action': '{{ prefix }}_price_formula_edit',
                'id': jQuery(this_row).prev().attr('formula-id'),
                'pos': jQuery(this_row).find('[name="pos"]').val(),
                'type': jQuery(this_row).find('[name="type"]').val(),
                'type_name': jQuery(this_row).find('[name="type"] option:selected').text(),
                'category': jQuery(this_row).find('[name="category"]').val(),
                'category_name': jQuery(this_row).find('[name="category"] option:selected').text(),
                'min_price': jQuery(this_row).find('[name="min_price"]').val(),
                'max_price': jQuery(this_row).find('[name="max_price"]').val(),
                'sign': jQuery(this_row).find('[name="sign"]').val(),
                'value': jQuery(this_row).find('[name="value"]').val(),
                'discount1': jQuery(this_row).find('[name="discount1"]').val(),
                'discount2': jQuery(this_row).find('[name="discount2"]').val()
            };

            jQuery(this_row).find('.button-primary').hide();
            var loaderContainer = jQuery('<span/>', {'class': 'loader-image-container'}).insertAfter(this);
            jQuery('<img/>', {
                src: WPURLS.siteurl + '/wp-admin/images/loading.gif',
                'class': 'loader-image'
            }).appendTo(loaderContainer);

            jQuery.post(ajaxurl, data, function (response) {
                //console.log('response: ', response);
                var json = jQuery.parseJSON(response);
                console.log('json: ', json);

                var discount_html = "";
                if (json.formula.discount1 && json.formula.discount2) {
                    if (parseInt(json.formula.discount1) > parseInt(json.formula.discount2)) {
                        discount_html = json.formula.discount2 + "% &mdash; " + json.formula.discount1 + "%";
                    } else {
                        discount_html = json.formula.discount1 + "% &mdash; " + json.formula.discount2 + "%";
                    }
                } else if (json.formula.discount1 || json.formula.discount2) {
                    discount_html = (json.formula.discount1 ? json.formula.discount1 : json.formula.discount2) + "%";
                }
                jQuery(this_row).prev().html('<td>' + json.formula.pos + '</td><td>' + json.formula.category_name + '</td><td>' + json.formula.min_price + ' < PRICE < ' + json.formula.max_price + '</td><td>' + ((json.formula.sign == "=") ? (json.formula.value) : ("PRICE " + json.formula.sign + " " + json.formula.value)) + '</td><td>' + discount_html + '</td><td><button class="button-primary affiliate_edit_formula">Edit</button> <button class="button-primary affiliate_del_formula">Delete</button></td>');

                jQuery(this_row).prev().show();
                jQuery(this_row).remove();

                jQuery(this_row).find('.button-primary').show();
                loaderContainer.remove();
            });
        });

        jQuery("#affiliate_price_formula").on("click", ".affiliate_cancel_edit_formula", function () {
            var this_row = jQuery(this).parents('tr');
            jQuery(this_row).prev().show();
            jQuery(this_row).remove();
        });

        jQuery("#affiliate_price_formula").on("click", ".affiliate_del_formula", function () {
            var this_row = jQuery(this).closest('tr');
            var data = {'action': '{{ prefix }}_price_formula_del', 'id': jQuery(this_row).attr('formula-id')};

            jQuery(this_row).find('.button-primary').hide();
            var loaderContainer = jQuery('<span/>', {'class': 'loader-image-container'}).insertAfter(this);
            jQuery('<img/>', {
                src: WPURLS.siteurl + '/wp-admin/images/loading.gif',
                'class': 'loader-image'
            }).appendTo(loaderContainer);

            jQuery.post(ajaxurl, data, function (response) {
                //console.log('response: ', response);

                var find = false;
                jQuery('#affiliate_price_formula tr').each(function (index, el) {
                    if (find) {
                        jQuery(el).find('td').first().html(index - 1);
                    }
                    if (jQuery(el).attr('formula-id') == jQuery(this_row).attr('formula-id')) {
                        find = true;
                    }
                });

                loaderContainer.remove();
                jQuery(this_row).remove();
            });

            return false;
        });

        jQuery(".aeidn_save_formula").click(function () {
            //console.log('save ' + jQuery(this).closest('tr').attr('formula-id'));
            return false;
        });
        jQuery(".aeidn_cancel_formula").click(function () {
            //console.log('cancel ' + jQuery(this).closest('tr').attr('formula-id'));
            return false;
        });
    });
</script>