<?php

namespace App\Console\Commands\Cashback;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Yajny\Member\Models\Sale;
use Yajny\EventsYj\Events\SaleUpdated;

class AutoConfirmCashback extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cashback:auto_confirm_cashback';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Auto confirm cashback';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $startTime = microtime(true);

        $sales = Sale::join('networks', 'sales.network_id', '=', 'networks.id')
            ->where('networks.confirm_days', '>', 0)
            ->where('networks.auto_confirm', '=', 1)
            ->where('sales.status', '=', 'pending')
            ->whereRaw('networks.confirm_days <=  DATEDIFF(now(), sales.transaction_time)')
            ->get('sales.*');
        foreach ($sales as $sale) {
            $sale->status = 'confirmed';
            $sale->auto_action = true;
            $sale->save();
            event(new SaleUpdated($sale, $sale->getChanges()));
        }
        $endTime = microtime(true);
        $executionTime = $endTime - $startTime;
        Log::channel("separated_file")->info("The Script".class_basename($this)."   Took : $executionTime");
    }
}
