{{-- Injected into resources/views/sale_pos/create.blade.php via DataController::get_pos_screen_view --}}
@php $vc = $view_data['clc_preselect'] ?? null; @endphp
@if($vc && !empty($vc['items']))
<script>
(function () {
    var drmPreselect = @json($vc);

    // Toast informing the user that vet items are being added
    function drmShowBanner() {
        if (!window.toastr) return;
        if (drmPreselect.items && drmPreselect.items.length) {
            toastr.info(
                'Pre-filling invoice from clinic appointment ' + (drmPreselect.ref_no || '#' + drmPreselect.appointment_id)
                + (drmPreselect.pet_name ? ' (' + drmPreselect.pet_name + ')' : '')
                + ' — ' + drmPreselect.items.length + ' item(s)'
            );
        }
        if (drmPreselect.skipped && drmPreselect.skipped.length) {
            toastr.warning(
                'Skipped (no linked product): <br>• ' + drmPreselect.skipped.join('<br>• ')
                + '<br><br>Link these to ERP products in <b>SOAP Options</b> to auto-bill them.',
                'Some items were not added', { timeOut: 8000, extendedTimeOut: 4000, escapeHtml: false }
            );
        }
    }

    // Apply per-item unit-price override (e.g. doctor consultation_fee) to the
    // most recent matching row after POS has added it.
    function drmApplyOverride(variation_id, price) {
        if (price == null) return;
        // The row containing this variation_id has input.row_variation_id with that value.
        var $row = $('#pos_table tbody tr').filter(function () {
            return String($(this).find('.row_variation_id').val()) === String(variation_id);
        }).last();
        if (!$row.length) return;
        var $price = $row.find('input.pos_unit_price');
        if (!$price.length) return;
        // Write the override and fire change so POS recalculates tax + line total
        $price.val(parseFloat(price).toFixed(2)).trigger('change');
    }

    // Add a single item by calling POS's own row-builder. Sequenced via delays
    // because pos_product_row triggers async XHRs to fetch product details.
    function drmAddSequentially(index) {
        if (index >= drmPreselect.items.length) return;
        var it = drmPreselect.items[index];
        try {
            if (typeof pos_product_row === 'function' && it.variation_id) {
                pos_product_row(it.variation_id, null, null, it.qty || 1);
            }
        } catch (e) {
            console.error('ClinicCore pre-fill failed for variation_id ' + it.variation_id, e);
        }
        // Wait for the XHR-rendered row before overriding price, then move on
        setTimeout(function () {
            drmApplyOverride(it.variation_id, it.price_override);
            drmAddSequentially(index + 1);
        }, 500);
    }

    $(function () {
        drmShowBanner();
        // Wait a moment so POS finishes its own initialisation (cash register, location, etc.)
        setTimeout(function () { drmAddSequentially(0); }, 800);
    });
})();
</script>
@endif
