<?php

namespace App\Livewire\Dashboard;

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

class RevenueWidget extends Component
{
    use UsesBranchScope;

    public string $period = 'month';

    public function render()
    {
        $branchId = $this->getActiveBranchId();

        $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)
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->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])
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->sum('amount');

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

        $byMethod = Payment::where('status', 'confirmed')
            ->where('created_at', '>=', $startDate)
            ->when($branchId, fn ($q) => $q->where('branch_id', $branchId))
            ->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,
        ]);
    }
}
