'use strict';
let input = document.querySelector("#phone");
let iti = intlTelInput(input, {
    nationalMode: false,
    autoHideDialCode: true,
    separateDialCode: true,
    formatOnDisplay: true,
});

// get number in hidden field on input value change
let phoneNumber = $('#phone').change(function () {
    $('#hidden_phone').val('');
    $('#hidden_phone').val(iti.getNumber())
})

// get number in hidden field
input.addEventListener("countrychange", function () {
    $('#hidden_phone').val('');
    $('#hidden_phone').val(iti.getNumber())
});

// set number
iti.setNumber($('#hidden_phone').val());

// Disable hidden field on submit if empty
$("form").submit(function (e) {
    if ($('#phone').val() === '') {
        $('#hidden_phone').val('');
        $('#hidden_phone').attr('disabled', true)
    }
});

$(document).ready(function () {
    $("#price").keydown(function (e) {
        let oldvalue = $(this).val();
        let field = this;
        setTimeout(function () {
            if (field.value.indexOf('$') !== 0) {
                $(field).val(oldvalue);
            }
        }, 1);
    });
});

let emailInput = $("#email");
let introducedByInput = $("#introduced_by");
let email = emailInput.val();

$(document).ready(function () {
    // send ajax with email
    let formData = {
        'email': email
    };
    if (email !== '') {
        $.ajax({
                type: "POST",
                dataType: 'json',
                url: 'check-sponsor',
                data: formData,
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            })
            // get response and show text in "Introduced By" and "Introduced Name" input
            .then((response) => {
                let sponsorData = {
                    status: response.status,
                    email: response.email,
                    introduced_by: response.username,
                };

                // check if email is undefined
                if (sponsorData.email === undefined) {
                    introducedByInput.val("");
                    introducedByInput.prop('disabled', false);
                    $('#allHidden').empty();
                } else {
                    introducedByInput.val(sponsorData.introduced_by);
                    introducedByInput.prop('disabled', true);
                    $('#allHidden').html('<input type="hidden" name="introduced_by" value="' + introducedByInput.val() + '">');
                }
            });
    }
});

// if email changed
emailInput.on('change', function () {
    email = emailInput.val();
    if (email === "") {
        introducedByInput.val("");
        introducedByInput.prop('disabled', false);
    }

    // send ajax with email
    let formData = {
        'email': email,
        'current_url': window.location.pathname
    };
    $.ajax({
            type: "POST",
            dataType: 'json',
            url: 'check-sponsor',
            data: formData,
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        })
        // get response and show text in "Introduced By" and "Introduced Name" input
        .then((response) => {
            if (response.status) {
                if (response.isEmailExist) {
                    Swal.fire({
                        text: response.msg,
                        icon: 'warning',
                        showCancelButton: false,
                        confirmButtonColor: '#3A31A1',
                        cancelButtonColor: '#b61853',
                        confirmButtonText: 'Login',
                        allowOutsideClick: false
                    }).then((result) => {
                        if (result.isConfirmed) {
                            window.location = '/login';
                        }
                    });
                }
            }
            let sponsorData = {
                status: response.status,
                email: response.email,
                introduced_by: response.username,
            };

            // check if email is undefined
            if (sponsorData.email === undefined) {
                introducedByInput.val("");
                introducedByInput.prop('disabled', false);
                $('#allHidden').empty();
            } else {
                introducedByInput.val(sponsorData.introduced_by);
                introducedByInput.prop('disabled', true);
                $('#allHidden').html('<input type="hidden" name="introduced_by" value="' + introducedByInput.val() + '">');
            }
        })
});

// if username changed
introducedByInput.on('change', function () {
    let introducedBy = introducedByInput.val();
    // send ajax with email
    let formData = {
        'introduced_by': introducedBy
    };

    $.ajax({
        type: "POST",
        dataType: 'json',
        url: 'check-sponsor',
        data: formData,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function (response) {
            let name = introducedByInput.attr("name");
            if (response.status === 'active') {
                let sponsorData = {
                    status: response.status,
                    email: response.email,
                    introduced_by: response.username,
                };

                // check if username is undefined
                introducedByInput.val(sponsorData.introduced_by);
                introducedByInput.removeClass('is-invalid');
                $(".custom-error-" + name).remove();
            }
        },
        error: function (response) {
            if (response.status == 500) {
                swalMsg('Something went wrong.', 'error')
                return;
            }
            let name = introducedByInput.attr("name");
            let error = response.responseJSON;
            $('.custom-error').remove();
            if (error !== undefined) {
                introducedByInput.val("");
                introducedByInput.addClass('is-invalid');
                $("#custom-error-" + name).show();
                $('#custom-errors-' + name).append('<span class="custom-error custom-error-' + name + '"><strong>' + error.message + '</strong></span>');
            }
        }
    });
});

// On Load
$(document).ready(function () {
    // prevent zeros
    $("input[type=number]").keyup(function () {
        let value = $(this).val();
        value = value.replace(/^(0*)/, "");
        $(this).val(value);
    });

    // add comma after 3 digits
    let priceAttr = $("#price");
    let price = priceAttr.val();
    priceAttr.val(numberWithCommas(price));

    let amountAttr = $("#amount");
    let amount = amountAttr.val();
    amountAttr.val(numberWithCommas(amount));
});
