<?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\ValueObjects\Constants\ApprovalStatus;
use App\Models\Booking;
use App\Models\Transaction;
use Illuminate\Console\Command;

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


    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Update those payment reference that actually should be showing partially refund instead of fully refund.');
        $start   = new Carbon();

        $transactions = Transaction::where('payment_reference', 'LIKE', '%Fully Refund%')->whereDate('created_at', '>=', Carbon::createFromDate(2024, 4, 2))->get();

        foreach ($transactions as $transaction) {
            $booking_marking = trim(explode('.', $transaction->payment_reference)[1]);
            $booking = Booking::where('marking', $booking_marking)->first();

            if ($booking) {
                $payments = $booking->transactions()->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED, ApprovalStatus::REFUNDED])->get();

                if ($payments->count() === 0) {
                    Log::info("Booking ID: {$booking->id}, payment not found");
                } else if ($payments->count() > 1) {
                    Log::info("Booking ID: {$booking->id}, more than 1 payment found");
                } else {
                    $payment = $payments->first();

                    if (!($payment->amount - $transaction->amount < 0.01)) {
                        $transaction->payment_reference = str_replace('Fully', 'Partially', $transaction->payment_reference);
                        $transaction->save();
                        Log::info("Updated Payment Reference of Transaction ID: {$transaction->id}, corrected from Fully Refund to Partially Refund");
                    }
                }
            }
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Update those payment reference that actually should be showing partially refund instead of fully refund. ElapsedTime: ' . $elapsedTime . '.');
    }
}
