{{--
  Shared MedPortal back-office CRUD behaviour (mirrors Modules/MedBilling).
  Included once per index view inside @section('javascript'). Handles the generic
  modal-open / AJAX-submit / delete flow.

  Conventions:
    - Modal-open buttons: class="mportal-modal-btn"  data-href="..."
    - Forms in the modal:  class="mportal-form"
    - Delete buttons:      class="mportal-delete-btn" data-href="..."  (DELETE)
--}}
<script>
window.mportalReload = function () { location.reload(); };

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

    // Submit a modal form via AJAX.
    $(document).off('submit.mpForm').on('submit.mpForm', 'form.mportal-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') && $form.attr('method').toUpperCase() !== 'GET' ? $form.attr('method') : 'POST',
            data: $form.serialize(),
            success: function (resp) {
                if (resp.success) {
                    toastr.success(resp.msg);
                    if (resp.note) { toastr.warning(resp.note); }
                    $form.closest('.modal').modal('hide');
                    window.mportalReload();
                } 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) || {};
                    if (xhr.responseJSON.message) { toastr.error(xhr.responseJSON.message); }
                    Object.keys(errs).forEach(function (k) { toastr.error(errs[k][0]); });
                } else {
                    toastr.error('Something went wrong.');
                }
            }
        });
    });

    // Delete a row.
    $(document).off('click.mpDel').on('click.mpDel', '.mportal-delete-btn', function (e) {
        e.preventDefault();
        if (!confirm('{{ __('messages.sure') }}')) { return; }
        $.ajax({
            url: $(this).data('href'),
            method: 'DELETE',
            data: { _token: '{{ csrf_token() }}' },
            success: function (resp) {
                if (resp.success) { toastr.success(resp.msg); window.mportalReload(); }
                else { toastr.error(resp.msg || 'Something went wrong.'); }
            },
            error: function () { toastr.error('Something went wrong.'); }
        });
    });
});
</script>
