
$("#btnSave").on('click',function(e){
    e.preventDefault();
    data_id = $('#data-id').val();
    let url = (data_id < 1 ? save_url : update_url);
    $.ajax({
        url: url,
        type:"POST",
        data :{
            "_token": csrf_token,
            uid : data_id,
            code: $('#medicine-code').val(),
            medicine_id: $('#medicine-id').val(),
            medicine_group_id: $('#medicine-group-id').val(),
            unit_price: $('#unit-price').val(),
            sale_price: $('#sale-price').val(),
            dosage: $('#dosage').val(),
            is_vaccination: $("input[name='is_vaccination']:checked").attr('data-id'),
        },
        success:function(res){
            handleMessage(res.success, res.message)
            if(res.success) setTimeout(function () {location.reload()}, messageDuration)
        }
    });
});

function delete_data(uid){
    Swal.fire({
        text: confirm_delete_record,
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass:'danger',
        confirmButtonText: confirm_ok_delete,
        cancelButtonText: confirm_cancel
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: delete_url,
                method:'POST',
                data:{
                    "_token": csrf_token,
                    uid : uid,
                },
                success:function(res){
                    handleMessage(res.success, res.message)
                    if(res.success) setTimeout(function () {location.reload()}, messageDuration)
                }
            })

        }
    });
}

function restore_data(uid){
    Swal.fire({
        text: confirm_restore_record,
        icon: 'question',
        showCancelButton: true,
        cancelButtonClass:'danger',
        confirmButtonText: confirm_ok_restore,
        cancelButtonText: confirm_cancel_restore,
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: restore_url,
                method:'POST',
                data:{
                    "_token": csrf_token,
                    uid : uid,
                },
                success:function(res){
                    handleMessage(res.success, res.message)
                    if(res.success) setTimeout(function () {location.reload()}, messageDuration)
                }
            })

        }
    });
}


$('#modal-medicine-item').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget) // Button that triggered the modal
    var action = button.data('action') // Extract info from data-* attributes
    var modal = $(this);
    if(action === "new"){
        // Clear inputs
        modal.find('.modal-body input[name="uid"]').val(0);
        modal.find('.modal-body input').val("");
        modal.find('.modal-title').html(modal_add_title);

        modal.find('.modal-body select[name="medicine_id"]').val("").trigger("change");
        modal.find('.modal-body select[name="medicine_group_id"]').val("").trigger("change");

        $('#is-vaccination').prop("checked", false)
    }else if(action === "edit"){
        uid = button.data('uid');
        modal.find('.modal-body input[name="uid"]').val(uid);
        modal.find('.modal-title').html(modal_edit_title);
        $.ajax({
            url: get_url,
            type:"POST",
            data:{
                "_token": csrf_token,
                uid: uid,
            },
            success:function(res){
                let data = res.data;
                modal.find('.modal-body input[name="unit_price"]').val(data.unit_price);
                modal.find('.modal-body input[name="dosage"]').val(data.dosage);
                modal.find('.modal-body input[name="sale_price"]').val(data.sale_price);
                modal.find('.modal-body input[name="medicine_code"]').val(data.code);

                modal.find('.modal-body select[name="medicine_id"]').val(data.medicine_id).trigger('change');
                modal.find('.modal-body select[name="medicine_group_id"]').val(data.medicine_group_id).trigger('change');

                if(data.is_vaccination == 1){
                    $('#is-vaccination').prop("checked", true)
                } else{
                    $('#is-vaccination').prop("checked", false)
                }
                if(!res.success) handleMessage(res.success, res.message)
            }
        });
    }
})

function addNewMedicine(patientElementId){
    Swal.fire({
        html:"<p style='float: left;'>Medicine Name</p>",
        input: "text",
        showCancelButton: !0,
        confirmButtonText: "<i class='fa fa-save mr-2'></i>Save",
        cancelButtonText: "Cancel",
        showLoaderOnConfirm: !1,
        confirmButtonColor: "#844fc1",
        cancelButtonColor: "#cbcbcb",
        preConfirm: function (n) {
            return new Promise(function (t) {
                $.ajax({
                    url: medicine_base_url + '/save',
                    method:'post',
                    dataType:'json',
                    data:{
                        "_token": csrf_token,
                        name_en: n
                    },
                    success:function(r)
                    {
                        if(r.success !== true){
                            Swal.showValidationMessage('Failed while saving medicine name. ' + r.errors)
                            Swal.enableButtons()
                        }
                        else t(r.data)
                    }
                })
            })
        },
        allowOutsideClick:!1,
    }).then(function (t) {
        if(!t.dismiss){
            t.value.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                patientOption.setAttribute('selected','selected');
                patientOption.text = item.name;
                $('#'+patientElementId).append(patientOption);
            })
        }
    })
}

function editMedicineName(testId,oldName, patientElementId){
    Swal.fire({
        html:"<p style='float: left;'>Medicine Name</p>",
        input: "text",
        inputValue: oldName,
        showCancelButton: !0,
        confirmButtonText: "<i class='fa fa-save mr-2'></i>Save",
        cancelButtonText: "Cancel",
        showLoaderOnConfirm: !1,
        confirmButtonColor: "#844fc1",
        cancelButtonColor: "#cbcbcb",
        preConfirm: function (n) {
            return new Promise(function (t) {
                $.ajax({
                    url: medicine_base_url + '/update',
                    method:'post',
                    dataType:'json',
                    data:{
                        "_token": csrf_token,
                        uid: testId,
                        name_en: n
                    },
                    success:function(r)
                    {
                        if(r.success !== true){
                            Swal.showValidationMessage('Failed while saving medicine name. ' + r.errors)
                            Swal.enableButtons()
                        }
                        else t(r.data)
                    }
                })
            })
        },
        allowOutsideClick:!1,
    }).then(function (t) {
        if(!t.dismiss){
            t.value.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                patientOption.setAttribute('selected','selected');
                patientOption.text = item.name;
                $('#'+patientElementId).append(patientOption);
            })
        }
    })
}
