<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Carbon\Carbon;

#[Fillable(['name', 'email', 'password', 'avatar', 'daily_banker_ends_at', 'vip_master_ends_at', 'ht_draw_ends_at', 'is_admin', 'fcm_token'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable  // Email verification is optional — implements MustVerifyEmail only if needed
{
    /** @use HasFactory<UserFactory> */
    use HasFactory, Notifiable, HasApiTokens;

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at'       => 'datetime',
            'password'                => 'hashed',
            'daily_banker_ends_at'    => 'datetime',
            'vip_master_ends_at'      => 'datetime',
            'ht_draw_ends_at'         => 'datetime',
            'is_admin'                => 'boolean',
        ];
    }


    // ─── Relationships ────────────────────────────────────────────────────────

    public function subscriptions(): HasMany
    {
        return $this->hasMany(UserSubscription::class);
    }

    /** Only subscriptions that are currently active and not expired. */
    public function activeSubscriptions(): HasMany
    {
        return $this->hasMany(UserSubscription::class)
            ->where('status', 'active')
            ->where('ends_at', '>', Carbon::now());
    }

    // ─── Helpers ──────────────────────────────────────────────────────────────

    /**
     * Check whether the user has an active subscription for a given VIP package.
     * Uses the pre-loaded activeSubscriptions relation if available (avoids N+1).
     */
    public function hasActiveSubscriptionFor(int $packageId): bool
    {
        if ($this->relationLoaded('activeSubscriptions')) {
            return $this->activeSubscriptions
                ->contains('vip_package_id', $packageId);
        }

        return $this->subscriptions()
            ->where('vip_package_id', $packageId)
            ->where('status', 'active')
            ->where('ends_at', '>', Carbon::now())
            ->exists();
    }
}
