
$("#btnSave").on('click',function(e){
    e.preventDefault();
    data_id = $('#data-id').val();
    let url = vaccination_base_url + (data_id < 1 ? '/save' : '/update');
    $.ajax({
        url: url,
        type:"POST",
        data :{
            "_token": csrf_token,
            uid : data_id,
            patient_id: $('#patient-id').val(),
            vaccinated_date: $('#vaccinated-date').val(),
            description: $('#description').val(),
            medicine_id: $('select[name="medicine_id"]').serializeArray(),
            step: $('input[name="step"]').serializeArray(),
            next_visit: $('input[name="next_visit"]').serializeArray(),
        },
        success:function(res){
            customErrorAlert(res)
            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: vaccination_base_url+'/delete',
                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: vaccination_base_url+'/restore',
                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-vaccination').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);

    $('#vaccination-detail tbody').empty();

    if(action === "new"){
        // Clear inputs
        addVaccinationRow()
        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="patient_id"]').val("").trigger("change");

    }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: vaccination_base_url+'/get',
            type:"POST",
            data:{
                "_token": csrf_token,
                uid: uid,
            },
            success:function(res){
                let data = res.data;
                modal.find('.modal-body input[name="description"]').val(data.description);
                modal.find('.modal-body input[name="vaccinated_date"]').val(data.vaccinated_date);
                modal.find('.modal-body select[name="patient_id"]').val(data.patient_id).trigger("change");

                data.vaccination_detail.map(item =>{
                    addVaccinationRow(item.medicine_id, item.step, item.next_visit_date)
                })

                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_en;
                $('#'+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_en;
                $('#'+patientElementId).append(patientOption);
            })
        }
    })
}

$("#searchPatientAddForm").click(function () {
    searchPatientToForm('patient-id')
});

function searchPatientToForm(patientElementId){
    Swal.fire({
        html:"<p style='text-align: left;'>Search the patient with their name, phone, Khmer ID, or patient ID</p>",
        input: "text",
        showCancelButton: !0,
        confirmButtonText: "<i class='fa fa-search mr-2'></i>Search",
        cancelButtonText: "Close",
        position: 'top',
        showLoaderOnConfirm: !1,
        confirmButtonColor: "#4fb51a",
        preConfirm: function (n) {
            return new Promise(function (t) {
                $.ajax({
                    url: patient_base_url + "/async",
                    method:'get',
                    dataType:'json',
                    data:{kword: n},
                    success:function(response)
                    {
                        if(response.data.length<1 || !response.success){
                            Swal.showValidationMessage('No patient found!')
                            Swal.enableButtons()
                        }
                        else {
                            t(response.data)
                        }
                    }
                })
            })
        },
        allowOutsideClick:!1,
    }).then(function (t) {
        if(!t.dismiss){
            $('#'+patientElementId).html('');
            t.value.map(item =>{
                var patientOption = document.createElement('OPTION');
                patientOption.setAttribute('value',item.id);
                patientOption.text = item.patient_uuid + ' - ' + item.name_en;
                $('#'+patientElementId).append(patientOption);
            })
        }
    })
}

