@extends('layouts.app')

@section('title', 'AI Usage')

@section('content')
<section class="content-header">
    <h1><i class="fas fa-chart-line"></i> AI Usage &amp; Cost
        <small>tokens, features, providers &amp; failover — last {{ $days }} days</small>
    </h1>
</section>

<section class="content">
    @php
        $calls   = (int) ($totals->calls ?? 0);
        $okCalls = (int) ($totals->ok_calls ?? 0);
        $tokens  = (int) ($totals->tin ?? 0) + (int) ($totals->tout ?? 0);
        $okPct   = $calls ? round($okCalls / $calls * 100) : 100;
        $fbPct   = $calls ? round($fallbackCalls / $calls * 100) : 0;
        $peak    = max(1, (int) ($daily->max('tokens') ?? 1));
    @endphp

    {{-- Budget guardrail: warning banner + month-to-date meter --}}
    @if(($budget['limit'] ?? 0) > 0)
        @php
            $bpc  = min(100, round(($budget['fraction'] ?? 0) * 100));
            $bcol = $budget['over'] ? '#dc2626' : ($budget['near'] ? '#d97706' : '#16a34a');
        @endphp
        @if($budget['over'])
            <div class="alert alert-danger" style="margin-bottom:12px;">
                <i class="fa fa-ban"></i> <strong>Monthly AI budget reached.</strong>
                {{ number_format($budget['used']) }} / {{ number_format($budget['limit']) }} tokens used this month.
                @if($budget['enforced']) New AI calls are refused until next month or until the budget is raised in AI Settings. @else Budget enforcement is off, so calls still run. @endif
            </div>
        @elseif($budget['near'])
            <div class="alert alert-warning" style="margin-bottom:12px;">
                <i class="fa fa-exclamation-triangle"></i> <strong>Approaching the monthly AI budget</strong> —
                {{ $bpc }}% used ({{ number_format($budget['used']) }} / {{ number_format($budget['limit']) }} tokens).
            </div>
        @endif
        <div style="margin-bottom:14px;">
            <div class="text-muted" style="font-size:12px;display:flex;justify-content:space-between;margin-bottom:3px;">
                <span>Monthly token budget</span>
                <span>{{ number_format($budget['used']) }} / {{ number_format($budget['limit']) }} ({{ $bpc }}%)</span>
            </div>
            <div style="height:10px;background:#e5e7eb;border-radius:5px;overflow:hidden;">
                <div style="height:100%;width:{{ $bpc }}%;background:{{ $bcol }};transition:width .3s;"></div>
            </div>
        </div>
    @endif

    {{-- Range selector --}}
    <div style="margin-bottom:12px;">
        @foreach([7=>'7 days',30=>'30 days',90=>'90 days'] as $d => $lbl)
            <a href="{{ route('aicore.usage', ['days' => $d]) }}"
               class="btn btn-xs {{ $days == $d ? 'btn-primary' : 'btn-default' }}">{{ $lbl }}</a>
        @endforeach
    </div>

    {{-- KPI cards --}}
    <div class="row">
        @php
        $cards = [
            ['Total calls', number_format($calls), 'fa-comments', '#2563eb'],
            ['Tokens used', number_format($tokens), 'fa-coins', '#7c3aed'],
            ['Success rate', $okPct . '%', 'fa-check-circle', $okPct >= 95 ? '#16a34a' : ($okPct >= 80 ? '#d97706' : '#dc2626')],
            ['Failover hits', number_format($fallbackCalls) . ' (' . $fbPct . '%)', 'fa-random', $fbPct > 10 ? '#d97706' : '#64748b'],
        ];
        // Audit trail: acceptance of AI suggestions (only once there is feedback data).
        if (($acceptancePct ?? null) !== null) {
            $cards[] = ['Suggestions applied', $accApplied . ' / ' . $accGenerated . ' (' . $acceptancePct . '%)',
                'fa-clipboard-check', $acceptancePct >= 50 ? '#16a34a' : '#64748b'];
        }
        @endphp
        @foreach($cards as [$label, $val, $icon, $color])
            <div class="col-md-3 col-sm-6">
                @component('components.widget', ['class' => 'box-solid'])
                    <div style="display:flex;align-items:center;gap:12px;">
                        <span style="width:46px;height:46px;border-radius:10px;display:flex;align-items:center;justify-content:center;background:{{ $color }};color:#fff;font-size:20px;flex:none;">
                            <i class="fas {{ $icon }}"></i>
                        </span>
                        <div>
                            <div style="font-size:22px;font-weight:700;line-height:1.1;">{{ $val }}</div>
                            <div class="text-muted" style="font-size:12px;">{{ $label }}</div>
                        </div>
                    </div>
                @endcomponent
            </div>
        @endforeach
    </div>

    <div class="row">
        {{-- Daily trend --}}
        <div class="col-md-7">
            @component('components.widget', ['class' => 'box-primary', 'title' => 'Daily tokens'])
                @if($daily->isEmpty())
                    <p class="text-muted">No AI calls in this period.</p>
                @else
                    <div style="display:flex;align-items:flex-end;gap:3px;height:140px;">
                        @foreach($daily as $row)
                            <div title="{{ $row->d }} — {{ number_format($row->tokens) }} tok, {{ $row->calls }} calls"
                                 style="flex:1;min-width:3px;background:#3b82f6;border-radius:2px 2px 0 0;
                                        height:{{ max(2, round($row->tokens / $peak * 100)) }}%;"></div>
                        @endforeach
                    </div>
                    <div class="text-muted" style="font-size:11px;margin-top:6px;display:flex;justify-content:space-between;">
                        <span>{{ optional($daily->first())->d }}</span><span>{{ optional($daily->last())->d }}</span>
                    </div>
                @endif
            @endcomponent
        </div>

        {{-- By provider / model --}}
        <div class="col-md-5">
            @component('components.widget', ['class' => 'box-default', 'title' => 'By provider / model'])
                <table class="table table-condensed" style="font-size:12px;margin-bottom:0;">
                    <thead><tr><th>Provider · Model</th><th class="text-right">Calls</th><th class="text-right">Tokens</th></tr></thead>
                    <tbody>
                    @forelse($byModel as $m)
                        <tr>
                            <td>{{ $m->provider }}<br><small class="text-muted">{{ $m->model ?: '—' }}</small></td>
                            <td class="text-right">{{ number_format($m->calls) }}</td>
                            <td class="text-right">{{ number_format((int) $m->tokens) }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="3" class="text-muted text-center">No data.</td></tr>
                    @endforelse
                    </tbody>
                </table>
            @endcomponent
        </div>
    </div>

    {{-- By feature --}}
    <div class="row">
        <div class="col-md-7">
            @component('components.widget', ['class' => 'box-default', 'title' => 'By feature'])
                <table class="table table-condensed" style="font-size:12px;margin-bottom:0;">
                    <thead><tr><th>Module / Feature</th><th class="text-right">Calls</th><th class="text-right">OK%</th><th class="text-right">Tokens</th></tr></thead>
                    <tbody>
                    @forelse($byFeature as $f)
                        @php $fok = $f->calls ? round($f->ok_calls / $f->calls * 100) : 100; @endphp
                        <tr>
                            <td>{{ $f->module ?: '—' }}{{ $f->feature ? ' / '.$f->feature : '' }}</td>
                            <td class="text-right">{{ number_format($f->calls) }}</td>
                            <td class="text-right" style="color:{{ $fok >= 95 ? '#16a34a' : ($fok >= 80 ? '#d97706' : '#dc2626') }};">{{ $fok }}%</td>
                            <td class="text-right">{{ number_format((int) $f->tokens) }}</td>
                        </tr>
                    @empty
                        <tr><td colspan="4" class="text-muted text-center">No data.</td></tr>
                    @endforelse
                    </tbody>
                </table>
            @endcomponent
        </div>

        {{-- Recent errors --}}
        <div class="col-md-5">
            @component('components.widget', ['class' => 'box-default', 'title' => 'Recent errors'])
                @if($errors->isEmpty())
                    <p class="text-muted" style="margin-bottom:0;"><i class="fa fa-check" style="color:#16a34a;"></i> No errors in this period.</p>
                @else
                    <table class="table table-condensed" style="font-size:11px;margin-bottom:0;">
                        <tbody>
                        @foreach($errors as $e)
                            <tr>
                                <td style="white-space:nowrap;">{{ optional($e->created_at)->format('m-d H:i') }}</td>
                                <td>{{ $e->feature ?: $e->module }}<br><span class="text-danger">{{ \Illuminate\Support\Str::limit($e->error, 80) }}</span></td>
                            </tr>
                        @endforeach
                        </tbody>
                    </table>
                @endif
            @endcomponent
        </div>
    </div>
</section>
@endsection
