<?php

namespace App\Console\Commands;


use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\PaymentMethodType;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class ShowFailediBllplzCallback extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'show-failed-billplz-callback';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Show all failled callback from billplz';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        ini_set('memory_limit', '-1');

        $start   = new Carbon();

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

        if ($totalTransactions) {
            $this->info(Carbon::now() . ' : ' . $this->description);
        }

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

            if($response->successful()){
                $data = $response->json();
                if($data['paid']){
                    dump($transaction->payment_reference);
                    dump($transaction->id);
                }
            }else{
                $this->info("billplz error</br>");
            }
            $counter++;
        }

        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');

        if ($totalTransactions) {
            $this->info(Carbon::now() . ' : Done Billplz Failled Callback. ElapsedTime: ' . $elapsedTime . '. Total: ' . $totalAmount);
        }

    }
}
