@extends('layouts.app')
@section('title', 'ProductCompat — Control Panel')

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

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

    @if(!empty($limitAt))
        <div class="alert alert-danger">
            <i class="fa fa-exclamation-triangle"></i>
            <strong>Icecat limit reached</strong> ({{ $limitAt }}). {{ $limitMsg }}
            Update the account in <a href="{{ route('productcompat.settings') }}">Settings</a> to continue.
        </div>
    @endif

    {{-- Coverage --}}
    <div class="row">
        <div class="col-md-3"><div class="info-box bg-aqua"><div class="info-box-content"><span class="info-box-text">Parseable products</span><span class="info-box-number">{{ number_format($coverage['parseable']) }}</span></div></div></div>
        <div class="col-md-3"><div class="info-box bg-green"><div class="info-box-content"><span class="info-box-text">With part number</span><span class="info-box-number">{{ number_format($coverage['with_pn']) }}</span></div></div></div>
        <div class="col-md-3"><div class="info-box bg-yellow"><div class="info-box-content"><span class="info-box-text">Enriched (success)</span><span class="info-box-number">{{ number_format($coverage['enriched']) }}</span></div></div></div>
        <div class="col-md-3"><div class="info-box bg-red"><div class="info-box-content"><span class="info-box-text">No part number</span><span class="info-box-number">{{ number_format($coverage['without_pn']) }}</span></div></div></div>
    </div>

    {{-- Parse coverage: how many parseable products have actually been parsed --}}
    @php
        $pct = ($coverage['parseable'] ?? 0) > 0 ? (int) floor($coverage['parsed'] / $coverage['parseable'] * 100) : 100;
    @endphp
    <div class="row">
        <div class="col-md-12">
            <div class="box {{ ($coverage['unparsed'] ?? 0) > 0 ? 'box-warning' : 'box-success' }}">
                <div class="box-body">
                    <strong>Parse coverage</strong>
                    &nbsp; <span class="text-muted">{{ number_format($coverage['parsed']) }} / {{ number_format($coverage['parseable']) }} parseable products parsed</span>
                    @if(($coverage['unparsed'] ?? 0) > 0)
                        &nbsp;·&nbsp; <span class="text-red"><strong>{{ number_format($coverage['unparsed']) }}</strong> not parsed yet</span>
                        <small class="text-muted">— click "Parse custom fields" below.</small>
                    @else
                        &nbsp; <span class="text-green"><i class="fa fa-check-circle"></i> all parsed</span>
                    @endif
                    <div class="progress" style="margin:6px 0 0;">
                        <div class="progress-bar {{ $pct >= 100 ? 'progress-bar-success' : 'progress-bar-yellow' }}" style="width:{{ $pct }}%;">{{ $pct }}%</div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-header with-border">
                    <h3 class="box-title">Run pipeline</h3>
                    <div class="box-tools pull-right">
                        <small>Active providers: <strong>{{ implode(', ', $providerKeys) ?: 'none' }}</strong></small>
                        &nbsp; <a href="{{ route('productcompat.settings') }}" class="btn btn-xs btn-default"><i class="fa fa-cog"></i> Settings</a>
                    </div>
                </div>
                <div class="box-body">
                    <button class="btn btn-default pc-run" data-type="parse"><i class="fa fa-cogs"></i> Parse custom fields</button>
                    <button class="btn btn-info pc-run" data-type="enrich_has"><i class="fa fa-cloud-download-alt"></i> Enrich (Icecat — has part #)</button>
                    <button class="btn btn-warning pc-run" data-type="enrich_missing"><i class="fa fa-search"></i> Enrich (search — no part #)</button>
                    <button class="btn btn-danger pull-right" id="pc-stop" style="display:none;"><i class="fa fa-stop"></i> Stop</button>

                    <div id="pc-progress-wrap" style="display:none;margin-top:18px;">
                        <div><strong id="pc-prog-label"></strong> <span id="pc-prog-status" class="label label-info"></span></div>
                        <div class="progress" style="margin-top:6px;height:24px;">
                            <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>

    {{-- AI Search Queue --}}
    <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.ai_search_queue')</h3>
                    <div class="box-tools pull-right">
                        <small>
                            @lang('productcompat::lang.status_queued'): <strong>{{ number_format($queueStats['queued']) }}</strong>
                            &nbsp;·&nbsp; @lang('productcompat::lang.status_failed'): <strong>{{ number_format($queueStats['failed']) }}</strong>
                        </small>
                        &nbsp; <a href="{{ route('productcompat.queue') }}" class="btn btn-xs btn-default"><i class="fa fa-list"></i> @lang('productcompat::lang.manage_queue')</a>
                    </div>
                </div>
                <div class="box-body">
                    <button class="btn btn-success pc-run" data-type="ai_queue" @if($queueStats['queued'] < 1) disabled @endif>
                        <i class="fa fa-robot"></i> @lang('productcompat::lang.queue_run_now')
                    </button>
                    <span class="text-muted" style="margin-left:8px;">@lang('productcompat::lang.queue_card_help')</span>
                </div>
            </div>
        </div>
    </div>

    {{-- Recent runs --}}
    <div class="row">
        <div class="col-md-12">
            <div class="box box-default">
                <div class="box-header with-border"><h3 class="box-title">Recent runs</h3></div>
                <div class="box-body table-responsive">
                    <table class="table table-condensed table-bordered">
                        <thead><tr><th>#</th><th>Type</th><th>Trigger</th><th>Status</th><th>Processed</th><th>Matched</th><th>+Parts</th><th>+Devices</th><th>+Barcodes</th><th>When</th></tr></thead>
                        <tbody>
                            @forelse($recent as $j)
                                <tr>
                                    <td>{{ $j->id }}</td><td>{{ $j->type }}</td><td>{{ $j->trigger }}</td>
                                    <td><span class="label label-{{ $j->status=='done'?'success':($j->status=='running'?'info':($j->status=='stopped'?'warning':'danger')) }}">{{ $j->status }}</span></td>
                                    <td>{{ $j->processed }}/{{ $j->total }}</td><td>{{ $j->matched }}</td>
                                    <td>{{ $j->added_parts }}</td><td>{{ $j->added_devices }}</td><td>{{ $j->added_barcodes }}</td>
                                    <td>{{ optional($j->started_at)->diffForHumans() }}</td>
                                </tr>
                            @empty
                                <tr><td colspan="10" class="text-center text-muted">No runs yet.</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</section>
@endsection

@section('javascript')
<script>
$(function () {
    var token = $('meta[name="csrf-token"]').attr('content');
    var labels = { parse: 'Parsing custom fields', enrich_has: 'Enriching (Icecat)', enrich_missing: 'Enriching (search)', ai_queue: 'AI search queue' };
    var current = null, stopped = false;
    $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': token } });

    function render(p) {
        $('#pc-progress-wrap').show();
        $('#pc-prog-label').text(labels[p.type] || p.type);
        $('#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); }); // transient error: retry
    }

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

    $('.pc-run').on('click', function () {
        var type = $(this).data('type');
        stopped = false;
        $('.pc-run').prop('disabled', true);
        $('#pc-stop').show();
        $.post('{{ route('productcompat.panel.start') }}', { type: type }, function (res) {
            current = res.job_id;
            render({ type: type, 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(); });
    });

    @if(!empty($active))
        // resume an in-progress UI job
        current = {{ $active->id }};
        $('.pc-run').prop('disabled', true); $('#pc-stop').show();
        loop(current);
    @endif
});
</script>
@endsection
