<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\DeliveryMan;
use App\Models\DeliveryManBoost;
use App\Models\DMBoost;
use Carbon\Carbon;
use Illuminate\Http\Request;

class DeliveryManBoostController extends Controller
{
    public function boost(Request $request): \Illuminate\Http\JsonResponse
    {
        $dm = DeliveryMan::where(['auth_token' => $request['token']])->first();
        $deliveryManBoosts = DeliveryManBoost::where('start_at', '<=', date('Y-m-d'))->where('end_at', '>=', date('Y-m-d'))->first();
        if(!$deliveryManBoosts){
            return response()->json(['errors' => translate('messages.no_boosts_available_now')], 403);
        }
        $check = DMBoost::where('delivery_man_id', $dm->id)->where('boost_id', $deliveryManBoosts->id)->orderBy('id', 'DESC')->first();
        if(!$check){
            DMBoost::create([
                'delivery_man_id' => $dm->id,
                'boost_id' => $deliveryManBoosts->id,
                'boost_info' => json_encode($deliveryManBoosts),
            ]);
        }
        return response()->json(['message' => translate('messages.boost_added_to_your_account')], 200);
    }

    public function get(Request $request): \Illuminate\Http\JsonResponse
    {
        $result = [
            'btn_status' => 0,
            'is_enabled' => 0,
            'boost_info' => null,
        ];
        $dm = DeliveryMan::where(['auth_token' => $request['token']])->first();
        $deliveryManBoosts = DeliveryManBoost::where('start_at', '<=', date('Y-m-d'))->where('end_at', '>=', date('Y-m-d'))->first();
        if($deliveryManBoosts){
            $result['btn_status'] = 1;
            $result['boost_info'] = $deliveryManBoosts;
        }else{
            return response()->json($result, 200);
        }

        $check = DMBoost::where('delivery_man_id', $dm->id)->where('boost_id', $deliveryManBoosts->id)->orderBy('id', 'DESC')->first();
        if(!$check){
            $result['is_enabled'] = 1;
        }
        return response()->json($result, 200);
    }
}
