<?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 AuditBillplzInvoice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'billplz-invoice:audit';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check all unpaid invoice but marked paid at our system';

    /**
     * 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() . ' : Audit Billplz Invoice cron started.');
        $start   = new Carbon();

        $transactions = Transaction::where('type', TransactionType::SHIPPING_INVOICE)->where('status', ApprovalStatus::COMPLETED)->whereHas('transactions', function($query){
            return $query->where('type', TransactionType::PAYMENT)->where('payment_method', PaymentMethodType::PAYMENT_GATEWAY)->where('status', ApprovalStatus::REJECTED);
        })->get();

        $totalTransactions = count($transactions);
        $counter = 1;
        $totalAmount = 0;
        foreach ($transactions as $transaction){
            $payment_transaction = $transaction->transactions->sortByDesc('created_at')->first();

            if ($payment_transaction->status === ApprovalStatus::REJECTED) {
                $this->info($counter . ' of ' . $totalTransactions . '. Order Marking: '. $payment_transaction->owner->owner->owner->reference . '. Transaction Id: '. $payment_transaction->id . '. Invoice Id: '. $transaction->id . ' - Date: '.$payment_transaction->created_at->format('d-m-Y').' - Amount: '. $payment_transaction->amount);
    
                $totalAmount += $transaction->amount;
                
                $counter++;
            }
        }
    
        $end = new Carbon();
        $elapsedTime = $start->diff($end)->format('%H:%I:%S');

        $this->info(Carbon::now() . ' : Done Audit Billplz. ElapsedTime: ' . $elapsedTime . '. Total: ' . $totalAmount);
    }
}
