<?php

namespace App\Console\Commands;


use App\Classes\Modules\Transactions\Services\ListsGroups;
use App\Classes\Modules\Transactions\Processors\CheckStorageInvoiceTransactionProcessor;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Console\Command;

class CheckStorageInvoicesGroupTransactions extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check-storage-invoices-group-transactions';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check all storage invoices due to make sure that they are up to date daily, prevent \'back door\' cases';

    /** @var ListsGroups */
    private $listsGroups;

    /** @var CheckStorageInvoiceTransactionProcessor */
    private $storageInvoiceTransactionProcessor;


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(ListsGroups $listsGroups, CheckStorageInvoiceTransactionProcessor $storageInvoiceTransactionProcessor)
    {
        parent::__construct();
        $this->listsGroups = $listsGroups;
        $this->storageInvoiceTransactionProcessor = $storageInvoiceTransactionProcessor;
    }


    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '-1');

        $this->info(Carbon::now() . ': Start Check all pending group payment with storage invoice is valid.');
        $start   = new Carbon();


        $newfilters['order_by_updated_at_desc'] = true;
        $newfilters['status_in'] = [0, 1];
        $groups = $this->listsGroups->execute($newfilters);

        foreach ($groups as $group){
            $this->info('CheckForStorageInvoiceByTransactions group: '.json_encode($group));
            foreach ($group->groupTransactions as $groupTransaction) {
                $invoice = $groupTransaction->transaction;
                $packingList = $invoice->owner()->first();
                if($packingList){
                    $order = $packingList->owner()->first();
                    if($order instanceof Order){
                        $storages = $this->storageInvoiceTransactionProcessor->executeOrder($order);
                    }
                }
            }
        }


        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');

        $this->info(Carbon::now() . ': Done Check all pending group payment with storage invoice is valid. ElapsedTime: ' . $elapsedTime . '.');
    }
}
