<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use App\BlockIP;

class BlockIPCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ip:add {ip} {--block}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'This command for add or block an IP address. Eg: ip:add 127.0.0.1 --block';

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

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        $ipAddress = $this->argument('ip');
        $blockMode = $this->option('block');
        $ip = BlockIP::where('ip', $ipAddress)->first();

        if (!$ip) {
            $ip = BlockIP::create([
                'ip'           => $ipAddress,
                'incorrect'    => 0,
                'is_activated' => 0,
                'is_deleted'   => 0,
                'created_at'   => date('Y-m-d H:i:s'),
                'updated_at'   => date('Y-m-d H:i:s'),
            ]);
        }

        if ($blockMode) {
            $ip->update([ 'is_activated' => 0, 'updated_at' => date('Y-m-d H:i:s') ]);
        } else {
            $ip->update([ 'incorrect' => 0, 'is_activated' => 1, 'is_deleted' => 0, 'updated_at' => date('Y-m-d H:i:s') ]);
        }

        Cache::forget('white-ips');
        $this->info('IP address was updated successful!');
    }
}
