<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use app\Models\SRO_VT_ACCOUNT\TbUser;

class RechargeReward extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'recharge_transaction_id',
        'reward_setting_id',
        'reward_type',
        'reward_name',
        'reward_value',
        'reward_description',
        'status',
        'expires_at',
        'claimed_at'
    ];

    protected $casts = [
        'reward_value' => 'decimal:2',
        'expires_at' => 'datetime',
        'claimed_at' => 'datetime'
    ];

    /**
     * Get the user who received the reward
     */
    public function user()
    {
        return $this->belongsTo(TbUser::class);
    }

    /**
     * Get the related transaction
     */
    public function transaction()
    {
        return $this->belongsTo(RechargeTransaction::class, 'recharge_transaction_id');
    }

    /**
     * Get the reward setting
     */
    public function rewardSetting()
    {
        return $this->belongsTo(RechargeRewardsSetting::class, 'reward_setting_id');
    }

    /**
     * Get pending rewards for a user
     */
    public static function getPendingRewardsForUser($userId)
    {
        return self::where('user_id', $userId)
                   ->where('status', 'pending')
                   ->where(function($query) {
                       $query->whereNull('expires_at')
                             ->orWhere('expires_at', '>', now());
                   })
                   ->with('rewardSetting')
                   ->orderBy('created_at', 'desc')
                   ->get();
    }

    /**
     * Get reward history for a user
     */
    public static function getRewardHistoryForUser($userId)
    {
        return self::where('user_id', $userId)
                   ->with(['rewardSetting', 'transaction'])
                   ->orderBy('created_at', 'desc')
                   ->get();
    }

    /**
     * Mark reward as claimed
     */
    public function markAsClaimed()
    {
        $this->update([
            'status' => 'claimed',
            'claimed_at' => now()
        ]);
    }

    /**
     * Check if reward is expired
     */
    public function isExpired()
    {
        return $this->expires_at && $this->expires_at->isPast();
    }

    /**
     * Get formatted reward display
     */
    public function getFormattedRewardAttribute()
    {
        switch ($this->reward_type) {
            case 'diamonds':
                return '💎 ' . number_format($this->reward_value) . ' Diamonds';
            case 'vip_days':
                return '👑 ' . $this->reward_value . ' VIP Days';
            case 'bonus_percentage':
                return '⚡ +' . $this->reward_value . '% Bonus';
            default:
                return $this->reward_name;
        }
    }
}
