<?php

namespace App\Console\Commands;


use App\Classes\Modules\Orders\Services\ListsOrders;
use App\Classes\Modules\Transactions\Processors\CheckStorageInvoiceTransactionProcessor;
use App\Classes\ValueObjects\Constants\OrderType;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Console\Command;

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

    /**
     * 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 ListsOrders */
    private $listsOrders;

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


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


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

        $this->info(Carbon::now() . ': Start Check all orders for storage invoice.');
        $start   = new Carbon();

        $orders = $this->listsOrders->execute(['with_parcels' => true, 'type_in' => [OrderType::SHARED_CONTAINER, OrderType::DEDICATED_CONTAINER]]);

        $count = 0;
        foreach ($orders as $order){
            try{
                $storages = $this->storageInvoiceTransactionProcessor->executeOrder($order);
                $count =  $count + 1;
                $this->info('Order '.$count);
            }
            catch(\Exception $ex){
                $this->info('Exception '.$ex->getMessage());
                break;
            }
        }


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

        $this->info(Carbon::now() . ': Done Check all orders for storage invoice. ElapsedTime: ' . $elapsedTime . '.');
    }
}
