<?php

namespace App\Support;

use App\Models\Order;
use Illuminate\Support\Facades\Schema;

class PaymentFailure
{
    public static function flash(string $reason): void
    {
        session()->flash('payment_failure_reason', $reason);
    }

    public static function markOrderFailed(Order $order, string $reason): Order
    {
        self::flash($reason);

        $update = ['status' => Order::$fail];

        if (Schema::hasColumn('orders', 'payment_failure_reason')) {
            $update['payment_failure_reason'] = $reason;
        }

        $order->update($update);

        return $order->refresh();
    }

    public static function resolveReason(?Order $order = null): ?string
    {
        $sessionReason = session('payment_failure_reason');
        if (is_string($sessionReason) && trim($sessionReason) !== '') {
            return trim($sessionReason);
        }

        if ($order && Schema::hasColumn('orders', 'payment_failure_reason')) {
            $dbReason = $order->payment_failure_reason ?? null;
            if (is_string($dbReason) && trim($dbReason) !== '') {
                return trim($dbReason);
            }
        }

        return null;
    }
}
