{{--
    NX600 Lab — pet profile / appointment panel (shell).
    Included by VetClinic pet & appointment screens inside a tab pane.
    Self-contained: receives only $pet. The worklist/results body is in
    _pet_lab_body.blade.php and is refreshed over AJAX (no page reload).
--}}
@php
    $nxBusinessId = session('user.business_id');
    $nxSync       = \Modules\NX600Lab\Entities\Services\VetClinicSyncService::syncEnabled($nxBusinessId);
    $nxCanManage  = auth()->user()->can('nx600_lab.manage_worklist');
@endphp

<div id="nx-lab-panel">

    <div class="row">
        <div class="col-md-12">
            <h4 style="margin-top:0;display:flex;align-items:center;gap:10px;">
                <span><i class="fas fa-vials"></i> NX600 Laboratory</span>
                @if(!$nxSync)
                    <span class="label label-default">Sync disabled</span>
                @else
                    <button type="button" id="nx-lab-refresh" class="btn btn-xs btn-default"
                            title="Refresh lab data" style="margin-left:auto;">
                        <i class="fas fa-sync-alt"></i> Refresh
                    </button>
                @endif
            </h4>
        </div>
    </div>

    @if(!$nxSync)
        <div class="alert alert-info">
            VetClinic ↔ NX600 Lab sync is currently turned off. Enable it under
            <strong>NX600 Lab → Settings → VetClinic Integration</strong> to raise lab orders
            for this pet and see results here.
        </div>
    @else

        <div id="nx-lab-msg" class="alert" style="display:none;"></div>

        @if($nxCanManage)
        <div class="row">
            <div class="col-md-12">
                <div class="box box-solid box-primary">
                    <div class="box-header"><h3 class="box-title">Raise a Lab Order</h3></div>
                    <div class="box-body">
                        <form id="nx-lab-order-form" method="POST" action="{{ route('nx.bridge.pet-order') }}" class="form-inline">
                            @csrf
                            <input type="hidden" name="vc_pet_id" value="{{ $pet->id }}">
                            <div class="form-group">
                                <label>Sample No</label>
                                <input type="text" name="sample_no" maxlength="13" class="form-control"
                                       placeholder="Auto-generate">
                            </div>
                            <div class="form-group" style="margin-left:8px;">
                                <label>Tests</label>
                                <input type="text" name="test_names" class="form-control" style="width:280px;"
                                       placeholder="GLU-P, BUN-P, CRE-P (blank = device default)">
                            </div>
                            <button type="submit" class="btn btn-primary" style="margin-left:8px;">
                                <i class="fa fa-plus"></i> Create Order
                            </button>
                        </form>
                        <p class="text-muted" style="margin-top:8px;margin-bottom:0;">
                            The order is queued for the analyzer using {{ $pet->petname }}'s species, sex and age.
                        </p>
                    </div>
                </div>
            </div>
        </div>
        @endif

        <div id="nx-lab-panel-body">
            @include('nx600Lab::bridge._pet_lab_body', ['pet' => $pet])
        </div>

    @endif

</div>

@if($nxSync)
<script>
(function () {
    // Dependency-free: this runs inline mid-page, before the ERP loads jQuery.
    var panel = document.getElementById('nx-lab-panel');
    if (!panel || panel.dataset.nxBound) { return; }
    panel.dataset.nxBound = '1';

    var refreshUrl = @json(route('nx.bridge.pet-panel', $pet->id));
    var msgBox     = document.getElementById('nx-lab-msg');
    var bodyBox    = document.getElementById('nx-lab-panel-body');
    var refreshBtn = document.getElementById('nx-lab-refresh');
    var orderForm  = document.getElementById('nx-lab-order-form');

    function showMsg(type, text) {
        if (!msgBox) { return; }
        msgBox.className = 'alert alert-' + type;
        msgBox.textContent = text;
        msgBox.style.display = '';
    }

    function refreshBody(done) {
        var icon = refreshBtn ? refreshBtn.querySelector('i') : null;
        if (icon) { icon.classList.add('fa-spin'); }
        fetch(refreshUrl, {
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            credentials: 'same-origin'
        })
        .then(function (r) { return r.text(); })
        .then(function (html) { if (bodyBox) { bodyBox.innerHTML = html; } })
        .catch(function () { showMsg('danger', 'Could not refresh lab data.'); })
        .then(function () {
            if (icon) { icon.classList.remove('fa-spin'); }
            if (typeof done === 'function') { done(); }
        });
    }

    if (refreshBtn) {
        refreshBtn.addEventListener('click', function (e) {
            e.preventDefault();
            refreshBody();
        });
    }

    if (orderForm) {
        orderForm.addEventListener('submit', function (e) {
            e.preventDefault();
            var submitBtn = orderForm.querySelector('button[type=submit]');
            if (submitBtn) { submitBtn.disabled = true; }

            fetch(orderForm.getAttribute('action'), {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json' },
                credentials: 'same-origin',
                body: new FormData(orderForm)
            })
            .then(function (r) {
                return r.json().then(function (data) {
                    return { ok: r.ok, status: r.status, data: data };
                });
            })
            .then(function (res) {
                if (res.ok && res.data && res.data.success) {
                    showMsg('success', res.data.msg || 'Lab order created.');
                    var sn = orderForm.querySelector('input[name=sample_no]');
                    var tn = orderForm.querySelector('input[name=test_names]');
                    if (sn) { sn.value = ''; }
                    if (tn) { tn.value = ''; }
                    refreshBody();
                } else {
                    var m = (res.data && res.data.msg) ? res.data.msg : 'Could not create the order.';
                    if (res.status === 422 && res.data && res.data.errors) {
                        var firstKey = Object.keys(res.data.errors)[0];
                        m = res.data.errors[firstKey][0];
                    }
                    showMsg('danger', m);
                }
            })
            .catch(function () { showMsg('danger', 'Could not create the order.'); })
            .then(function () {
                if (submitBtn) { submitBtn.disabled = false; }
            });
        });
    }
})();
</script>
@endif
