<?php

namespace App\Console\Commands\Cashback;

use Yajny\Member\Models\Network;
use Illuminate\Console\Command;
use Yajny\EventsYj\Events\SaleUpdated;
use Yajny\Member\Models\Sale;

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

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

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $networks = Network::where('enabled', 1)->where('confirm_days', '>', 0)->get()->toArray();
        foreach ($networks as $network) {
            $pendingSales = Sale::whereRaw(' DATE(transaction_time) <= DATE_SUB(CURRENT_DATE, INTERVAL ' . ($network['confirm_days'] * 2) . ' DAY) ')->where('network_id', $network['id'])->where('status', 'pending')->get();
            foreach ($pendingSales as $sale) {
                $sale->update(['status' => 'declined', 'auto_action' => true]);
                event(new SaleUpdated($sale, $sale->getChanges()));
            }
        }
    }
}
