{{--
  Shared MedOrganization back-office CRUD behaviour (mirrors Modules/Vrc).
  Included once per index view inside @section('javascript'). DataTable init
  lives in each index view (columns differ); this handles the generic
  modal-open / AJAX-submit / POST-action / delete flow.

  Conventions:
    - Add/Edit buttons:  class="medorg-modal-btn"  data-href="..."  [data-container=".medorg_modal"]
    - Forms in modal:    class="medorg-form"   (Form::open includes _token / _method)
    - POST buttons:      class="medorg-post-btn"  data-href="..."  (toggle / set-primary)
    - Delete buttons:    class="medorg-delete"  data-href="..."  [data-confirm="..."]
    - Each DataTable registers itself: window.__medorgTables.push(table);
--}}
<script>
window.__medorgTables = window.__medorgTables || [];
window.medorgReloadTables = function () {
    window.__medorgTables.forEach(function (t) { try { t.ajax.reload(null, false); } catch (e) {} });
};

$(function () {
    $(document).off('click.medorgModal').on('click.medorgModal', '.medorg-modal-btn', function (e) {
        e.preventDefault();
        var container = $($(this).data('container') || '.medorg_modal');
        $.get($(this).data('href'), function (html) {
            container.html(html).modal('show');
            container.find('.medorg-select2').each(function () {
                try { $(this).select2({ dropdownParent: container, width: '100%' }); } catch (e) {}
            });
        }).fail(function () { toastr.error('Could not load the form.'); });
    });

    $(document).off('submit.medorgForm').on('submit.medorgForm', 'form.medorg-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.medorgReloadTables();
                } 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.');
                }
            }
        });
    });

    // Simple POST actions (activate/deactivate rule, make-primary, ...)
    $(document).off('click.medorgPost').on('click.medorgPost', '.medorg-post-btn', function (e) {
        e.preventDefault();
        $.post($(this).data('href'), { _token: $('meta[name=csrf-token]').attr('content') }, function (resp) {
            if (resp.success) { toastr.success(resp.msg); window.medorgReloadTables(); }
            else { toastr.error(resp.msg || 'Something went wrong.'); }
        }).fail(function () { toastr.error('Something went wrong.'); });
    });

    $(document).off('click.medorgDelete').on('click.medorgDelete', '.medorg-delete', function (e) {
        e.preventDefault();
        var href = $(this).data('href');
        var msg = $(this).data('confirm') || 'Are you sure you want to delete this?';
        if (!window.confirm(msg)) return;
        $.ajax({
            url: href,
            method: 'DELETE',
            data: { _token: $('meta[name=csrf-token]').attr('content') },
            success: function (resp) {
                if (resp.success) { toastr.success(resp.msg); window.medorgReloadTables(); }
                else { toastr.error(resp.msg || 'Something went wrong.'); }
            },
            error: function () { toastr.error('Something went wrong.'); }
        });
    });
});
</script>
