window.addEventListener('viewCouponType', event => {
    $("#add_coupon").modal('show');
    event.detail.map((val) => {
      $("#type_id").append(`<option value=${val.id}>${val.type}</option>`)
    })
})
window.addEventListener('assignToUser', event => {
    $("#assign_user").modal('show');
    $('#assign_user #users').select2({
        dropdownParent: $('#assign_user'),
        placeholder : "Select users"
    });
    let { id, name, assign_customer } = event.detail[1]
    $("#coupon_id").val(id)
    $("#assign_user #coupon_name").val(name).attr('disabled', 'disabled')
    let userIds = []
    assign_customer.map((val) => {
        userIds.push(val.id)
    })
    let selected;
    event.detail[0].map((val) => {
        if (userIds.includes(val.id)) {
            selected = 'selected'
        } else {
            selected = ''
        }
        $('#assign_user #users').append(`<option value=${val.id} ${selected}>${val.name}</option>`)
    })
})
$(document).ready(function () {
    $("#expires_at").datepicker('setStartDate', new Date()).datepicker('setDate', new Date())
    $(document).on('change', '#type_id', function () {
        if ($(this).val() == 1) {
            $("#amount").removeClass('d-none')
            $("#percentage").addClass('d-none')
        } else {
            $("#percentage").removeClass('d-none')
            $("#amount").addClass('d-none')
        }
    })
    $(document).on('click', '.addCoupon', function (e) {
        e.preventDefault()
        let formData = $("#add_coupon_form").serializeArray()
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            },
            url : addCouponUrl,
            method : 'post',
            data : formData,
            success : function (data) {
                ajaxSuccessFunc("#add_coupon", data)
            },
            error : function (error) {
                ajaxErrorFunc('#add_coupon', error)
            }
        })
    })
    $(document).on('click', '.assign_coupon', function () {
        let userIds = []
        let data = $('#assign_user #users').select2('data')
        data.map((val) => {
            userIds.push(val.id) 
        })
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('input[name="_token"]').val()
            },
            url : assignCouponUrl,
            method : 'post',
            data : {
                'user_ids' : userIds,
                'coupon_id' : $("#coupon_id").val()
            },
            success : function (data) {
                ajaxSuccessFunc("#assign_user", data)
            },
            error : function (error) {
                ajaxErrorFunc('#assign_user', error)
            }
        })
    })
})