<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DMBoost extends Model
{
    use HasFactory;
    protected $fillable = ['boost_id', 'boost_info', 'delivery_man_id'];

    public static function getBoost($deliveryMan, $orderId): bool
    {
        $check = DMBoost::where('delivery_man_id', $deliveryMan->id)->orderBy('id', 'DESC')->first();
        if($check){
            $created_at = $check->created_at;
            $boostInfo = json_decode($check->boost_info);
            $startAt = $boostInfo->start_at;
            $endAt = $boostInfo->end_at;
            //Check orders count
            $checkOrdersCount = Order::where('boost_id', $check->boost_id)->where('delivery_man_id', $deliveryMan->id)->where('order_status', '!=', 'canceled')->count();
            if($checkOrdersCount >= $boostInfo->max_number_of_orders){
                return false;
            }

            if(Carbon::create(date('Y-m-d'))->between($startAt, $endAt)){
                $date = Carbon::parse($created_at);
                $now = Carbon::now();
                $diff = $date->diffInHours($now);
                if($diff <= $boostInfo->duration_by_hours){
                    $orderInfo = Order::where('id', $orderId)->first();
                    if($orderInfo->delivery_charge <= $boostInfo->max_amount) {
                        Order::where('id', $orderId)->update([
                            'boost_id' => $boostInfo->id,
                            'boost_info' => json_encode($boostInfo),
                            'boost_amount' => null,
                        ]);
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
