<?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 Illuminate\Support\Facades\Log;
use App\Classes\Modules\Documents\DataTransferObjects\DocumentObject;
use App\Classes\Modules\Documents\Services\CreatesDocument;
use App\Classes\Modules\Documents\Services\CreatesFiles;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\DocumentType;
use App\Models\Document;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Group;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Mccarlosen\LaravelMpdf\Facades\LaravelMpdf;

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


    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Update those group with currency rate more than 100.');
        $start   = new Carbon();

        $groups = Group::where('currency_rate', '>', 100)->get();

        foreach ($groups as $group) {
            $transactions = $group->transactions()->get();

            $rate = DB::table('transaction_logs')->where('transaction_id', $transactions->first()->id)->latest('updated_at')->first()->currency_rate;

            $supplier = $group->issuerCompany;

            foreach ($transactions as $transaction) {
                $transaction->currency_rate = $rate;
                $transaction->amount = $transaction->original_amount / $rate;
                $transaction->save();

                $supplierRefundTransactions = $transaction->owner->transactions()->supplierRefunds()->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::APPROVED])->get();

                foreach ($supplierRefundTransactions as  $supplierRefundTransaction) {
                    $claimBefore = $supplierRefundTransaction->transactions()->where('type', TransactionType::BILL_REFUND)->where('status', ApprovalStatus::APPROVED)->exists();

                    if (!$claimBefore) {
                        $supplierRefundTransaction->currency_rate = $rate;
                        $supplierRefundTransaction->amount =  $supplierRefundTransaction->original_amount / $rate;
                        $supplierRefundTransaction->save();
                    }
                }
            }

            $group_transfer_fee = $group->morphTransactions()->where('type', TransactionType::TRANSFER_FEE)->first();

            $group_transfer_fee_original_amount = 0;

            if ($group_transfer_fee) {
                $group_transfer_fee_original_amount = $group_transfer_fee->original_amount;
            }

            $transferFeeTransactions = $group->transactions()->with([
                'transactions' => function ($transaction) {
                    return $transaction->where('type', TransactionType::TRANSFER_FEE);
                }
            ])->get()->pluck('transactions')->flatten();

            $group->original_amount = $group->transactions()->sum('original_amount') + ((float)$transferFeeTransactions->sum('service_charge') + (float)$group_transfer_fee_original_amount);
            $group->amount = $group->transactions()->sum('amount') + (((float)$transferFeeTransactions->sum('service_charge') + (float)$group_transfer_fee_original_amount) / $rate) + $group->transactions()->sum('service_charge');
            $group->currency_rate = $rate;
            $group->tax = $group->transactions()->sum('tax');
            $group->service_charge = $group->transactions()->sum('service_charge');

            $group->save();

            $group->documents()->delete();

            $pdf = LaravelMpdf::loadView('pages.pdfs.currency_vendor_order', ['transactions' => $group->transactions, 'transferFeeTransactions' => $transferFeeTransactions, 'supplier' => $supplier, 'groupTransferFeeOriginalAmount' => $group_transfer_fee_original_amount]);

            $object = new DocumentObject(
                DocumentType::CURRENCY_VENDOR_ORDER,
                [chunk_split('data:application/pdf;base64,' . base64_encode($pdf->output()))],
                '',
                ApprovalStatus::COMPLETED,
                'currency_vendor_order'
            );

            /** @var Document $document */
            $document = (App()->make(CreatesDocument::class))->execute($group, $object);
            (App()->make(CreatesFiles::class))->execute($document, $object);

            Log::info("Group ID: {$group->id} updated to currency rate {$rate}");
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Update those group with currency rate more than 100. ElapsedTime: ' . $elapsedTime . '.');
    }
}
