<?php

namespace App\Http\Controllers;

use App\Services\OwnerDashboardAggregator;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\View\View;

class OwnerDashboardController extends Controller
{
    public function __construct(
        private OwnerDashboardAggregator $aggregator
    ) {}

    public function __invoke(Request $request): View
    {
        $dateFrom = $request->filled('date_from')
            ? Carbon::parse($request->date_from)->startOfDay()
            : now()->startOfMonth()->startOfDay();
        $dateTo = $request->filled('date_to')
            ? Carbon::parse($request->date_to)->endOfDay()
            : now()->endOfDay();

        $data = $this->aggregator->aggregate($dateFrom, $dateTo);

        $now = Carbon::now();
        $presets = [
            ['label' => 'Bulan ini', 'from' => $now->copy()->startOfMonth()->toDateString(), 'to' => $now->copy()->toDateString()],
            ['label' => '7 hari terakhir', 'from' => $now->copy()->subDays(6)->toDateString(), 'to' => $now->copy()->toDateString()],
            ['label' => '30 hari terakhir', 'from' => $now->copy()->subDays(29)->toDateString(), 'to' => $now->copy()->toDateString()],
            ['label' => 'Tahun ini', 'from' => $now->copy()->startOfYear()->toDateString(), 'to' => $now->copy()->toDateString()],
        ];

        return view('owner.dashboard', [
            'data' => $data,
            'dateFrom' => $dateFrom->toDateString(),
            'dateTo' => $dateTo->toDateString(),
            'generatedAt' => now(),
            'presets' => $presets,
        ]);
    }
}

