
$("#btnSaveMedication").on('click',function(e){
    var formData = $('#form-save-medication').serializeArray()
    let data_id = $('#data-id').val();
    let url = (data_id < 1 ? save_url : update_url);
    $.ajax({
        url: url,
        type: "POST",
        data: formData,
        dataType: "json",
        success: function (res) {
            handleMessage(res.success, res.message)
            if(res.success) setTimeout(function () {location.reload()}, messageDuration)
        }
    });
});

function delete_medication(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)
                }
            })

        }
    });
}

$('#modal-medication').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);
    $('#purchase_detail_body').empty();
    if(action === "new"){
        // Clear inputs
        modal.find('.modal-body input[name="uid"]').val(0);
        modal.find('.modal-body .clearable').val("");
        modal.find('.modal-title').html(modal_add_title);
        modal.find('.modal-body select[name="supplier_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: get_url,
            type:"POST",
            data:{
                "_token": csrf_token,
                uid: uid,
            },
            success:function(res){
                let data = res.data;

                modal.find('.modal-body input[name="grn_number"]').val(data.grn_number);
                modal.find('.modal-body input[name="po_number"]').val(data.po_number);
                modal.find('.modal-body input[name="received_date"]').val(data.received_date);
                modal.find('.modal-body #note').val(data.description);
                modal.find('.modal-body select[name="supplier"]').val(data.supplier_id).trigger('change');
                data.purchase_detail.map(item=>{
                    addPurchasedMedicalItem(item)
                })

                if(!res.success)handleMessage(res.success, res.message)
            }
        });
    }
})

function addMedicationItem(purchaseDetail = null) {
    var table = document.getElementById("purchase_detail_body");
    var table_len = table.rows.length;
    var id = table_len + 1

    var opt = "<?php foreach($medicineGroups as $item){ ?>";
    opt += "<option value='<?php echo $item->id ?>'><?php echo $item->name_en ?></option>";
    opt += "<?php } ?>";

    var medicalItemUnitOpt = "<?php foreach($medicineUnits as $item){ ?>";
    medicalItemUnitOpt += "<option value='<?php echo $item->id ?>'><?php echo $item->name_en ?></option>";
    medicalItemUnitOpt += "<?php } ?>";

    var row_ = "<tr id='row_" + id + "'>" +
        '<td class="p-2">' +
        '<select class="form-control form-control-sm clearable rounded-0" id="cate_' + id + '" name="category_id[]" onchange=getMedicalItemByGroupId(this.value,' + id + ') required>' +
        '<option value="">Chose</option>' + opt +
        '</select>' +
        '</td>' +
        '<td class="p-2">' +
        '<select name="drug_name[]" id="medicine_name' + id + '" class="form-control clearable form-control-sm rounded-0" required></select>' +
        '</td>' +
        '<td class="p-2">' +
        '    <input type="date" class="form-control-sm clearable rounded-0 form-control"  id="exp_' + id + '" data-date-format="dd-mm-yyyy"  data-language="en"  placeholder="dd-mm-yyyy" autocomplete="off" name="expiry_date[]" required>' +
        '</td>' +
        '<td class="p-2">' +
        '<select class="form-control form-control-sm clearable rounded-0" id="unit_' + id + '" name="medicine_unit_id[]" required>' +
        '<option value="">Chose</option>' + medicalItemUnitOpt +
        '</select>' +
        '</td>' +
        '<td style="margin-top:20px;" class="p-2">' +
        '    <button type="button" onclick="removePurchasedMedicalItem(' + id + ')" class="btn rounded-0 btn-md btn-danger"><i class="mdi mdi-trash-can text-white"></i></button>' +
        '</td>' +
        '</tr>';


    table.insertRow(table_len).outerHTML = row_;

    if (purchaseDetail != null) {
        $('#cate_' + id).val(purchaseDetail.medicine_group_id);
        $('#exp_' + id).val(purchaseDetail.expiry_date)
        $('#unit_' + id).val(purchaseDetail.medicine_unit_id)
        $('#qty_' + id).val(purchaseDetail.quantity)
        $('#pur_price_' + id).val(purchaseDetail.unit_price)
        $('#subtotal_' + id).val(purchaseDetail.unit_price * purchaseDetail.quantity)
        $('#medicine_name' + id).empty().append('<option selected value = "'+purchaseDetail.medicine_item_id+'">'+purchaseDetail.medicine_item.medicine.name+'</option>');
    }
    //$("#medicine_name"+id).select2();
}

function removePurchasedMedicalItem(id)
{
    $("#row_"+id).remove();
    calculatePurchasedPrice();
}

function calculatePurchasedPrice()
{
    var total=0;
    var price=[];
    var qty=[];
    var sum=0;

    $(".unit-price").each(function () {
        var pr=$(this).val();
        if(pr=="NaN" || pr==null || pr==""){
            pr=parseFloat("0");
        }
        price.push(pr);
    });

    $(".qty").each(function () {
        var q=$(this).val();
        if(q=="NaN" || q==null || q==""){
            q=parseFloat("0");
        }
        qty.push(q);
    });

    for(var i=0; i<price.length; i++)
    {
        var sum=(price[i]*qty[i]);
        total+=sum;
        $("input[name='amount[]']:eq("+i+")").val(sum.toFixed(2));
    }
    var amount= total
    //console.log('Riel', new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(total))
    $("#total_").html("$ "+amount.toFixed(2));
}


