<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\Models\User;
use Carbon\Carbon;

use App\Models\EmailQueue;
use Illuminate\Support\Str;


class ExpiredAccountsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check_expired_users';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This script check expired users and block them';

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

    function checkExpired(){
    	echo "\n\n CHECKING EXPIRED ACCOUNTS!\n\n";

    	// Calcolo un anno fa da oggi
    	$data = Carbon::now()->subYear();

        echo "\n ".$data." checking an year ago from now ...\n";
    	
    	// prendo gli utenti
    	$users_first_renewal = User::where([
            ['created_at', '<=', $data],
            ['renew_date', '=', NULL],
            ['expired', '=', 0],
        ])->get();

        $users_next_renewal = User::where([
            ['expired', '=', 0],
            ['renew_date', '<=', $data]
        ])->get();

        echo "\n ".(count($users_first_renewal) + count($users_next_renewal))." expired accounts.\n\n";


    	foreach ($users_first_renewal as $k => $v) {

            $token = Str::random(64);

            echo "\n Disabling -> ".$v->first_name." ".$v->last_name." (".$v->email.")\n";
    		$v->active = 0;
    		$v->expired = 1;
            $v->renewal_token = $token;

    		$v->save();

            $mail = EmailQueue::create([
                'label' => 'Account expired 12',
                'type' => '2',
                'user_id' => $v->id,
                'info' => $v->first_name.' '.$v->last_name.': account expired! It will be deactivated. ',
                'to' => $v->email
            ]);
    	}

        foreach ($users_next_renewal as $k => $v) {

            $token = Str::random(64);

            echo "\n Disabling -> ".$v->first_name." ".$v->last_name." (".$v->email.")\n";
            $v->active = 0;
            $v->expired = 1;
            $v->renewal_token = $token;
            
            $v->save();

            $mail = EmailQueue::create([
                'label' => 'Account expired 12',
                'type' => '2',
                'user_id' => $v->id,
                'info' => $v->first_name.' '.$v->last_name.': account expired! It will be deactivated. ',
                'to' => $v->email
            ]);


        }

        echo "\n\n All Done!\n\n";

    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
    	# $ctrl = new MailQueueController();
    	# echo $ctrl->sendEmails();

        return $this->checkExpired();

    }
}