@extends('layouts.app')
@section('title', __('productcompat::lang.editor'))

@section('css')
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css">
<style>
    .pc-row { margin-bottom: 8px; }
    .pc-legacy { background:#fafafa; border:1px dashed #ddd; padding:8px 12px; border-radius:4px; }
</style>
@endsection

@section('content')
@php $typeLabels = ['mpn'=>'MPN','oem'=>'OEM','model_code'=>'Model code','internal'=>'Internal','other'=>'Other']; @endphp
<section class="content-header">
    <h1>@lang('productcompat::lang.product_compatibility')
        <small>{{ $product->sku }} — {{ $product->name }}</small>
    </h1>
</section>

<section class="content">
    @includeIf('productcompat::partials.status')

    {{-- Legacy custom fields (reference) + checked / cleanup controls --}}
    <div class="row">
        <div class="col-md-12">
            <div class="box box-default">
                <div class="box-header with-border">
                    <h3 class="box-title">Legacy custom fields (reference)</h3>
                    <div class="box-tools pull-right">
                        <form method="POST" action="{{ action('\Modules\ProductCompat\Http\Controllers\ProductCompatController@enrich') }}" style="display:inline;"
                              onsubmit="return confirm('Fetch part numbers / compatibility from configured sources? Results land as needs-review.');">
                            @csrf
                            <input type="hidden" name="product_id" value="{{ $product->id }}">
                            <button class="btn btn-xs btn-info" title="Fetch from official/trusted/API sources"><i class="fa fa-cloud-download-alt"></i> Enrich now</button>
                        </form>
                        @if(empty($status) || empty($status->checked_at))
                            <form method="POST" action="{{ action('\Modules\ProductCompat\Http\Controllers\ReviewController@markChecked') }}" style="display:inline;">
                                @csrf
                                <input type="hidden" name="product_id" value="{{ $product->id }}">
                                <button class="btn btn-xs btn-success">@lang('productcompat::lang.mark_checked')</button>
                            </form>
                        @else
                            <span class="label label-success"><i class="fa fa-check"></i> @lang('productcompat::lang.checked')</span>
                        @endif

                        @if(!empty($status) && $status->checked_at && empty($status->custom_fields_cleared_at))
                            <form method="POST" action="{{ action('\Modules\ProductCompat\Http\Controllers\ReviewController@removeCustomFields') }}" style="display:inline;"
                                  onsubmit="return confirm('@lang('productcompat::lang.remove_cf_confirm')');">
                                @csrf
                                <input type="hidden" name="product_id" value="{{ $product->id }}">
                                <button class="btn btn-xs btn-danger">@lang('productcompat::lang.remove_custom_fields')</button>
                            </form>
                        @elseif(!empty($status) && $status->custom_fields_cleared_at)
                            <span class="label label-default">custom fields cleared</span>
                        @endif
                    </div>
                </div>
                <div class="box-body">
                    @if(count($customFields))
                        <div class="pc-legacy">
                            @foreach($customFields as $col => $val)
                                <div><strong>{{ $col }}:</strong> {{ $val }}</div>
                            @endforeach
                        </div>
                    @else
                        <em class="text-muted">No legacy custom field data.</em>
                    @endif
                </div>
            </div>
        </div>
    </div>

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

    <form method="POST" action="{{ action('\Modules\ProductCompat\Http\Controllers\ProductCompatController@store') }}">
        @csrf
        <input type="hidden" name="product_id" value="{{ $product->id }}">

        <div class="row">
            {{-- Part numbers --}}
            <div class="col-md-6">
                <div class="box box-info">
                    <div class="box-header with-border"><h3 class="box-title">@lang('productcompat::lang.part_numbers')</h3></div>
                    <div class="box-body">
                        <div id="pc-parts">
                            @foreach($partNumbers as $i => $pn)
                                <div class="row pc-row pc-part">
                                    <div class="col-xs-5"><input type="text" class="form-control input-sm" name="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="part_numbers[{{ $i }}][type]">
                                            @foreach($typeLabels as $k => $label)
                                                <option value="{{ $k }}" @if($pn->type==$k) selected @endif>{{ $label }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    <div class="col-xs-2"><label class="checkbox-inline"><input type="checkbox" name="part_numbers[{{ $i }}][is_primary]" value="1" @if($pn->is_primary) checked @endif> @lang('productcompat::lang.primary')</label></div>
                                    <div class="col-xs-2">
                                        @if($pn->needs_review)<span class="label label-warning" title="@lang('productcompat::lang.needs_review')">!</span>@endif
                                        <button type="button" class="btn btn-xs btn-danger pc-remove">&times;</button>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                        <button type="button" class="btn btn-xs btn-default" id="pc-add-part"><i class="fa fa-plus"></i> @lang('productcompat::lang.add')</button>
                    </div>
                </div>
            </div>

            {{-- Device models --}}
            <div class="col-md-6">
                <div class="box box-info">
                    <div class="box-header with-border"><h3 class="box-title">@lang('productcompat::lang.device_models')</h3></div>
                    <div class="box-body">
                        <div id="pc-devices">
                            @foreach($deviceModels as $i => $dc)
                                <div class="row pc-row pc-device">
                                    <div class="col-xs-3"><input type="text" class="form-control input-sm" name="device_models[{{ $i }}][brand]" value="{{ $dc->deviceModel->brand ?? '' }}" placeholder="@lang('productcompat::lang.brand')"></div>
                                    <div class="col-xs-3"><input type="text" class="form-control input-sm" name="device_models[{{ $i }}][series]" value="{{ $dc->deviceModel->series ?? '' }}" placeholder="@lang('productcompat::lang.series')"></div>
                                    <div class="col-xs-4"><input type="text" class="form-control input-sm" name="device_models[{{ $i }}][model]" value="{{ $dc->deviceModel->model ?? '' }}" placeholder="@lang('productcompat::lang.model')"></div>
                                    <div class="col-xs-2">
                                        @if($dc->needs_review)<span class="label label-warning">!</span>@endif
                                        <button type="button" class="btn btn-xs btn-danger pc-remove">&times;</button>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                        <button type="button" class="btn btn-xs btn-default" id="pc-add-device"><i class="fa fa-plus"></i> @lang('productcompat::lang.add')</button>
                    </div>
                </div>
            </div>
        </div>

        {{-- Compatible products --}}
        <div class="row">
            <div class="col-md-12">
                <div class="box box-info">
                    <div class="box-header with-border"><h3 class="box-title">@lang('productcompat::lang.compatible_products')</h3></div>
                    <div class="box-body">
                        <select class="form-control pc-compatibles" name="compatible_products[]" multiple style="width:100%;">
                            @foreach($compatibles as $c)
                                @if($c->compatibleProduct)
                                    <option value="{{ $c->compatibleProduct->id }}" selected>{{ $c->compatibleProduct->sku }} — {{ $c->compatibleProduct->name }}</option>
                                @endif
                            @endforeach
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <button type="submit" class="btn btn-primary">@lang('productcompat::lang.save')</button>
                <a href="{{ action('\Modules\ProductCompat\Http\Controllers\ProductCompatController@index') }}" class="btn btn-default">@lang('messages.back')</a>
            </div>
        </div>
    </form>
</section>

{{-- Row templates --}}
<template id="pc-part-template">
    <div class="row pc-row pc-part">
        <div class="col-xs-5"><input type="text" class="form-control input-sm" name="part_numbers[__I__][part_number]" placeholder="@lang('productcompat::lang.part_number')"></div>
        <div class="col-xs-3">
            <select class="form-control input-sm" name="part_numbers[__I__][type]">
                @foreach($typeLabels as $k => $label)<option value="{{ $k }}">{{ $label }}</option>@endforeach
            </select>
        </div>
        <div class="col-xs-2"><label class="checkbox-inline"><input type="checkbox" name="part_numbers[__I__][is_primary]" value="1"> @lang('productcompat::lang.primary')</label></div>
        <div class="col-xs-2"><button type="button" class="btn btn-xs btn-danger pc-remove">&times;</button></div>
    </div>
</template>
<template id="pc-device-template">
    <div class="row pc-row pc-device">
        <div class="col-xs-3"><input type="text" class="form-control input-sm" name="device_models[__I__][brand]" placeholder="@lang('productcompat::lang.brand')"></div>
        <div class="col-xs-3"><input type="text" class="form-control input-sm" name="device_models[__I__][series]" placeholder="@lang('productcompat::lang.series')"></div>
        <div class="col-xs-4"><input type="text" class="form-control input-sm" name="device_models[__I__][model]" placeholder="@lang('productcompat::lang.model')"></div>
        <div class="col-xs-2"><button type="button" class="btn btn-xs btn-danger pc-remove">&times;</button></div>
    </div>
</template>
@endsection

@section('javascript')
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(function () {
    var partIdx = {{ $partNumbers->count() }};
    var deviceIdx = {{ $deviceModels->count() }};

    $('#pc-add-part').on('click', function () {
        var html = $('#pc-part-template').html().replace(/__I__/g, partIdx++);
        $('#pc-parts').append(html);
    });
    $('#pc-add-device').on('click', function () {
        var html = $('#pc-device-template').html().replace(/__I__/g, deviceIdx++);
        $('#pc-devices').append(html);
    });
    $(document).on('click', '.pc-remove', function () {
        $(this).closest('.pc-row').remove();
    });

    $('.pc-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'
    });
});
</script>
@endsection
