@extends('layouts.admin')
@section('title', __('Financial dashboard'))

@section('content')
<h1 class="h4 fw-bold mb-3">📊 {{ __('Financial dashboard') }}</h1>

@if($pendingProofs > 0)
<a href="{{ route('admin.payments.index') }}" class="text-decoration-none">
    <div class="alert alert-warning d-flex justify-content-between align-items-center">
        <span>🧾 {{ __(':n payment proof(s) awaiting your review.', ['n' => $pendingProofs]) }}</span>
        <span class="btn btn-sm mb-btn-primary">{{ __('Review now') }}</span>
    </div>
</a>
@endif

{{-- KPI row --}}
<div class="row g-3 mb-3">
    <div class="col-6 col-lg-3"><div class="mb-metric">
        <div class="l">{{ __('Monthly recurring revenue') }}</div>
        <div class="v" dir="ltr">{{ number_format($mrr) }} <span class="fs-6 mb-muted">IQD</span></div>
    </div></div>
    <div class="col-6 col-lg-3"><div class="mb-metric">
        <div class="l">{{ __('Annual run-rate') }}</div>
        <div class="v" dir="ltr">{{ number_format($arr) }} <span class="fs-6 mb-muted">IQD</span></div>
    </div></div>
    <div class="col-6 col-lg-3"><div class="mb-metric">
        <div class="l">{{ __('Active subscriptions') }}</div>
        <div class="v">{{ $counts['active'] }}</div>
    </div></div>
    <div class="col-6 col-lg-3"><div class="mb-metric">
        <div class="l">{{ __('Monthly churn') }}</div>
        <div class="v">{{ $churn }}%</div>
    </div></div>
</div>

{{-- Subscription status counts --}}
<div class="row g-3 mb-3">
    @foreach([
        [__('Trialing'), $counts['trialing'], '#0EA5E9'],
        [__('Active'), $counts['active'], '#22C55E'],
        [__('Grace'), $counts['grace'], '#F5A524'],
        [__('Suspended'), $counts['suspended'], '#EF4444'],
        [__('Cancelled'), $counts['cancelled'], '#94A3B8'],
        [__('Expiring (7d)'), $expiringCount, '#EC4899'],
        [__('Trial → paid'), $conversion.'%', '#8B5CF6'],
    ] as $c)
        <div class="col-4 col-lg-2"><div class="mb-metric" style="border-inline-start:4px solid {{ $c[2] }}">
            <div class="l">{{ $c[0] }}</div><div class="v">{{ $c[1] }}</div>
        </div></div>
    @endforeach
</div>

<div class="row g-3">
    <div class="col-lg-8"><div class="mb-card p-4">
        <h2 class="h6 fw-semibold mb-3">{{ __('Revenue — last 6 months') }} <span class="mb-muted small">(IQD, {{ __('approx') }})</span></h2>
        <canvas id="revChart" height="110"></canvas>
    </div></div>
    <div class="col-lg-4">
        <div class="mb-card p-4 mb-3">
            <h2 class="h6 fw-semibold mb-3">{{ __('MRR by gateway') }}</h2>
            @forelse($mrrByGateway as $g)
                <div class="d-flex justify-content-between py-1">
                    <span>{{ \App\Enums\SubscriptionGateway::from($g->gateway ?? 'paddle')->label() }} <span class="mb-muted small">({{ $g->count }})</span></span>
                    <strong dir="ltr">{{ number_format($g->total) }} IQD</strong>
                </div>
            @empty
                <p class="mb-muted small mb-0">{{ __('No active paid subscriptions yet.') }}</p>
            @endforelse
        </div>
        <div class="mb-card p-4">
            <h2 class="h6 fw-semibold mb-3">{{ __('Revenue by payment method') }}</h2>
            @forelse($revenueByMethod as $m)
                <div class="d-flex justify-content-between py-1">
                    <span>{{ \App\Enums\SubscriptionGateway::from($m['gateway'] ?? 'paddle')->label() }} <span class="mb-muted small">({{ $m['count'] }})</span></span>
                    <strong dir="ltr">{{ number_format($m['total_iqd']) }} IQD</strong>
                </div>
            @empty
                <p class="mb-muted small mb-0">{{ __('No approved payments yet.') }}</p>
            @endforelse
        </div>
    </div>
</div>

<div class="row g-3 mt-0 mb-3">
    <div class="col-lg-4"><div class="mb-card p-4">
        <h2 class="h6 fw-semibold mb-3">{{ __('Trial conversion') }}</h2>
        <div class="d-flex justify-content-between py-1"><span>🟢 {{ __('Trials started') }}</span><strong>{{ $trialFunnel['started'] }}</strong></div>
        <div class="d-flex justify-content-between py-1"><span>💰 {{ __('Converted') }}</span><strong>{{ $trialFunnel['converted'] }}</strong></div>
        <div class="d-flex justify-content-between py-1"><span>⌛ {{ __('Expired without converting') }}</span><strong>{{ $trialFunnel['expired'] }}</strong></div>
        <hr>
        <div class="d-flex justify-content-between"><span class="fw-semibold">{{ __('Conversion rate') }}</span><strong>{{ $trialFunnel['rate'] }}%</strong></div>
    </div></div>
    <div class="col-lg-8"><div class="mb-card p-3 h-100">
        <h2 class="h6 fw-semibold px-2 pt-2">⏰ {{ __('Expiring within 7 days') }}</h2>
        <table class="table mb-table align-middle mb-0">
            <thead><tr><th>{{ __('Clinic') }}</th><th>{{ __('Status') }}</th><th>{{ __('Expires') }}</th></tr></thead>
            <tbody>
            @forelse($expiringClinics as $sub)
                <tr>
                    <td>{{ $sub->tenant?->name }}</td>
                    <td><span class="badge text-bg-{{ $sub->status === 'trialing' ? 'info' : 'success' }}">{{ __(ucfirst($sub->status)) }}</span></td>
                    <td>{{ $sub->current_period_ends_at->format('d M Y') }} <span class="mb-muted small">({{ $sub->current_period_ends_at->diffForHumans() }})</span></td>
                </tr>
            @empty
                <tr><td colspan="3" class="mb-muted py-3 text-center">{{ __('No clinics expiring this week.') }}</td></tr>
            @endforelse
            </tbody>
        </table>
    </div></div>
</div>

<div class="mb-card p-3 mt-3">
    <h2 class="h6 fw-semibold px-2 pt-2">{{ __('Recent clinics') }}</h2>
    <table class="table mb-table align-middle mb-0">
        <thead><tr><th>{{ __('Clinic') }}</th><th>{{ __('Status') }}</th><th>{{ __('Joined') }}</th></tr></thead>
        <tbody>
        @foreach($recentClinics as $clinic)
            <tr>
                <td>{{ $clinic->name }} @if($clinic->is_demo)<span class="badge text-bg-info">{{ __('Demo') }}</span>@endif
                    <div class="mb-muted small" dir="ltr">{{ $clinic->slug }}</div></td>
                <td><span class="badge text-bg-secondary">{{ __(ucfirst($clinic->subscription?->status ?? 'n/a')) }}</span></td>
                <td class="mb-muted small">{{ $clinic->created_at->format('d M Y') }}</td>
            </tr>
        @endforeach
        </tbody>
    </table>
</div>

@push('page-scripts')
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
<script>
new Chart(document.getElementById('revChart'), {
    type: 'bar',
    data: {
        labels: @json($revenueByMonth->pluck('label')),
        datasets: [{ data: @json($revenueByMonth->pluck('total')), backgroundColor: '#0EA5E9', borderRadius: 6 }],
    },
    options: { plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true } } },
});
</script>
@endpush
@endsection
