<?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\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Booking;

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


    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Change the EXPIRED payment transaction of EXPIRED booking to REFUNDED if the payment transaction is fully refunded.');
        $start   = new Carbon();

        $bookings = Booking::where('status', ApprovalStatus::EXPIRED)->whereHas('transactions', function ($q) {
            $q->where('type', TransactionType::PAYMENT)->where('status', ApprovalStatus::EXPIRED)->whereHas('transactions', function ($q2) {
                $q2->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
            });
        })->get();

        foreach ($bookings as $booking) {
            $payment_transactions = $booking->transactions()->where('type', TransactionType::PAYMENT)->whereHas('transactions', function ($q2) {
                $q2->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED]);
            })->get();

            foreach ($payment_transactions as $payment) {
                $payment_original_amount = $payment->original_amount;
                $refund_original_amount = $payment->transactions()->where('type', TransactionType::REFUND)->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])->sum('original_amount');

                if ($payment_original_amount - $refund_original_amount < 0.01) {
                    Log::info("Updated booking id: $booking->id, payment transaction id: $payment->id, from EXPIRED to REFUNDED");

                    $payment->status = ApprovalStatus::REFUNDED;
                    $payment->save();
                }
            }
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Change the EXPIRED payment transaction of EXPIRED booking to REFUNDED if the payment transaction is fully refunded. ElapsedTime: ' . $elapsedTime . '.');
    }
}
