<?php

declare(strict_types=1);


namespace Plugins\Neatstudio\Payment\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class Payment extends Model
{
    protected $fillable = [
        'order_no', 'user_id', 'subject', 'description', 'amount', 'channel', 'status', 'gateway_trade_no', 'payload', 'paid_at',
        'payable_type', 'payable_id',
    ];

    protected $casts = [
        'payload' => 'array',
        'paid_at' => 'datetime',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 可购买实体：文章（单篇解锁）、会员套餐、皮肤等。
     */
    public function payable(): MorphTo
    {
        return $this->morphTo();
    }

    public function getPayableLabelAttribute(): string
    {
        $payable = $this->payable;

        if (! $payable) {
            return '—';
        }

        if (method_exists($payable, 'payableLabel')) {
            return $payable->payableLabel();
        }

        return $payable->title ?? $payable->name ?? ('#'.$payable->getKey());
    }

    public function getPayableUrlAttribute(): ?string
    {
        $payable = $this->payable;

        if (! $payable || ! method_exists($payable, 'payableUrl')) {
            return null;
        }

        return $payable->payableUrl();
    }

    public function markPaid(string $gatewayTradeNo = null): void
    {
        $this->update([
            'status' => 'paid',
            'gateway_trade_no' => $gatewayTradeNo,
            'paid_at' => now(),
        ]);

        app(\App\Blog\Support\PluginManager::class)->doAction('payment.paid', $this);
    }
}
