<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class TopspenderReward extends Model
{
    protected $table = 'topspender_rewards';

    protected $fillable = [
        'month',
        'year',
        'rank',
        'item_id',
        'item_name',
        'item_count',
        'protect_type',
        'octet',
        'mask',
        'mail_message',
        'is_active',
        'created_by',
    ];

    protected $casts = [
        'month' => 'integer',
        'year' => 'integer',
        'rank' => 'integer',
        'item_id' => 'integer',
        'item_count' => 'integer',
        'protect_type' => 'integer',
        'octet' => 'integer',
        'mask' => 'integer',
        'is_active' => 'boolean',
    ];

    /**
     * Get claims for this reward
     */
    public function claims(): HasMany
    {
        return $this->hasMany(TopspenderClaim::class, 'reward_id');
    }

    /**
     * Get the admin who created this reward
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by', 'ID');
    }

    /**
     * Get rewards for a specific month/year
     */
    public static function getRewardsForPeriod(int $month, int $year)
    {
        return self::where('month', $month)
            ->where('year', $year)
            ->orderBy('rank')
            ->get();
    }

    /**
     * Get reward for specific rank in a period (only active rewards for claiming)
     */
    public static function getRewardForRank(int $month, int $year, int $rank, bool $onlyActive = true)
    {
        $query = self::where('month', $month)
            ->where('year', $year)
            ->where('rank', $rank);
        
        if ($onlyActive) {
            $query->where('is_active', true);
        }
        
        return $query->first();
    }

    /**
     * Check if active rewards exist for a period
     */
    public static function hasRewardsForPeriod(int $month, int $year): bool
    {
        return self::where('month', $month)
            ->where('year', $year)
            ->where('is_active', true)
            ->exists();
    }

    /**
     * Get auto-generated mail title
     */
    public function getMailTitleAttribute(): string
    {
        $monthName = date('F', mktime(0, 0, 0, $this->month, 1));
        return "Top Spender Reward - Rank #{$this->rank} ({$monthName} {$this->year})";
    }

    /**
     * Get rank label
     */
    public function getRankLabelAttribute(): string
    {
        return match ($this->rank) {
            1 => '🥇 Rank #1',
            2 => '🥈 Rank #2',
            3 => '🥉 Rank #3',
            default => "Rank #{$this->rank}",
        };
    }

    /**
     * Get month name
     */
    public function getMonthNameAttribute(): string
    {
        return date('F', mktime(0, 0, 0, $this->month, 1));
    }
}
