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

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

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

    {{-- Run the queue now (chunked, live progress) --}}
    <div class="row">
        <div class="col-md-12">
            <div class="box box-solid box-success">
                <div class="box-body">
                    <button type="button" class="btn btn-success pc-run" data-type="ai_queue"
                            @if(($statusCounts['queued'] ?? 0) < 1) disabled @endif>
                        <i class="fa fa-robot"></i> @lang('productcompat::lang.queue_run_now')
                    </button>
                    <button type="button" class="btn btn-danger" id="pc-stop" style="display:none;">
                        <i class="fa fa-stop"></i> @lang('productcompat::lang.stop')
                    </button>
                    <span class="text-muted" style="margin-left:8px;">@lang('productcompat::lang.queue_card_help')</span>

                    <div id="pc-progress-wrap" style="display:none; margin-top:12px;">
                        <div>
                            <strong id="pc-prog-label"></strong>
                            <span id="pc-prog-status" class="label"></span>
                        </div>
                        <div class="progress" style="margin:6px 0;">
                            <div id="pc-bar" class="progress-bar progress-bar-striped active" role="progressbar" style="width:0%;">0%</div>
                        </div>
                        <div id="pc-prog-stats" class="text-muted"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    {{-- Add products + backfill --}}
    <div class="row">
        <div class="col-md-7">
            <div class="box box-solid box-info">
                <div class="box-header with-border"><h3 class="box-title">@lang('productcompat::lang.add_products')</h3></div>
                <div class="box-body">
                    <form method="POST" action="{{ route('productcompat.queue.add') }}" class="form-inline">
                        @csrf
                        <select class="form-control pc-q-products" name="product_ids[]" multiple style="width:70%;"></select>
                        <button class="btn btn-primary"><i class="fa fa-plus"></i> @lang('productcompat::lang.add_to_queue')</button>
                    </form>
                    <p class="text-muted" style="margin:6px 0 0;">@lang('productcompat::lang.add_products_help')</p>
                </div>
            </div>
        </div>
        <div class="col-md-5">
            <div class="box box-solid box-warning">
                <div class="box-header with-border"><h3 class="box-title">@lang('productcompat::lang.backfill_missing')</h3></div>
                <div class="box-body">
                    <form method="POST" action="{{ route('productcompat.queue.backfill') }}" class="form-inline"
                          onsubmit="return confirm('@lang('productcompat::lang.backfill_confirm')');">
                        @csrf
                        <label>@lang('productcompat::lang.backfill_cap'):</label>
                        <input type="number" name="cap" value="500" min="1" max="5000" class="form-control input-sm" style="width:90px;">
                        <button class="btn btn-warning btn-sm"><i class="fa fa-database"></i> @lang('productcompat::lang.backfill_run')</button>
                    </form>
                    <p class="text-muted" style="margin:6px 0 0;">@lang('productcompat::lang.backfill_help')</p>

                    <hr style="margin:10px 0;">
                    <form method="POST" action="{{ route('productcompat.queue.all') }}" class="form-inline"
                          onsubmit="return confirm('@lang('productcompat::lang.queue_all_confirm')');">
                        @csrf
                        <button class="btn btn-danger btn-sm"><i class="fa fa-list-ul"></i> @lang('productcompat::lang.queue_all')</button>
                    </form>
                    <p class="text-muted" style="margin:6px 0 0;">@lang('productcompat::lang.queue_all_help')</p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-header with-border">
                    {{-- Status filter tabs --}}
                    <ul class="nav nav-pills">
                        <li class="{{ empty($status) ? 'active' : '' }}">
                            <a href="{{ route('productcompat.queue') }}">@lang('productcompat::lang.all') <span class="badge">{{ array_sum($statusCounts) }}</span></a>
                        </li>
                        @foreach($statusCounts as $s => $c)
                            <li class="{{ $status === $s ? 'active' : '' }}">
                                <a href="{{ route('productcompat.queue', ['status' => $s]) }}">@lang('productcompat::lang.status_' . $s) <span class="badge">{{ $c }}</span></a>
                            </li>
                        @endforeach
                    </ul>
                </div>
                <div class="box-body table-responsive">
                    <form method="POST">
                        @csrf
                        <button class="btn btn-sm btn-info" formaction="{{ route('productcompat.queue.retry') }}">
                            <i class="fa fa-redo"></i> @lang('productcompat::lang.retry_selected')
                        </button>
                        <button class="btn btn-sm btn-default" formaction="{{ route('productcompat.queue.skip') }}"
                                onclick="return confirm('@lang('productcompat::lang.skip_confirm')');">
                            <i class="fa fa-ban"></i> @lang('productcompat::lang.skip_selected')
                        </button>

                        <table class="table table-bordered table-condensed" style="margin-top:10px;">
                            <thead>
                                <tr>
                                    <th style="width:24px;"><input type="checkbox" class="pc-q-check-all"></th>
                                    <th>@lang('productcompat::lang.product_compatibility')</th>
                                    <th>SKU</th>
                                    <th>@lang('productcompat::lang.reason')</th>
                                    <th>@lang('productcompat::lang.queue_status')</th>
                                    <th>@lang('productcompat::lang.attempts')</th>
                                    <th>@lang('productcompat::lang.last_error')</th>
                                    <th>@lang('productcompat::lang.queued_at')</th>
                                    <th>@lang('productcompat::lang.processed_at')</th>
                                </tr>
                            </thead>
                            <tbody>
                                @forelse($entries as $e)
                                    <tr>
                                        <td>
                                            @if(in_array($e->status, ['queued', 'failed'], true))
                                                <input type="checkbox" name="ids[]" value="{{ $e->id }}" class="pc-q-item">
                                            @endif
                                        </td>
                                        <td>{{ \Illuminate\Support\Str::limit($e->product_name ?? ('#' . $e->product_id), 50) }}</td>
                                        <td>{{ $e->product_sku }}</td>
                                        <td><span class="label label-default">{{ $e->reason }}</span></td>
                                        <td>
                                            <span class="label label-{{ $e->status == 'done' ? 'success' : ($e->status == 'queued' ? 'info' : ($e->status == 'processing' ? 'primary' : ($e->status == 'failed' ? 'danger' : 'default'))) }}">
                                                @lang('productcompat::lang.status_' . $e->status)
                                            </span>
                                        </td>
                                        <td>{{ $e->attempts }}</td>
                                        <td><small class="text-danger">{{ \Illuminate\Support\Str::limit($e->last_error, 80) }}</small></td>
                                        <td><small>{{ optional($e->created_at)->diffForHumans() }}</small></td>
                                        <td><small>{{ optional($e->processed_at)->diffForHumans() }}</small></td>
                                    </tr>
                                @empty
                                    <tr><td colspan="9" class="text-center text-muted">@lang('productcompat::lang.queue_empty')</td></tr>
                                @endforelse
                            </tbody>
                        </table>
                    </form>
                    {{ $entries->links() }}
                </div>
            </div>
        </div>
    </div>
</section>
@endsection

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

    if ($.fn.select2) {
        $('.pc-q-products').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: '{{ __('productcompat::lang.search_product') }}',
            width: '70%'
        });
    }

    // ── Run the AI search queue in chunks with live progress ──────────────
    // Reuses the shared panel run endpoints, so this screen can start a run
    // without sending the user to the Control Panel.
    var token = $('meta[name="csrf-token"]').attr('content');
    var current = null, stopped = false;
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': token } });

    function render(p) {
        $('#pc-progress-wrap').show();
        $('#pc-prog-label').text('{{ __('productcompat::lang.ai_search_queue') }}');
        $('#pc-prog-status').removeClass().addClass('label label-' + (p.status=='done'?'success':(p.status=='running'?'info':(p.status=='stopped'?'warning':'danger')))).text(p.status);
        $('#pc-bar').css('width', p.percent + '%').text(p.percent + '%');
        $('#pc-prog-stats').html('Processed <b>' + p.processed + '</b> / ' + p.total +
            ' &nbsp;·&nbsp; matched <b>' + p.matched + '</b> &nbsp;·&nbsp; +' + p.parts + ' parts, +' + p.devices + ' devices, +' + p.barcodes + ' barcodes' +
            (p.message ? '<br><span class="text-danger">' + p.message + '</span>' : ''));
    }

    function loop(jobId) {
        if (stopped) return;
        $.post('{{ route('productcompat.panel.chunk') }}', { job_id: jobId }, function (p) {
            render(p);
            if (p.status === 'running') { setTimeout(function () { loop(jobId); }, 250); }
            else { finish(); }
        }).fail(function () { setTimeout(function () { loop(jobId); }, 1500); });
    }

    function finish() {
        $('.pc-run').prop('disabled', false);
        $('#pc-stop').hide();
        setTimeout(function () { location.reload(); }, 1400);
    }

    $('.pc-run').on('click', function () {
        stopped = false;
        $('.pc-run').prop('disabled', true);
        $('#pc-stop').show();
        $.post('{{ route('productcompat.panel.start') }}', { type: 'ai_queue' }, function (res) {
            current = res.job_id;
            render({ type: 'ai_queue', status: 'running', percent: 0, processed: 0, total: res.total, matched: 0, parts: 0, devices: 0, barcodes: 0 });
            loop(current);
        });
    });

    $('#pc-stop').on('click', function () {
        stopped = true;
        if (current) $.post('{{ route('productcompat.panel.stop') }}', { job_id: current }, function (p) { render(p); finish(); });
    });
});
</script>
@endsection
