<?php

namespace App\Console\Commands;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\Booking;
use App\Models\Transaction;
use Illuminate\Console\Command;
use Carbon\Carbon;

class UpdateWrongFullyRefundPaymentReference extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'payment-reference:update-wrong-fully-refund';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update those payment reference that actually should be showing partially refund instead of fully refund';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $transactions = Transaction::where('payment_reference', 'LIKE', '%Fully Refund%')->whereDate('created_at', '>=', Carbon::createFromDate(2024, 4, 2))->get();

        foreach ($transactions as $transaction) {
            $booking_marking = trim(explode('.', $transaction->payment_reference)[1]);
            $booking = Booking::where('marking', $booking_marking)->first();

            if ($booking) {
                $payments = $booking->transactions()->payments()->whereIn('status', [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED, ApprovalStatus::REFUNDED])->get();

                if ($payments->count() === 0) {
                    $this->info("Booking ID: {$booking->id}, payment not found");
                } else if ($payments->count() > 1) {
                    $this->info("Booking ID: {$booking->id}, more than 1 payment found");
                } else {
                    $payment = $payments->first();

                    if (!($payment->amount - $transaction->amount < 0.01)) {
                        $transaction->payment_reference = str_replace('Fully', 'Partially', $transaction->payment_reference);
                        $transaction->save();
                        $this->info("Updated Payment Reference of Transaction ID: {$transaction->id}, corrected from Fully Refund to Partially Refund");
                    }
                }
            }
        }
    }
}
