<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\DeliveryMan;
use App\Models\DeliveryManBonus;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;

class DeliveryManBonusController extends Controller
{
    public function list(Request $request): \Illuminate\Http\JsonResponse
    {
        $dm = DeliveryMan::where(['auth_token' => $request['token']])->first();
        $deliveryManBonus = DeliveryManBonus::where('from_date', '<=', date('Y-m-d'))->where('to_date', '>=', date('Y-m-d'))->first();
        if($deliveryManBonus) {
            $getFinishedBonusesCount = count($dm->bonuses->where('bonus_id', $deliveryManBonus->id));
            $totalLevelsCount = count(json_decode($deliveryManBonus->levels));
            $currentLevel = $getFinishedBonusesCount + 1;
            if ($currentLevel > $totalLevelsCount) {
                $currentLevel = $getFinishedBonusesCount;
            }
            $currentLevelInfo = json_decode($deliveryManBonus->levels)[max($currentLevel - 1, 0)];
            $ordersCount = Order::where('delivery_man_id', $dm->id)->where('order_status', 'delivered')->where('delivered', '>=', $deliveryManBonus->from_date . ' 00:00:00')->where('delivered', '<=', $deliveryManBonus->to_date . ' 23:59:59')->where('is_collect_bonus', null)->orderBy('id', 'DESC')->paginate($currentLevelInfo->orders_count)->count();
            $deliveryManBonus['current_level'] = $currentLevel;
            $deliveryManBonus['finished_orders'] = $ordersCount;
            $deliveryManBonus['levels'] = json_decode($deliveryManBonus['levels']);
        }
        return response()->json($deliveryManBonus, 200);
    }
}
