<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use \Carbon\Carbon;
use App\Models\User;

class UpdateLastOnline extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'users:update-last-online';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update last online user if he/she is not active with the period of three minutes';

    /**
     * Execute the console command.
     */
    public function handle()
    {
       $now = Carbon::now()->format('Y-m-d H:i:s');
       $users = User::whereNotNull('last_online')->where('last_online', '!=', '')->get();
       foreach($users as $user)
       {
            $lastOnline = Carbon::parse($user->last_online);
        
            if ($lastOnline->diffInMinutes($now) > 3) {
                //update user
                $user->is_available = 0;
                $user->save();
            }
       }
       
       $this->info('Users last online updated successfully.');
       return 0;
    }
}
