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

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


    public function handle()
    {
        Log::info(Carbon::now() . ': Start job - Debug Billplz Failed Payment.');
        $start   = new Carbon();

        $transactions = Transaction::where('type', TransactionType::PAYMENT)->where('payment_method', PaymentMethodType::PAYMENT_GATEWAY)->whereNotIn('status', [ApprovalStatus::COMPLETED, ApprovalStatus::APPROVED])->get();

        $i = 0;
        $totalAmount = 0;
        foreach ($transactions as $transaction){
            $response = Http::withBasicAuth(config('billplz.api_key').':', '')->get(config('billplz.base_url').'/api/v3/bills/'.$transaction->payment_reference);

            // dd($response);

            if($response->successful()){
                $data = $response->json();
                if($data['paid']){
                    if (!in_array($transaction->status, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])) {
                        $this->returnLog('Paid transaction', $transaction);
                    }
                }
                // else {
                //     $totalAmount += $transaction->amount;
                //     $this->returnLog('Unpaid Transaction', $transaction);
                // }
            }else{
                $this->returnLog('billplz error', $transaction);
            }
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');
        Log::info(Carbon::now() . ': End job - Debug Billplz Failed Payment. ElapsedTime: ' . $elapsedTime . '.');
    }

    public function returnLog($text, $transaction) {
        $approvalStatusArray = ApprovalStatus::APPROVAL_STATUS_ID;
        Log::info($text . ' - id: '. $transaction->id . '. Booking Marking: '. $transaction->owner->marking . ' - Date: '.$transaction->created_at->format('d-m-Y').' - Amount: '. $transaction->amount . '. Current Status: ' . $approvalStatusArray[$transaction->status]);
    }
}
