<?php

namespace App\Console\Commands;

use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;
use Illuminate\Console\Command;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use App\Classes\Modules\Transactions\Processors\CreatePurchaseOrderTransactionProcessor;
use App\Classes\Modules\Transactions\Services\GeneratesPurchaseOrderProducts;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Models\Transaction;
use Illuminate\Support\Facades\DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Auto fill up the purchase order for booking that have payment';

    /** @var GeneratesPurchaseOrderProducts */
    private $generatesPurchaseOrderProducts;

    /** @var GeneratesTransactionBillNumber */
    private $generatesTransactionBillNumber;

    /** @var CreatePurchaseOrderTransactionProcessor */
    private $createPurchaseOrderTransactionProcessor;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(GeneratesPurchaseOrderProducts $generatesPurchaseOrderProducts, GeneratesTransactionBillNumber $generatesTransactionBillNumber, CreatePurchaseOrderTransactionProcessor $createPurchaseOrderTransactionProcessor)
    {
        parent::__construct();
        $this->generatesPurchaseOrderProducts = $generatesPurchaseOrderProducts;
        $this->generatesTransactionBillNumber = $generatesTransactionBillNumber;
        $this->createPurchaseOrderTransactionProcessor = $createPurchaseOrderTransactionProcessor;
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 5. If purchase order not fill up in 2 month, auto fill up it
        $bookings = Booking::where('status', ApprovalStatus::APPROVED)
            ->where('created_at', '<', now()->subDays(60)->endOfDay())
            ->whereHas('transactions', function($transaction) {
                return $transaction->where('type', TransactionType::PAYMENT)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
            })
            ->whereDoesntHave('transactions', function($transaction){
                $transaction->where('type', TransactionType::PURCHASE_ORDER);
                $transaction->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED]);
            })->get();

        foreach ($bookings as $booking) {
            $po = Transaction::where('type', TransactionType::PURCHASE_ORDER)
                ->where('status', ApprovalStatus::APPROVED)->where('issuer', $booking->company_id)
                ->select('*', DB::raw('abs(amount - ' . $booking->fix_amount . ') as nearest_price'))->orderBy('nearest_price')->first();


            if (!$po) {
                $po = Transaction::where('type', TransactionType::PURCHASE_ORDER)
                    ->where('status', ApprovalStatus::APPROVED)->select('*', DB::raw('abs(amount - ' . $booking->fix_amount . ') as nearest_price'))->orderBy('nearest_price')->first();
            }

            $products = $this->generatesPurchaseOrderProducts->execute($po, $booking->fix_amount);

            $deference = $booking->fix_amount - $products->sum('total');

            if($deference > -150 && $deference < 150 && $deference != 0) {

                $products->push([
                    'description' => $deference < 0 ? 'Discount':'Shipping Fee',
                    'quantity' => 1,
                    'stockCode' => '',
                    'total' => $deference,
                    'unit_price' => $deference
                ]);
            }

            $billNumber = $this->generatesTransactionBillNumber->execute('XPO-');

            $total = $products->sum('total');

            $object = new TransactionObject($billNumber, TransactionType::PURCHASE_ORDER, $booking->company->id, 1,
                1, PaymentMethodType::CASH,
                $total, $total, $booking->fix_currency_id, $booking->fix_currency_id,
                1, 0, 0, null, ApprovalStatus::PENDING_SUBMISSION, $products->toArray());

            $this->createPurchaseOrderTransactionProcessor->execute($booking, $object);
        }
    }
}
