<?php

namespace App\Http\Controllers\Api\Customer;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StatsController extends Controller
{
    /**
     * Spend/trip summary for the customer app's account screen — the old
     * project offered several preset ranges (today/this-week/this-month/
     * last-month/custom); {range} covers the same presets from one route.
     */
    public function summary(Request $request, string $range = 'this_month'): JsonResponse
    {
        [$from, $to] = match ($range) {
            'today' => [now()->startOfDay(), now()->endOfDay()],
            'this_week' => [now()->startOfWeek(), now()->endOfWeek()],
            'last_month' => [now()->subMonthNoOverflow()->startOfMonth(), now()->subMonthNoOverflow()->endOfMonth()],
            default => [now()->startOfMonth(), now()->endOfMonth()],
        };

        $bookings = $request->user()->bookings()
            ->whereHas('status', fn ($q) => $q->where('name', 'Completed'))
            ->whereBetween('pickup_datetime', [$from, $to])
            ->get();

        return response()->json([
            'range' => $range,
            'trip_count' => $bookings->count(),
            'total_spend' => round((float) $bookings->sum('fare_amount'), 2),
            'total_distance' => round((float) $bookings->sum('distance'), 2),
        ]);
    }
}
