<?php

namespace App\Console\Commands;

use App\Classes\Modules\PackingLists\Services\ListsPackingLists;
use App\Classes\Modules\Transactions\Processors\CreateInvoiceTransactionProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Order;
use Carbon\Carbon;
use Exception;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Auto generate invoice';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $packingLists = (App()->make(ListsPackingLists::class))->execute(['does_not_have_transaction_type' => 1, 'type' => 2]);

        if (count($packingLists)) {
            $this->info(Carbon::now() . ' : Auto generate invoice cron started.');
            $start   = new Carbon();

            foreach ($packingLists as $packingList) {
                $order = $packingList->owner;
                if (!($order instanceof Order)) {
                    $this->info('Failed to generate invoice for reference' . $order->reference . '. It is not an instance of Order.');
                    continue;
                }

                $companyModule = $order->companyModule;
                $billingAddress = $companyModule->addresses()->where('type', \App\Classes\ValueObjects\Constants\AddressType::BILLING)->first();
                $deliveryAddress = $order->addresses()->where('status', ApprovalStatus::APPROVED)->first();

                $postCodes = \App\Models\SegmentConstant::whereIn('reference', ['CENTER_POSTCODE', 'OUTSTATION_POSTCODE'])->get()->pluck('value')->flatten();

                if (!!$billingAddress && in_array($deliveryAddress->postcode, $postCodes->toArray())) {
                    try {
                        (App()->make(CreateInvoiceTransactionProcessor::class))->execute($packingList);
                        $this->info('Invoice generated for reference ' . $order->reference . '.');
                    } catch (Exception $exception) {
                        $this->info('Failed to generate invoice for reference ' . $order->reference . '. Exception: ' . $exception->getMessage());
                    }
                }
                $this->info('Failed to generate invoice for reference ' . $order->reference . '. Billing Address is not defined / Postcode area is not defined.');
            }

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

            $this->info(Carbon::now() . ' : Done generating invoice. ElapsedTime: ' . $elapsedTime . '.');
        }
    }
}
