<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Booking;
use App\Models\Service;
use Illuminate\Support\Carbon;
use Illuminate\View\View;

class ReportController extends Controller
{
    public function index(): View
    {
        $from = request('from') ? Carbon::parse(request('from'))->startOfDay() : now()->startOfMonth();
        $to = request('to') ? Carbon::parse(request('to'))->endOfDay() : now()->endOfDay();

        $daily = Booking::query()
            ->whereBetween('scheduled_at', [$from, $to])
            ->selectRaw('DATE(scheduled_at) as day, COUNT(*) as bookings, SUM(total_amount) as revenue')
            ->groupBy('day')
            ->orderBy('day')
            ->get();

        $byStatus = Booking::query()
            ->whereBetween('scheduled_at', [$from, $to])
            ->selectRaw('status, COUNT(*) as total')
            ->groupBy('status')
            ->pluck('total', 'status');

        $topServices = Service::query()
            ->withCount(['bookings' => fn ($q) => $q->whereBetween('scheduled_at', [$from, $to])])
            ->orderByDesc('bookings_count')
            ->limit(8)
            ->get();

        return view('tenant.reports.index', [
            'from' => $from,
            'to' => $to,
            'dailyLabels' => $daily->pluck('day')->values(),
            'dailyBookings' => $daily->pluck('bookings')->map(fn ($value) => (int) $value)->values(),
            'dailyRevenue' => $daily->pluck('revenue')->map(fn ($value) => (float) $value)->values(),
            'statusLabels' => $byStatus->keys()->values(),
            'statusData' => $byStatus->values()->map(fn ($value) => (int) $value)->values(),
            'serviceLabels' => $topServices->pluck('name')->values(),
            'serviceData' => $topServices->pluck('bookings_count')->values(),
        ]);
    }
}
