<?php

namespace App\Models;

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

class TopspenderClaim extends Model
{
    protected $table = 'topspender_claims';

    protected $fillable = [
        'user_id',
        'month',
        'year',
        'rank',
        'role_id',
        'role_name',
        'reward_id',
        'claimed_at',
        'mail_sent',
    ];

    protected $casts = [
        'month' => 'integer',
        'year' => 'integer',
        'rank' => 'integer',
        'user_id' => 'integer',
        'role_id' => 'integer',
        'reward_id' => 'integer',
        'claimed_at' => 'datetime',
        'mail_sent' => 'boolean',
    ];

    /**
     * Get the reward associated with this claim
     */
    public function reward(): BelongsTo
    {
        return $this->belongsTo(TopspenderReward::class, 'reward_id');
    }

    /**
     * Get the user who claimed
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'ID');
    }

    /**
     * Check if user has already claimed for a period
     */
    public static function hasUserClaimed(int $userId, int $month, int $year): bool
    {
        return self::where('user_id', $userId)
            ->where('month', $month)
            ->where('year', $year)
            ->exists();
    }

    /**
     * Get claim for user in a period
     */
    public static function getUserClaim(int $userId, int $month, int $year)
    {
        return self::where('user_id', $userId)
            ->where('month', $month)
            ->where('year', $year)
            ->first();
    }

    /**
     * Get claims for a period
     */
    public static function getClaimsForPeriod(int $month, int $year)
    {
        return self::with(['user', 'reward'])
            ->where('month', $month)
            ->where('year', $year)
            ->orderBy('rank')
            ->get();
    }

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

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