<?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\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Http;

class CheckDeletedInvoiceButPaid extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check-deleted-paid-invoice';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check all deleted invoice but has completed payment';

    /**
     * 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'); 

        $this->info(Carbon::now() . ' : Start Check all deleted invoice but has completed payment.');
        $start   = new Carbon();

        $totalAmount = 0;

        $softDeletedTransactions = Transaction::onlyTrashed()->where('type', TransactionType::SHIPPING_INVOICE)->whereHas('transactions', function (Builder $query) {
            $query->where('type', TransactionType::PAYMENT)->where('payment_method', PaymentMethodType::PAYMENT_GATEWAY);
        })->get();

        foreach ($softDeletedTransactions as $invoice) {
            $invoice_payments = $invoice->transactions()->payments()->get();

            foreach($invoice_payments as $invoice_payment) {

                $response = Http::withBasicAuth(config('billplz.api_key').':', '')->get(config('billplz.base_url').'/api/v3/bills/'.$invoice_payment->payment_reference);
    
                if($response->successful()){
                    $data = $response->json();

                    $orderReference = $invoice->owner->owner->reference ?? null;

                    if($data['paid']){
                        $this->info('Invoice id: ' . $invoice->id. '. Payment id: ' . $invoice_payment->id . '. Order: ' . $orderReference);
                    } else {
                       
                    }
                }else{
                    $this->info("billplz error</br>");
                }
            }
        }

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

        $this->info(Carbon::now() . ' : Done Check all deleted invoice but has completed payment. ElapsedTime: ' . $elapsedTime . '. Total: ' . $totalAmount);
    }
}
