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

@section('content')
<section class="content-header">
    <h1>@lang('productcompat::lang.review_queue')</h1>
</section>

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

    {{-- Bulk fast-path --}}
    <div class="row">
        <div class="col-md-12">
            <div class="box box-solid box-warning">
                <div class="box-body">
                    <form method="POST" action="{{ route('productcompat.review.bulk_approve') }}" class="form-inline"
                          onsubmit="return confirm('Approve every device suggestion at or above the chosen confidence?');">
                        @csrf
                        <strong>{{ number_format($bulkCount) }}</strong> device suggestion(s) pending review.
                        &nbsp; Bulk-approve confidence ≥
                        <select name="min_confidence" class="form-control input-sm">
                            <option value="50">50%</option>
                            <option value="55">55%</option>
                            <option value="75">75%</option>
                            <option value="90">90%</option>
                        </select>
                        <button class="btn btn-sm btn-warning"><i class="fa fa-check-double"></i> Bulk approve</button>
                        <a href="{{ route('productcompat.report') }}" class="btn btn-sm btn-default">@lang('productcompat::lang.change_report')</a>
                        <a href="{{ route('productcompat.index') }}" class="btn btn-sm btn-default">@lang('productcompat::lang.editor')</a>
                    </form>
                </div>
            </div>
        </div>
    </div>

    @forelse($products as $p)
        @php
            $devs = $flaggedDevices[$p->id] ?? collect();
            $parts = $flaggedParts[$p->id] ?? collect();
            $links = (isset($flaggedCompat) ? ($flaggedCompat[$p->id] ?? collect()) : collect());
            $cands = (isset($pendingCandidates) ? ($pendingCandidates[$p->id] ?? collect()) : collect());
        @endphp
        <div class="row">
            <div class="col-md-12">
                <div class="box box-warning collapsed-box">
                    <div class="box-header with-border">
                        <h3 class="box-title">{{ $p->sku }} — {{ \Illuminate\Support\Str::limit($p->name, 60) }}
                            <span class="label label-default">{{ $parts->count() }} parts</span>
                            <span class="label label-info">{{ $devs->count() }} devices</span>
                            @if($links->count())<span class="label label-success">{{ $links->count() }} compatible</span>@endif
                            @if($cands->count())<span class="label label-primary">{{ $cands->count() }} AI</span>@endif
                        </h3>
                        <div class="box-tools pull-right">
                            <form method="POST" action="{{ route('productcompat.review.check') }}" style="display:inline;"
                                  onsubmit="return confirm('Mark checked? All remaining suggestions for this product will be verified.');">
                                @csrf <input type="hidden" name="product_id" value="{{ $p->id }}">
                                <button class="btn btn-xs btn-success">@lang('productcompat::lang.mark_checked')</button>
                            </form>
                            <form method="POST" action="{{ route('productcompat.edit') }}" style="display:inline;">
                                @csrf <input type="hidden" name="product_sku" value="{{ $p->sku }}">
                                <button class="btn btn-xs btn-primary">@lang('messages.edit')</button>
                            </form>
                            <button type="button" class="btn btn-xs btn-default" data-widget="collapse"><i class="fa fa-plus"></i></button>
                        </div>
                    </div>
                    <div class="box-body">
                        <form method="POST">
                            @csrf
                            <p><label><input type="checkbox" class="pc-check-all"> <em>select all</em></label></p>

                            @if($parts->count())
                                <strong>@lang('productcompat::lang.part_numbers')</strong>
                                <div style="margin:4px 0 10px;">
                                    @foreach($parts as $pn)
                                        <label class="checkbox-inline" style="display:block;">
                                            <input type="checkbox" name="part_ids[]" value="{{ $pn->id }}" class="pc-item">
                                            {{ $pn->part_number }} <small class="text-muted">[{{ $pn->type }}] · {{ $pn->confidence }}%</small>
                                        </label>
                                    @endforeach
                                </div>
                            @endif

                            @if($devs->count())
                                <strong>@lang('productcompat::lang.device_models')</strong>
                                <div style="margin:4px 0 10px;">
                                    @foreach($devs as $dc)
                                        <label class="checkbox-inline" style="display:block;">
                                            <input type="checkbox" name="compat_ids[]" value="{{ $dc->id }}" class="pc-item">
                                            {{ optional($dc->deviceModel)->label() ?: '—' }} <small class="text-muted">· {{ $dc->confidence }}%</small>
                                        </label>
                                    @endforeach
                                </div>
                            @endif

                            @if($links->count())
                                <strong>@lang('productcompat::lang.compatible_products')</strong>
                                <div style="margin:4px 0 10px;">
                                    @foreach($links as $lk)
                                        <label class="checkbox-inline" style="display:block;">
                                            <input type="checkbox" name="link_ids[]" value="{{ $lk->id }}" class="pc-item">
                                            @if($lk->compatibleProduct)
                                                {{ $lk->compatibleProduct->sku }} — {{ \Illuminate\Support\Str::limit($lk->compatibleProduct->name, 45) }}
                                            @else #{{ $lk->compatible_product_id }} @endif
                                            <small class="text-muted">· {{ $lk->relation_type }} · {{ $lk->source }}</small>
                                        </label>
                                    @endforeach
                                </div>
                            @endif

                            <button class="btn btn-sm btn-success" formaction="{{ route('productcompat.review.approve') }}">
                                <i class="fa fa-check"></i> Approve selected
                            </button>
                            <button class="btn btn-sm btn-danger" formaction="{{ route('productcompat.review.reject') }}"
                                    onclick="return confirm('Delete the selected suggestions (wrong data)?');">
                                <i class="fa fa-trash"></i> Reject selected
                            </button>
                        </form>

                        @if($cands->count())
                            @include('productcompat::review._candidates', ['product' => $p, 'candidates' => $cands])
                        @endif
                    </div>
                </div>
            </div>
        </div>
    @empty
        <div class="row"><div class="col-md-12"><div class="callout callout-success">Nothing pending review 🎉</div></div></div>
    @endforelse

    <div class="row"><div class="col-md-12">{{ $products->links() }}</div></div>
</section>
@endsection

@section('javascript')
<script>
$(function () {
    $(document).on('change', '.pc-check-all', function () {
        $(this).closest('form').find('.pc-item').prop('checked', this.checked);
    });

    // Download & attach an AI-suggested product image (AJAX).
    $(document).on('click', '.pc-attach-image', function (e) {
        e.preventDefault();
        var $btn = $(this);
        if ($btn.prop('disabled')) { return; }

        var $card = $btn.closest('.pc-image-card');
        var replace = $card.find('.pc-image-replace').prop('checked') ? 1 : 0;
        var original = $btn.html();

        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i>');

        $.ajax({
            url: '{{ route('productcompat.candidate.apply_image') }}',
            method: 'POST',
            data: {
                _token: '{{ csrf_token() }}',
                candidate_id: $btn.data('candidate'),
                replace: replace
            }
        }).done(function (res) {
            if (res && res.success) {
                $btn.html('<i class="fa fa-check"></i>').removeClass('btn-primary').addClass('btn-success');
                if (res.image_url) {
                    $card.find('img').attr('src', res.image_url);
                }
            } else {
                alert((res && res.msg) ? res.msg : 'Failed');
                $btn.prop('disabled', false).html(original);
            }
        }).fail(function () {
            alert('Request failed.');
            $btn.prop('disabled', false).html(original);
        });
    });
});
</script>
@endsection
