{{--
  Shared MedNotify back-office CRUD behaviour (mirrors Modules/Vrc). Included
  once per index view inside @section('javascript'). Handles the generic
  modal-open / AJAX-submit / reset flow. DataTable init lives in each index view.

  Conventions:
    - Edit buttons:  class="mednotify-modal-btn"  data-href="..."
    - Forms in modal: class="mednotify-form"
    - Reset buttons:  class="mednotify-reset"  data-* form fields
    - Each DataTable registers itself: window.__medNotifyTables.push(table);
--}}
<script>
window.__medNotifyTables = window.__medNotifyTables || [];
window.medNotifyReloadTables = function () {
    window.__medNotifyTables.forEach(function (t) { try { t.ajax.reload(null, false); } catch (e) {} });
};

$(function () {
    $(document).off('click.mnModal').on('click.mnModal', '.mednotify-modal-btn', function (e) {
        e.preventDefault();
        var container = $('.mednotify_modal');
        $.get($(this).data('href'), function (html) {
            container.html(html).modal('show');
        }).fail(function () { toastr.error('Could not load the form.'); });
    });

    $(document).off('submit.mnForm').on('submit.mnForm', 'form.mednotify-form', function (e) {
        e.preventDefault();
        var $form = $(this);
        var $btn = $form.find('button[type=submit]').prop('disabled', true);
        $.ajax({
            url: $form.attr('action'),
            method: $form.attr('method') || 'POST',
            data: $form.serialize(),
            success: function (resp) {
                if (resp.success) {
                    toastr.success(resp.msg);
                    $form.closest('.modal').modal('hide');
                    window.medNotifyReloadTables();
                } else {
                    toastr.error(resp.msg || 'Something went wrong.');
                }
                $btn.prop('disabled', false);
            },
            error: function (xhr) {
                $btn.prop('disabled', false);
                if (xhr.status === 422 && xhr.responseJSON) {
                    var errs = xhr.responseJSON.errors || {};
                    Object.keys(errs).forEach(function (k) { toastr.error(errs[k][0]); });
                } else {
                    toastr.error('Something went wrong.');
                }
            }
        });
    });
});
</script>
