<?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 Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

class debugBillplzFailedPayment extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'billplz-failed-payment:debug';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $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);
            }
        }
    }

    public function returnLog($text, $transaction) {
        $approvalStatusArray = ApprovalStatus::APPROVAL_STATUS_ID;
        $this->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]);
    }
}
