<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Yajny\EventsYj\Events\ProcessPayoutEvent;
use Yajny\EventsYj\Events\RecalculateBalance;
use Yajny\Member\Models\Sale;
use Yajny\Member\Models\UserPayoutMethods;
use Yajny\Member\Models\UserPayouts;
use Yajny\Member\Models\UserSales;
use Yajny\Member\Models\UsersBalance;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Get approved manually payments and process them';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $approvedPayouts = UserPayouts::where('status','approved_automatically')->get();

        foreach ($approvedPayouts as $payout){

            $method = UserPayoutMethods::where('method_code',$payout->method_code)->where('account', $payout->account)->firstOrFail();
            $oldProcessedPayout=DB::table('processed_payouts')->where('payout_id',$payout->id)->first();
            if (!$oldProcessedPayout) {
                event(new ProcessPayoutEvent($payout, $method));
                DB::table('processed_payouts')->insert([
                    "payout_id" => $payout->id,
                    "user_id" => $payout->user_id,
                    "processed_auto"=>true,
                ]);
                }



        }

    }
}
