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

  Conventions:
    - Modal-open buttons: class="medward-modal-btn"  data-href="..."
    - Forms in the modal:  class="medward-form"
    - Delete buttons:      class="medward-delete-btn" data-href="..."  (DELETE)
    - Each DataTable registers itself: window.__medWardTables.push(table);
--}}
<script>
window.__medWardTables = window.__medWardTables || [];
window.medWardReloadTables = function () {
    window.__medWardTables.forEach(function (t) { try { t.ajax.reload(null, false); } catch (e) {} });
};

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

    // Submit a modal / inline form via AJAX.
    $(document).off('submit.mwForm').on('submit.mwForm', 'form.medward-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');
                    if (resp.redirect) { window.location = resp.redirect; return; }
                    window.medWardReloadTables();
                    if (window.medWardAfterSave) { window.medWardAfterSave(resp); }
                } 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 msg = xhr.responseJSON.msg;
                    if (msg) { toastr.error(msg); }
                    var errs = xhr.responseJSON.errors || {};
                    Object.keys(errs).forEach(function (k) { toastr.error(errs[k][0]); });
                } else {
                    toastr.error('Something went wrong.');
                }
            }
        });
    });

    // Delete a row.
    $(document).off('click.mwDel').on('click.mwDel', '.medward-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.medWardReloadTables(); }
                else { toastr.error(resp.msg || 'Something went wrong.'); }
            },
            error: function () { toastr.error('Something went wrong.'); }
        });
    });
});
</script>
