<?php

namespace App\Livewire;

use App\Models\SaasSubscription;
use App\Models\Transaction;
use App\Models\User;
use Livewire\Attributes\Layout;
use Livewire\Component;

#[Layout('layouts.app')]
class AnalyticsPage extends Component
{
    public function render()
    {
        $totalUsers = User::query()->count();
        $premiumUsers = User::query()
            ->whereHas('saasSubscriptions', fn ($q) => $q->whereIn('status', ['active', 'trialing']))
            ->count();
        $activeSubscriptions = SaasSubscription::query()
            ->whereIn('status', ['active', 'trialing'])
            ->count();
        $monthlyRevenue = SaasSubscription::query()
            ->whereIn('status', ['active', 'trialing'])
            ->sum('price_monthly');
        $expensesThisMonth = abs((float) Transaction::query()
            ->where('type', 'expense')
            ->whereBetween('date', [now()->startOfMonth(), now()->endOfMonth()])
            ->sum('amount'));

        return view('livewire.analytics-page')
            ->with([
                'metrics' => [
                    ['icon' => 'users', 'label' => (string) __('budgets.analytics_page.metrics_total_users'), 'value' => $totalUsers, 'change' => '+0%'],
                    ['icon' => 'crown', 'label' => (string) __('budgets.analytics_page.metrics_premium_users'), 'value' => $premiumUsers, 'change' => '+0%'],
                    ['icon' => 'repeat', 'label' => (string) __('budgets.analytics_page.metrics_active_subscriptions'), 'value' => $activeSubscriptions, 'change' => '+0%'],
                    ['icon' => 'wallet', 'label' => (string) __('budgets.analytics_page.metrics_monthly_revenue'), 'amount' => $monthlyRevenue, 'change' => '+0%'],
                    ['icon' => 'receipt', 'label' => (string) __('budgets.analytics_page.metrics_monthly_expenses'), 'amount' => $expensesThisMonth, 'change' => '+0%'],
                ],
            ])
            ->title((string) __('budgets.analytics_page.title'));
    }
}
