<?php

namespace App\Console\Commands\Network;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Yajny\Member\Models\Network;

class SalesCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'network:sales {start_days=0} {end_days=0} {network=all}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Calculate network sales';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startTime = microtime(true);
        $end_days = $this->argument('end_days');
        $start_days = $this->argument('start_days');
        $networkArg = $this->argument('network');

        if ($end_days > $start_days)
            die('end_days has to be less than start_days');

        $networks = Network::where('enabled', 1)->where('type', 'pull')->get();
        Log::debug('AMAZON_EG_DEBUGGER::salesCommand', [
            'cli' => app()->runningInConsole(),
            'arguments' => $this->arguments(),
            'networks' => $networks->count(),
            'trace' => debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS),
        ]);
        foreach ($networks as $network) {
            if($networkArg != 'all' && $network->name != $networkArg)
                continue;
            try {
                if ($network->controller && class_exists('\App\Http\Controllers\Network\\' . $network->controller))
                    $networkCtrl = app()->make('\App\Http\Controllers\Network\\' . $network->controller, compact('network'));
                else
                    $networkCtrl = app()->make('\App\Http\Controllers\Network\DirectIntegration', compact('network'));

                $networkCtrl->getSales($start_days, $end_days);
                $network->error_count = 0;
                $network->save();
            } catch (\Exception $exception) {
                if ($network->error_count > 5) {
                    Log::error('Failed to get sales', [
                        'exception' => $exception,
                        'network' => $network->toArray(),
                        'start_days' => $start_days,
                        'end_days' => $end_days
                    ]);
                }
                $network->increment('error_count');
                $network->save();
            }
        }
        $endTime = microtime(true);
        $executionTime = $endTime - $startTime;
        Log::channel("separated_file")->info("The Script".class_basename($this)." from $start_days to $end_days Took : $executionTime");
    }
}