<?php

namespace App\Console\Commands\Cashback;

use App\Helpers\Bonus\ConfirmBonusHelper;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Yajny\EventsYj\Events\BonusUpdated;
use Yajny\Member\Models\UserBonus;

class ConfirmBonus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cashback:confirm_bonus {type?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'confirming bonuses';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startTime = microtime(true);

        $bonusType = $this->argument('type');
        $query = UserBonus::where('status', 'pending');
        if($bonusType)
            $query->where('bonus_code', $bonusType);
        $bonusCount = $query->count();
        for($i = 0 ; $i < $bonusCount ; $i += 50) {
            $query = UserBonus::where('status', 'pending');
            if($bonusType)
                $query->where('bonus_code', $bonusType);
            $pending_bonuses = $query->with('type_info')->skip($i)->take(50)->get();
            foreach ($pending_bonuses as $bonus) {
                if (ConfirmBonusHelper::isBonusConfirmed($bonus)) {
                    $bonus->update(['status' => 'confirmed']);
                    event(new BonusUpdated($bonus->user, $bonus));
                }
            }
        }
        $endTime = microtime(true);
        $executionTime = $endTime - $startTime;
        Log::channel("separated_file")->info("The Script".class_basename($this)." Took : $executionTime");
        return;

    }
}
