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

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

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

    <div class="row">
        <div class="col-md-12">
            <div class="box box-primary">
                <div class="box-header with-border">
                    @php
                        // Human labels for the run types.
                        $pcActionLabels = [
                            'ai_enrich' => 'AI check',
                            'ai_apply'  => 'AI applied',
                            'parse'     => 'Parse',
                            'enrich'    => 'Enrich',
                        ];
                        $pcActionLabel = fn ($a) => $pcActionLabels[$a] ?? ucfirst((string) $a);
                        $curAction = request('action');
                        $totalRuns = $actionCounts->sum();
                        // Group runs by type for the dropdown optgroups.
                        $pcRunsByAction = $runsMeta->groupBy('action');
                    @endphp

                    {{-- Group / type filter tabs --}}
                    <ul class="nav nav-pills" style="margin-bottom:10px;">
                        <li class="{{ $curAction ? '' : 'active' }}">
                            <a href="{{ route('productcompat.report') }}">@lang('productcompat::lang.all') <span class="badge">{{ $totalRuns }}</span></a>
                        </li>
                        @foreach($actionCounts as $action => $cnt)
                            <li class="{{ $curAction === $action ? 'active' : '' }}">
                                <a href="{{ route('productcompat.report', ['action' => $action]) }}">
                                    {{ $pcActionLabel($action) }} <span class="badge">{{ $cnt }}</span>
                                </a>
                            </li>
                        @endforeach
                    </ul>

                    <form method="GET" class="form-inline">
                        @if($curAction)<input type="hidden" name="action" value="{{ $curAction }}">@endif
                        <label>@lang('productcompat::lang.run'):</label>
                        <select name="run_id" class="form-control input-sm" onchange="this.form.submit()" style="min-width:280px;">
                            <option value="">— @lang('productcompat::lang.all') —</option>
                            @foreach($pcRunsByAction as $action => $runs)
                                <optgroup label="{{ $pcActionLabel($action) }}">
                                    @foreach($runs as $run)
                                        <option value="{{ $run->run_id }}" @if(request('run_id')==$run->run_id) selected @endif>
                                            {{ \Illuminate\Support\Carbon::parse($run->last_at)->format('M j, H:i') }} · {{ $run->cnt }} {{ \Illuminate\Support\Str::plural('product', $run->cnt) }}
                                        </option>
                                    @endforeach
                                </optgroup>
                            @endforeach
                        </select>
                        <a href="{{ action('\Modules\ProductCompat\Http\Controllers\ChangeReportController@export') }}?run_id={{ request('run_id') }}&action={{ $curAction }}"
                           class="btn btn-sm btn-success"><i class="fa fa-download"></i> @lang('productcompat::lang.export')</a>
                    </form>
                </div>
                <div class="box-body table-responsive">
                    <table class="table table-bordered table-condensed">
                        <thead>
                            <tr>
                                <th>SKU</th>
                                <th>@lang('productcompat::lang.product_compatibility')</th>
                                <th>@lang('productcompat::lang.old_data')</th>
                                <th>@lang('productcompat::lang.new_data')</th>
                                <th>@lang('productcompat::lang.removed_data')</th>
                                <th>@lang('productcompat::lang.missing_data')</th>
                            </tr>
                        </thead>
                        <tbody>
                            @php
                                // AI rows (ai_enrich / ai_apply) store arrays and count maps in the
                                // JSON columns, while parse/enrich rows store plain strings — render
                                // any shape safely instead of assuming scalars.
                                $pcStr = function ($v) use (&$pcStr) {
                                    if (is_array($v)) {
                                        return implode(', ', array_map($pcStr, $v));
                                    }
                                    if (is_bool($v)) {
                                        return $v ? 'yes' : 'no';
                                    }
                                    return (string) $v;
                                };
                            @endphp
                            @forelse($reports as $r)
                                <tr>
                                    <td>{{ $r->product->sku ?? '' }}</td>
                                    <td>
                                        {{ \Illuminate\Support\Str::limit($r->product->name ?? ('#'.$r->product_id), 40) }}
                                        @if(in_array($r->action, ['ai_enrich', 'ai_apply'], true))
                                            <br><span class="label label-primary">{{ $r->action === 'ai_enrich' ? 'AI check' : 'AI applied' }}</span>
                                        @endif
                                    </td>
                                    <td><small>
                                        @foreach((array) $r->old_data as $col => $val)
                                            <div><strong>{{ $col }}:</strong> {{ \Illuminate\Support\Str::limit($pcStr($val), 120) }}</div>
                                        @endforeach
                                    </small></td>
                                    <td><small>
                                        @php $nd = (array) $r->new_data; @endphp
                                        @if(in_array($r->action, ['ai_enrich', 'ai_apply'], true))
                                            @foreach($nd as $k => $v)
                                                <div><strong>{{ $k }}:</strong> {{ \Illuminate\Support\Str::limit($pcStr($v), 120) }}</div>
                                            @endforeach
                                        @else
                                            @if(!empty($nd['part_numbers']))
                                                <div><strong>PN:</strong>
                                                    @foreach($nd['part_numbers'] as $p)<span class="label label-default">{{ $p['value'] }} [{{ $p['type'] }}]</span> @endforeach
                                                </div>
                                            @endif
                                            @if(!empty($nd['device_models']))
                                                <div><strong>Fits:</strong>
                                                    @foreach($nd['device_models'] as $d)<span class="label label-info">{{ $d['label'] }}</span> @endforeach
                                                </div>
                                            @endif
                                            @if(!empty($nd['barcodes']))
                                                <div><strong>Barcodes:</strong> {{ $pcStr($nd['barcodes']) }}</div>
                                            @endif
                                        @endif
                                    </small></td>
                                    <td><small>
                                        @foreach((array) $r->removed_data as $rm)
                                            <span class="label label-danger">{{ is_array($rm) ? ($rm['value'] ?? $pcStr($rm)) : $rm }}</span>
                                        @endforeach
                                    </small></td>
                                    <td><small>
                                        @foreach((array) $r->missing_data as $m)
                                            <span class="label label-warning">{{ $pcStr($m) }}</span>
                                        @endforeach
                                    </small></td>
                                </tr>
                            @empty
                                <tr><td colspan="6" class="text-center text-muted">No change reports yet. Run <code>php artisan productcompat:parse-custom-fields</code>.</td></tr>
                            @endforelse
                        </tbody>
                    </table>
                    {{ $reports->links() }}
                </div>
            </div>
        </div>
    </div>
</section>
@endsection
