<?php

namespace App\Console\Commands;

use App\Constants\Status;
use App\Lib\RewardLib;
use App\Models\Reward;
use App\Models\User;
use Illuminate\Console\Command;

class MarkRewardExpiredCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:mark-reward-expired';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command marks reward as unachievable';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $users = User::with('rewards')->fullActivated()->where('rank', '<', 7)->get();
        $rewardLimit = RewardLib::rewards();

        foreach ($users as $user) {
            $networkActivatedAt = $user->network_activated_at;
            $rewards = $user->rewards;
            foreach ($rewardLimit as $level => $reward) {
                $endsAt = $networkActivatedAt->copy()->addDays($reward['time']);

                if ($endsAt->isPast()) {
                    $rewardStatus = $rewards->where(function ($item) use ($reward, $level) {
                        return $item->rank == $level;
                    })->first();

                    if(!$rewardStatus) {
                        // create reward with failed at achieved status.
                        Reward::create([
                            'user_id' => $user->id,
                            'prize' => $reward['reward'],
                            'rank' => $level,
                            'status_changed_at' => now(),
                            'reject_reason' => 'Reward Expired',
                            'status' => Status::Rejected,
                        ]);
                    }
                }
            }
        }
    }
}
