{{--
  Shared MedSurgery back-office JS helpers. Included once per screen inside
  @section('javascript'). Provides a generic AJAX POST/PUT helper used by the
  transition / checklist / count / op-note forms on the case detail screen.
--}}
<script>
window.medsx = window.medsx || {};

// Post a form (or plain object) to a url; toasts the result and optionally reloads.
window.medsx.submit = function ($form, opts) {
    opts = opts || {};
    var method = ($form.attr('method') || 'POST').toUpperCase();
    var data = $form.serialize();
    var $btn = $form.find('button[type=submit]').prop('disabled', true);

    $.ajax({
        url: $form.attr('action'),
        method: method === 'GET' ? 'POST' : method,
        data: data,
        success: function (resp) {
            $btn.prop('disabled', false);
            if (resp && resp.success) {
                toastr.success(resp.msg);
                if (resp.note) { toastr.warning(resp.note); }
                if (opts.reload !== false) { window.location.reload(); }
            } else {
                toastr.error((resp && resp.msg) || 'Something went wrong.');
            }
        },
        error: function (xhr) {
            $btn.prop('disabled', false);
            var msg = (xhr.responseJSON && xhr.responseJSON.msg) || 'Something went wrong.';
            toastr.error(msg);
        }
    });
};

$(function () {
    // Any form tagged .medsx-form submits via AJAX and reloads on success.
    $(document).off('submit.medsx').on('submit.medsx', 'form.medsx-form', function (e) {
        e.preventDefault();
        var reload = $(this).data('reload') !== false;
        window.medsx.submit($(this), { reload: reload });
    });

    // Add/remove repeatable JSON rows (procedures, specimens, implants).
    $(document).off('click.medsxAdd').on('click.medsxAdd', '.medsx-row-add', function (e) {
        e.preventDefault();
        var tpl = $('#' + $(this).data('template')).html();
        var idx = Date.now();
        $($(this).data('target')).append(tpl.replace(/__IDX__/g, idx));
    });
    $(document).off('click.medsxDel').on('click.medsxDel', '.medsx-row-del', function (e) {
        e.preventDefault();
        $(this).closest('.medsx-row').remove();
    });
});
</script>
