<?php

namespace App\Http\Controllers\Api\Driver;

use App\Http\Controllers\Controller;
use App\Models\Booking;
use App\Models\DriverShift;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Driver home-screen stats — replaces the old project's useractiveshift,
 * which bundled shift status + today's earnings into one endpoint. Shift
 * status already has its own endpoint (Api\Driver\ShiftController::active);
 * this covers just the earnings/activity summary.
 */
class StatsController extends Controller
{
    public function today(Request $request): JsonResponse
    {
        $driver = $request->user()->driver;
        abort_unless($driver, 404, __('api.no_driver_profile'));

        $completed = Booking::where('driver_id', $driver->id)
            ->whereHas('status', fn ($q) => $q->where('name', 'Completed'))
            ->whereDate('updated_at', today())
            ->get();

        $activeShift = DriverShift::where('driver_id', $driver->id)->whereNull('ended_at')->first();

        return response()->json([
            'jobs_completed' => $completed->count(),
            'total_earnings' => round((float) $completed->sum('fare_amount'), 2),
            'total_distance' => round((float) $completed->sum('distance'), 2),
            'hours_on_shift' => $activeShift ? round($activeShift->started_at->diffInMinutes(now()) / 60, 1) : 0,
            'is_on_shift' => (bool) $activeShift,
        ]);
    }

    /**
     * ADD-02: the driver's actual payout ledger — distinct from today() above,
     * which is a gross-fare activity summary, not what the driver is owed
     * after commission or what's already been paid out.
     */
    public function earnings(Request $request): JsonResponse
    {
        $driver = $request->user()->driver;
        abort_unless($driver, 404, __('api.no_driver_profile'));

        $payouts = $driver->payouts()->latest()->get();

        $unpaidBookings = Booking::where('driver_id', $driver->id)
            ->whereNull('payout_id')
            ->whereHas('status', fn ($q) => $q->where('name', 'Completed'))
            ->get();

        $rate = $driver->effective_commission_rate;
        $pendingAmount = round((float) $unpaidBookings->sum('fare_amount') * ($rate / 100), 2);

        return response()->json([
            'commission_rate' => $rate,
            'pending_amount' => $pendingAmount,
            'pending_bookings_count' => $unpaidBookings->count(),
            'paid_amount' => round((float) $payouts->where('status', 'paid')->sum('amount'), 2),
            'payouts' => $payouts,
        ]);
    }
}
