<?php

namespace App\Http\Controllers\Api\Provider;

use App\Enums\BookingItemStatus;
use App\Enums\BookingStatus;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\Traits\ApiResponse;
use App\Http\Resources\BookingItemResource;
use App\Http\Resources\BookingResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use OpenApi\Annotations as OA;

class DashboardController extends Controller
{
    use ApiResponse;

    /**
     * @OA\Get(
     *     path="/api/provider/dashboard",
     *     summary="Get dashboard data for the authenticated provider",
     *     tags={"Provider Dashboard"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="Accept-Language",
     *         in="header",
     *         required=false,
     *         description="Language preference (e.g., 'en', 'ar')",
     *         @OA\Schema(type="string", enum={"en", "ar"}, default="en")
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="Dashboard data",
     *         @OA\JsonContent(
     *             @OA\Property(property="success", type="boolean", example=true),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="total_bookings", type="integer", example=10),
     *                 @OA\Property(property="completed_bookings", type="integer", example=5),
     *                 @OA\Property(property="total_earnings", type="number", format="float", example=5000.00),
     *                 @OA\Property(property="total_clients", type="integer", example=5),
     *                 @OA\Property(property="average_rating", type="number", format="float", example=0),
     *                 @OA\Property(property="recent_bookings", type="array", @OA\Items(ref="#/components/schemas/BookingItemResource"))
     *             ),
     *             @OA\Property(property="message", type="string", example="Dashboard data retrieved successfully.")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="Unauthenticated"
     *     )
     * )
     */
    public function dashboard()
    {
        /** @var \App\Models\ServiceProvider $provider */
        $provider = Auth::user();

        $totalBookings = $provider->bookingItems()->count();
        $completedBookings = $provider->bookingItems()
            ->where('status', BookingItemStatus::COMPLETED->value)
            ->whereDate('service_date', '<', now())
            ->count();
        $totalEarnings = $provider->bookingItems()
            ->where('status', BookingItemStatus::COMPLETED->value)
            ->whereDate('service_date', '<', now())
            ->sum('net_price');
        $totalClients = $provider->bookingItems()->distinct('user_id')->count('user_id');
        // return the average rating of all products offered by the provider
        $averageRating = $provider->reviews()->avg('rating') ?? 0;

        $recentBookings = $provider->bookingItems()->with(['user', 'product.media', 'product.cities'])->latest()->take(5)->get();

        $data = [
            'total_bookings' => $totalBookings,
            'completed_bookings' => $completedBookings,
            'total_earnings' => $totalEarnings,
            'total_clients' => $totalClients,
            'average_rating' => round($averageRating, 2),
            'recent_bookings' => BookingItemResource::collection($recentBookings),
        ];

        return $this->successResponse($data, __('messages.dashboard_retrieved_successfully'));
    }
}
