<?php

namespace App\Classes\Jobs\Commands\V2;


use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\Booking;
use App\Models\Transaction;
use App\Classes\Modules\Transactions\DataTransferObjects\TransactionObject;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\Modules\Transactions\Processors\CreatePurchaseOrderTransactionProcessor;
use App\Classes\Modules\Transactions\Services\GeneratesPurchaseOrderProducts;
use App\Classes\Modules\Transactions\Services\GeneratesTransactionBillNumber;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AutoFillPurchaseOrderV2CommandJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Auto fill up the purchase order for booking that have payment.');
        $start   = new Carbon();

        // 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();
        Log::info('Bookings count: '.count($bookings));

        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 =  (App()->make(GeneratesPurchaseOrderProducts::class))->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 = (App()->make(GeneratesTransactionBillNumber::class))->execute('XPO-');

            Log::info('Single booking billNumber: '.$billNumber);

            $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());

                (App()->make(CreatePurchaseOrderTransactionProcessor::class))->execute($booking, $object);
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Auto fill up the purchase order for booking that have payment. ElapsedTime: ' . $elapsedTime . '.');
    }
}
