jQuery(document).ready(function ($) {
    $("#wiaas-add-pricing").click(function (event) {
        event.preventDefault();

        var pay_type = $('#wiaas_pay_types').val();

        if (! pay_type) {
            return;
        }

        var set_index = $("#wiaas_package_pricing_rules").data('setindex') + 1;
        $("#wiaas_package_pricing_rules").data('setindex', set_index);

        var data = {
            'pay_type': pay_type,
            action: 'create_empty_pricing_rule'
    };

        $.post(ajaxurl, data, function (response) {
            $('#wiaas_package_pricing_rules').append(response);

            $(`#wiaas_pay_type_${pay_type}`).prop( 'disabled', true );

            $('#wiaas_pay_types').val('0');

        });
    });

    //Remove Pricing Type
    $('#wiaas_package_pricing_rules').delegate('.delete_wiaas_pricing_rule', 'click', function (event) {
        event.preventDefault();
        if (confirm('Are you sure you would like to remove this pay type?')) {
            var name = $(this).data('name');
            $('#wiaas-pricing-rule-' + name).slideUp().remove();

            // append new option to controls
            $(`#wiaas_pay_type_${name}`).prop( 'disabled', false );
        }
    });

    $('#wiaas_package_pricing_rules').delegate('.wiaas_minimal_services_price', 'change', function (event) {
        event.preventDefault();

        var minimal_services_price = parseFloat($(this).val()) || 0;
        var principal_amount = 0;
        var name = $(this).data('name');

        var principal_amount_input = $(`#wiaas_principal_amount_${name}`).first();
        if (principal_amount_input) {
            principal_amount = parseFloat(principal_amount_input.val() / principal_amount_input.data('period')) || 0;
        }
        $(`#wiaas_minimal_recurrent_price_${name}`).text((minimal_services_price + principal_amount).toFixed(2));

        var services_contract_period = $(this).data('period');
        if (services_contract_period > 0) {
            var final_services_price = minimal_services_price * services_contract_period;
            $(`#wiaas_minimal_services_price_${name}_final`).text(final_services_price.toFixed(2));
        }

    });

    $('#wiaas_package_pricing_rules').delegate('.wiaas_principal_amount', 'change', function (event) {
        event.preventDefault();

        var value = parseFloat($(this).val());
        var period = parseFloat($(this).data('period'));
        var interestRate = 0.58;


        var principal_amount = wiaasCalculateFinancing(interestRate, period, value);
        var minimal_services_price = 0;
        var name = $(this).data('name');

        var minimal_services_price_input = $(`#wiaas_minimal_services_price_${name}`).first();
        if (minimal_services_price_input) {
            minimal_services_price = parseFloat(minimal_services_price_input.val()) || 0;
        }

        $(`#wiaas_minimal_recurrent_price_${name}`).text((minimal_services_price + principal_amount).toFixed(0));
        $(`#wiaas_minimal_recurrent_package_price_${name}`).text(principal_amount.toFixed(0));
    });

    $('#wiaas_package_pricing_editor').delegate('#wiaas_pricing_rules_commision', 'change', function(event) {
        event.preventDefault();

        var value = parseInt($(this).val());

        $('#wiaas_pricing_rules_commission_details').text('Commercial lead: ' + (100 - value) + ' %');
    });

    $('#wiaas_package_pricing_editor').delegate('#wiaas_pricing_rules_max_cost_margin', 'change', function(event) {
        event.preventDefault();

        var value = parseFloat($(this).val());
        var total = parseFloat($(this).data('total'));

        if (value > 0 && value < total) {
            $('#wiaas_pricing_rules_max_cost_margin_error').show();
        } else {
            $('#wiaas_pricing_rules_max_cost_margin_error').hide();
        }
    });

    /**
     * Copy of Excel's PMT function.
     * Credit: http://stackoverflow.com/questions/2094967/excel-pmt-function-in-js
     *
     * @param ratePerPeriod       The interest rate for the loan.
     * @param numberOfPayments    The total number of payments for the loan in months.
     * @param presentValue         The present value, or the total amount that a series of future payments is worth now;
     *                              Also known as the principal.
     * @param futureValue          The future value, or a cash balance you want to attain after the last payment is made.
     *                              If fv is omitted, it is assumed to be 0 (zero), that is, the future value of a loan is 0.
     * @param type                  Optional, defaults to 0. The number 0 (zero) or 1 and indicates when payments are due.
     *                              0 = At the end of period
     *                              1 = At the beginning of the period
     * @returns {number}
     */
    function wiaasCalculateFinancing(ratePerPeriod, numberOfPayments, presentValue, futureValue = 0, type = 0) {
        /*var q = 0;
        var c = 0;
        const monthlyRatePerPeriod = ratePerPeriod / 12;

        if (monthlyRatePerPeriod !== 0.0) {
            // Interest rate exists
            q = Math.pow(1 + monthlyRatePerPeriod, numberOfPayments);
            c = (monthlyRatePerPeriod * (futureValue + (q * presentValue))) / ((-1 + q) * (1 + monthlyRatePerPeriod * (type)));
            return c.toFixed(2);

        } else if (numberOfPayments !== 0.0) {
            // No interest rate, but number of payments exists
            return -(futureValue + presentValue) / numberOfPayments;
        }

        return 0;*/
        const rates = {
            24 : 4.282,
            30 : 3.451,
            36 : 2.896,
            42 : 2.500,
            48 : 2.223,
            54 : 2.025,
            60 : 1.834
        };

        const interest = rates[numberOfPayments] || 10;

        return presentValue * (interest / 100);
    }
});