<?php

namespace App\Console\Commands\FraudDetection;

use Illuminate\Console\Command;
use Yajny\Member\FraudDetection\FraudDetection;
use Yajny\Member\Models\FraudRule;

class DetectFraudUsers extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fraud_users:detect
                            {--S|simulate : Simulate the detection and only return the users who would have been flagged as fraud}
                            {--from= : Determine the date to start the detection from}
                            {--to= : Determine the date to end the detection to}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Detect fraud users';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function handle()
    {
        $applyFromDate = $this->option('from') ?? date('Y-m-d', strtotime('today - 2 weeks'));
        $applyToDate = $this->option('to') ?? date('Y-m-d', strtotime('today - 2 weeks'));
        $rules = FraudRule::where('status', 1)
            ->whereDate('effective_from', '<=', $applyFromDate)
            ->where(function ($query) use ($applyToDate) {
                $query->whereNull('effective_to')
                    ->orWhereDate('effective_to', '>=', $applyToDate);
            })
            ->get();
        $bar = $this->output->createProgressBar(count($rules));

        $bar->start();

        $headers = ['Rule Name', 'Number of detected users', 'Detected Users'];
        $detectedUsers = [];

        foreach ($rules as $rule) {
            $bar->advance();

            $fraudDetection = new FraudDetection($rule, $this->option('from'), $this->option('to'));

            if ($this->option('simulate'))
                $detectedFraudUsers = $fraudDetection->simulate();
            else
                $detectedFraudUsers = $fraudDetection->run();

            $detectedUsers[] = [
                'ruleName' => $rule->name,
                'detectedUsersCount' => count($detectedFraudUsers),
                'detectedUsers' => implode(', ', $detectedFraudUsers)
            ];
        }
        $bar->finish();
        $this->line('');
        $this->table($headers, $detectedUsers);
    }
}
