<?php

namespace App\Console\Commands;

use App\Order as AppOrder;
use Codexshaper\WooCommerce\Facades\Order;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Aggiornamenti ordini da GM';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $all_orderswoo = new Collection();
        $page = 1;
        do{
            $orderswoo = Order::all($options = ['per_page' => 100, 'page' => $page,'status'=> ["pending","processing","on-hold"]]);
            $all_orderswoo = $all_orderswoo->merge($orderswoo);
            $page++;
        } while($orderswoo->count() > 0);

        foreach($all_orderswoo as $orderwoo ){
            $ordergm = AppOrder::where('IdInternet', $orderwoo->id)->latest('DataOra')->first();
            if($ordergm){
                if($orderwoo->status == 'processing'){
                     if($ordergm->EnabledWoo == 1){
                                $data = [
                                    'status' => 'completed',
                                ];
                                $orderwooupdate = Order::update($orderwoo->id,$data);
                            }
            }
            elseif ($orderwoo->status == 'on-hold'){

                if($ordergm->FlagSospeso == 0) {
                    $data = [
                        'status' => 'processing',
                    ];
                    $orderwooupdate = Order::update($orderwoo->id,$data);
                }

            }

            }
        }
    }
}
