<?php

namespace App\Livewire\Dashboard;

use App\Domain\Financial\Models\Payment;
use Illuminate\Support\Facades\DB;
use Livewire\Component;

class RevenueWidget extends Component
{
    public string $period = 'month';

    public function render()
    {
        $startDate = match ($this->period) {
            'today' => now()->startOfDay(),
            'week' => now()->startOfWeek(),
            'month' => now()->startOfMonth(),
            'year' => now()->startOfYear(),
            default => now()->startOfMonth(),
        };

        $revenue = Payment::where('status', 'confirmed')
            ->where('created_at', '>=', $startDate)
            ->sum('amount');

        $previousStart = match ($this->period) {
            'today' => now()->subDay()->startOfDay(),
            'week' => now()->subWeek()->startOfWeek(),
            'month' => now()->subMonth()->startOfMonth(),
            'year' => now()->subYear()->startOfYear(),
            default => now()->subMonth()->startOfMonth(),
        };

        $previousRevenue = Payment::where('status', 'confirmed')
            ->whereBetween('created_at', [$previousStart, $startDate])
            ->sum('amount');

        $change = $previousRevenue > 0
            ? round(($revenue - $previousRevenue) / $previousRevenue * 100, 1)
            : ($revenue > 0 ? 100 : 0);

        $byMethod = Payment::where('status', 'confirmed')
            ->where('created_at', '>=', $startDate)
            ->select('method', DB::raw('SUM(amount) as total'))
            ->groupBy('method')
            ->pluck('total', 'method')
            ->toArray();

        return view('livewire.dashboard.revenue-widget', [
            'revenue' => $revenue,
            'change' => $change,
            'byMethod' => $byMethod,
        ]);
    }
}
