<?php

namespace App\Models;

use App\CentralLogics\Helpers;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class DeliveryManBonus extends Model
{
    use HasFactory;
    protected $fillable = ['from_date', 'to_date', 'levels'];

    public static function addBonusForDeliveryMan($dm)
    {
        if($dm->earning == 1) { //Add bonus for freelance delivery man
            //Check delivery man bonuses
            $DMBonus = DeliveryManBonus::where('from_date', '<=', date('Y-m-d'))->where('to_date', '>=', date('Y-m-d'))->first();
            if($DMBonus){
                $getFinishedBonusesCount = count($dm->bonuses->where('bonus_id', $DMBonus->id));
                $totalLevelsCount = count(json_decode($DMBonus->levels));
                $currentLevel = $getFinishedBonusesCount + 1;
                if($currentLevel > $totalLevelsCount) {
                    //$currentLevel = $getFinishedBonusesCount;
                    return;
                }
                //////$currentLevelInfo = json_decode($DMBonus->levels)[$currentLevel];
                $currentLevelInfo = json_decode($DMBonus->levels)[max($currentLevel - 1, 0)];
                //$ordersCount = Order::where('delivery_man_id', $dm->id)->where('order_status', 'delivered')->where('delivered', '>=', $DMBonus->from_date . ' 00:00:00')->where('delivered', '<=', $DMBonus->to_date . ' 23:59:59')->where('is_collect_bonus', null)->orderBy('id', 'DESC')->paginate($currentLevelInfo->orders_count)->count();
                $ordersCount = Order::where('delivery_man_id', $dm->id)->where('order_status', 'delivered')->where('delivered', '>=', $DMBonus->from_date . ' 00:00:00')->where('delivered', '<=', $DMBonus->to_date . ' 23:59:59')->where('is_collect_bonus', null)->orderBy('id', 'DESC')->limit($currentLevelInfo->orders_count)->get()->count();
                if($currentLevelInfo->orders_count == $ordersCount){
                    $amount = $currentLevelInfo->amount ?? 0;
                    $giftTitle = $currentLevelInfo->gift_title ?? '';
                    $giftPicture = $currentLevelInfo->gift_picture ?? '';

                    $collectBalanceFromOrders = Order::where('delivery_man_id', $dm->id)->where('order_status', 'delivered')->where('delivered', '>=', $DMBonus->from_date . ' 00:00:00')->where('delivered', '<=', $DMBonus->to_date . ' 23:59:59')->where('is_collect_bonus', null)->orderBy('id', 'DESC')->limit($currentLevelInfo->orders_count)->update([
                        'is_collect_bonus' => 1,
                    ]);

                    //Add bonus
                    $d_m_bouns = DMBouns::create([
                        'delivery_man_id' => $dm->id,
                        'bonus_id' => $DMBonus->id,
                        'bonus_info' => $DMBonus,
                        'amount' => $amount,
                        'gift_title' => $giftTitle,
                        'gift_picture' => $giftPicture,
                        'level' => $currentLevel,
                    ]);

                    if($amount > 0) {
                        //Add payment to delivery man account transaction
                        $account_transaction = new AccountTransaction();
                        $account_transaction->from_type = 'deliveryman';
                        $account_transaction->from_id = $dm->id;
                        $account_transaction->ref = ' الحافز عن الفترة من ' . $DMBonus->from_date . ' لغاية ' . $DMBonus->to_date;
                        $account_transaction->method = 'حافز تلقائي رقم: ' . $DMBonus->id;
                        $account_transaction->amount = $amount;
                        $account_transaction->current_balance = DeliveryMan::getTheRemainingBalanceForDeliveryMan($dm, '', '');
                        $account_transaction->save();
                    }

                    $getDMLogMessage = Helpers::getDMLogMessage('add_bonus');
                    $getDMLogMessage = str_replace('******', $DMBonus->from_date .' لغاية '. $DMBonus->to_date, $getDMLogMessage);
                    DMLog::createLog($dm->id, $getDMLogMessage, $amount == 0 ? null : $amount, null);

                }
            }
        }
    }


}
