<?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\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Wallet;
use Illuminate\Support\Facades\Log;

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


    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Audit and Update Wallet Balance.');
        $start   = new Carbon();

        $wallets = Wallet::all();

        $i = 0;
        foreach ($wallets as $wallet) {
            $topups = 0;
            $credit = 0;
            $payments = 0;
            $debit = 0;

            foreach ($wallet->transactions as $transaction) {
                if (!in_array((int) $transaction->status, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])) continue;
                if ((int) $transaction->type === TransactionType::TOP_UP) {
                    $topups += (float) $transaction->amount;
                }
                if ((int) $transaction->type === TransactionType::CREDIT_NOTE) $credit += (float) $transaction->amount;
                if ((int) $transaction->type === TransactionType::PAYMENT) $payments += (float) $transaction->amount;
                if ((int) $transaction->type === TransactionType::DEBIT_NOTE) $debit += (float) $transaction->amount;
            }
            $auditBalance = ($topups + $credit) - ($payments + $debit);
            $diffenrence = round((float) $wallet->amount - (($topups + $credit) - ($payments + $debit)), 2);
            if ((($diffenrence == 0) || ($diffenrence == -0)) and $wallet->amount > -0.01) continue;

            $i++;

            Log::info($i . ". Marking: " . $wallet->owner->reference . "(" . $wallet->id . ")" . PHP_EOL . "Current Balance: " . $wallet->amount . PHP_EOL . "Audit Balance: " . ($auditBalance) . PHP_EOL . "Difference: " . $diffenrence . PHP_EOL);

            Wallet::where('id', $wallet->id)->update(['amount' => $auditBalance]);
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Audit and Update Wallet Balance. ElapsedTime: ' . $elapsedTime . '.');
    }
}
