<?php

/**
 * 文件功能：VIP 会员支付订单模型
 * 负责记录聊天室用户购买 VIP 时的本地订单、远端支付单号与开通结果
 * 通过本地订单可串联下单、回调、会员开通与后台查询链路
 */

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class VipPaymentOrder extends Model
{
    use HasFactory;

    /** @var string 表名 */
    protected $table = 'vip_payment_orders';

    /** @var array<int, string> 可批量赋值字段 */
    protected $fillable = [
        'order_no',
        'merchant_order_no',
        'user_id',
        'vip_level_id',
        'status',
        'amount',
        'subject',
        'payment_order_no',
        'provider',
        'provider_trade_no',
        'vip_name',
        'vip_duration_days',
        'sync_return_payload',
        'async_notify_payload',
        'paid_at',
        'opened_vip_at',
        'meta',
    ];

    /**
     * 属性类型转换
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
            'vip_duration_days' => 'integer',
            'sync_return_payload' => 'array',
            'async_notify_payload' => 'array',
            'meta' => 'array',
            'paid_at' => 'datetime',
            'opened_vip_at' => 'datetime',
        ];
    }

    /**
     * 关联：支付订单所属用户
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    /**
     * 关联：支付订单对应的 VIP 等级
     */
    public function vipLevel(): BelongsTo
    {
        return $this->belongsTo(VipLevel::class, 'vip_level_id');
    }

    /**
     * 判断订单是否已经完成支付
     */
    public function isPaid(): bool
    {
        return $this->status === 'paid';
    }

    /**
     * 判断订单是否已经完成会员开通
     */
    public function isVipOpened(): bool
    {
        return $this->opened_vip_at !== null;
    }
}
