{{--
    Embedded part-numbers + device-models tables for the product ADD/EDIT form.
    Rendered via the get_product_screen_top_view module hook. Persisted by
    DataController::after_product_saved on product save. On edit, $product is
    inherited from the parent form scope and used to pre-fill.
--}}
@php
    use Modules\ProductCompat\Entities\PcPartNumber;
    use Modules\ProductCompat\Entities\PcDeviceCompat;
    use Modules\ProductCompat\Entities\PcCompatible;
    use Modules\ProductCompat\Entities\PcSearchQueue;
    use Modules\ProductCompat\Entities\Services\Settings as PcSettings;
    use Illuminate\Support\Facades\Schema;

    $pcProduct = (isset($product) && is_object($product) && ! empty($product->id)) ? $product : null;
    $pcParts = $pcProduct ? PcPartNumber::where('product_id', $pcProduct->id)->orderByDesc('is_primary')->get() : collect();
    $pcDevices = $pcProduct ? PcDeviceCompat::with('deviceModel')->where('product_id', $pcProduct->id)->get() : collect();
    $pcCompat = $pcProduct ? PcCompatible::with('compatibleProduct')->where('product_id', $pcProduct->id)->get() : collect();
    $pcTypeLabels = ['mpn' => 'MPN', 'oem' => 'OEM', 'model_code' => 'Model code', 'internal' => 'Internal', 'other' => 'Other'];

    // AI search queue: current entry (edit) / auto-queue notice (create).
    $pcQueueReady = Schema::hasTable('pc_search_queue');
    $pcQueueEntry = ($pcQueueReady && $pcProduct) ? PcSearchQueue::where('product_id', $pcProduct->id)->first() : null;
    $pcAutoQueue = $pcQueueReady && ! $pcProduct && PcSettings::bool('ai_auto_queue_on_create', true);
    $pcQueueBadge = ['queued' => 'bg-yellow', 'processing' => 'bg-aqua', 'done' => 'bg-green', 'failed' => 'bg-red', 'skipped' => 'bg-gray'];
@endphp

<div class="clearfix"></div>
<div class="col-sm-12">
    <div class="box box-solid box-info pc-form-block">
        <div class="box-header with-border">
            <h3 class="box-title"><i class="fa fa-microchip"></i> @lang('productcompat::lang.product_compatibility')</h3>
        </div>
        <div class="box-body">
            {{-- Ensures the core controller calls after_product_saved --}}
            <input type="hidden" name="has_module_data" value="1">

            @include('productcompat::partials.type_legend')

            <div class="row">
                {{-- Part numbers --}}
                <div class="col-sm-6">
                    <label>@lang('productcompat::lang.part_numbers')</label>
                    <div id="pc-f-parts">
                        @foreach($pcParts as $i => $pn)
                            <div class="row pc-f-row" style="margin-bottom:6px;">
                                <div class="col-xs-5"><input type="text" class="form-control input-sm" name="pc_part_numbers[{{ $i }}][part_number]" value="{{ $pn->part_number }}" placeholder="@lang('productcompat::lang.part_number')"></div>
                                <div class="col-xs-3">
                                    <select class="form-control input-sm" name="pc_part_numbers[{{ $i }}][type]">
                                        @foreach($pcTypeLabels as $k => $label)<option value="{{ $k }}" @if($pn->type==$k) selected @endif>{{ $label }}</option>@endforeach
                                    </select>
                                </div>
                                <div class="col-xs-3"><label class="checkbox-inline"><input type="checkbox" name="pc_part_numbers[{{ $i }}][is_primary]" value="1" @if($pn->is_primary) checked @endif> @lang('productcompat::lang.primary')</label></div>
                                <div class="col-xs-1"><button type="button" class="btn btn-xs btn-danger pc-f-remove">&times;</button></div>
                            </div>
                        @endforeach
                    </div>
                    <button type="button" class="btn btn-xs btn-default" id="pc-f-add-part"><i class="fa fa-plus"></i> @lang('productcompat::lang.add')</button>
                </div>

                {{-- Device models --}}
                <div class="col-sm-6">
                    <label>@lang('productcompat::lang.device_models')</label>
                    <div id="pc-f-devices">
                        @foreach($pcDevices as $i => $dc)
                            <div class="row pc-f-row" style="margin-bottom:6px;">
                                <div class="col-xs-3"><input type="text" class="form-control input-sm" name="pc_device_models[{{ $i }}][brand]" value="{{ optional($dc->deviceModel)->brand }}" placeholder="@lang('productcompat::lang.brand')"></div>
                                <div class="col-xs-3"><input type="text" class="form-control input-sm" name="pc_device_models[{{ $i }}][series]" value="{{ optional($dc->deviceModel)->series }}" placeholder="@lang('productcompat::lang.series')"></div>
                                <div class="col-xs-5"><input type="text" class="form-control input-sm" name="pc_device_models[{{ $i }}][model]" value="{{ optional($dc->deviceModel)->model }}" placeholder="@lang('productcompat::lang.model')"></div>
                                <div class="col-xs-1"><button type="button" class="btn btn-xs btn-danger pc-f-remove">&times;</button></div>
                            </div>
                        @endforeach
                    </div>
                    <button type="button" class="btn btn-xs btn-default" id="pc-f-add-device"><i class="fa fa-plus"></i> @lang('productcompat::lang.add')</button>
                </div>
            </div>

            {{-- Compatible products --}}
            <div class="row" style="margin-top:10px;">
                <div class="col-sm-12">
                    <label>@lang('productcompat::lang.compatible_products')</label>
                    <select class="form-control pc-f-compatibles" name="pc_compatible_products[]" multiple style="width:100%;">
                        @foreach($pcCompat as $c)
                            @if($c->compatibleProduct)
                                <option value="{{ $c->compatibleProduct->id }}" selected>{{ $c->compatibleProduct->sku }} — {{ $c->compatibleProduct->name }}</option>
                            @endif
                        @endforeach
                    </select>
                </div>
            </div>

            {{-- AI search queue: edit asks, create auto-queues silently --}}
            @if($pcQueueReady && $pcProduct)
                <div class="row" style="margin-top:10px;">
                    <div class="col-sm-12">
                        <label class="checkbox-inline">
                            <input type="checkbox" name="pc_queue_recheck" value="1">
                            @lang('productcompat::lang.queue_recheck_label')
                        </label>
                        @if($pcQueueEntry)
                            <span class="label {{ $pcQueueBadge[$pcQueueEntry->status] ?? 'bg-gray' }}" style="margin-left:8px;">
                                @lang('productcompat::lang.queue_current_status'): @lang('productcompat::lang.status_' . $pcQueueEntry->status)
                            </span>
                        @endif
                    </div>
                </div>
            @elseif($pcAutoQueue)
                <div class="row" style="margin-top:10px;">
                    <div class="col-sm-12">
                        <p class="text-muted" style="margin:0;"><i class="fa fa-info-circle"></i> @lang('productcompat::lang.queue_auto_note')</p>
                    </div>
                </div>
            @endif
        </div>
    </div>
</div>
<div class="clearfix"></div>

<template id="pc-f-part-tpl">
    <div class="row pc-f-row" style="margin-bottom:6px;">
        <div class="col-xs-5"><input type="text" class="form-control input-sm" name="pc_part_numbers[__I__][part_number]" placeholder="@lang('productcompat::lang.part_number')"></div>
        <div class="col-xs-3">
            <select class="form-control input-sm" name="pc_part_numbers[__I__][type]">
                @foreach($pcTypeLabels as $k => $label)<option value="{{ $k }}">{{ $label }}</option>@endforeach
            </select>
        </div>
        <div class="col-xs-3"><label class="checkbox-inline"><input type="checkbox" name="pc_part_numbers[__I__][is_primary]" value="1"> @lang('productcompat::lang.primary')</label></div>
        <div class="col-xs-1"><button type="button" class="btn btn-xs btn-danger pc-f-remove">&times;</button></div>
    </div>
</template>
<template id="pc-f-device-tpl">
    <div class="row pc-f-row" style="margin-bottom:6px;">
        <div class="col-xs-3"><input type="text" class="form-control input-sm" name="pc_device_models[__I__][brand]" placeholder="@lang('productcompat::lang.brand')"></div>
        <div class="col-xs-3"><input type="text" class="form-control input-sm" name="pc_device_models[__I__][series]" placeholder="@lang('productcompat::lang.series')"></div>
        <div class="col-xs-5"><input type="text" class="form-control input-sm" name="pc_device_models[__I__][model]" placeholder="@lang('productcompat::lang.model')"></div>
        <div class="col-xs-1"><button type="button" class="btn btn-xs btn-danger pc-f-remove">&times;</button></div>
    </div>
</template>

<script>
$(function () {
    var pIdx = {{ $pcParts->count() }}, dIdx = {{ $pcDevices->count() }};
    $('#pc-f-add-part').on('click', function () {
        $('#pc-f-parts').append($('#pc-f-part-tpl').html().replace(/__I__/g, pIdx++));
    });
    $('#pc-f-add-device').on('click', function () {
        $('#pc-f-devices').append($('#pc-f-device-tpl').html().replace(/__I__/g, dIdx++));
    });
    $(document).on('click', '.pc-f-remove', function () { $(this).closest('.pc-f-row').remove(); });

    if ($.fn.select2) {
        $('.pc-f-compatibles').select2({
            ajax: {
                url: '{{ route('products.search') }}', type: 'POST', dataType: 'json', delay: 250,
                headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
                data: function (params) { return { search: params.term, page: params.page }; },
                processResults: function (data) { return { results: data.results.map(function (p) { return { id: p.id, text: p.sku + ' — ' + p.name }; }) }; },
                cache: true
            },
            minimumInputLength: 1,
            placeholder: 'Search product by SKU or name',
            width: '100%'
        });
    }
});
</script>
