<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
// use Laravel\Sanctum\HasApiTokens; // <-- تم تعطيل هذا السطر
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Laravel\Sanctum\HasApiTokens;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
    // use HasApiTokens, HasFactory, Notifiable; // <-- تم تعطيل هذا واستبداله بالتالي:
    use HasRoles;
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'credits',
        'package_id',
        'subscription_ends_at',
    ];

    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
        'subscription_ends_at' => 'date',
    ];

    public function package(): BelongsTo
    {
        return $this->belongsTo(Package::class);
    }

    public function hasActiveSubscription()
    {
        return $this->package_id && $this->subscription_ends_at && $this->subscription_ends_at->isFuture();
    }

    public function hasFeature($featureName)
    {
        if (!$this->hasActiveSubscription()) return false;
        return (bool) $this->package->{$featureName};
    }

    public function checkQuota($limitName, $currentUsage)
    {
        if (!$this->hasActiveSubscription()) return false;
        $limit = $this->package->{$limitName};
        if ($limit == 0) return true;
        return $currentUsage < $limit;
    }

    protected static function booted()
    {
        static::created(function ($user) {
            $freePackage = \App\Models\Package::where('price', 0)->first();
            if ($freePackage) {
                $user->update([
                    'package_id' => $freePackage->id,
                    'credits' => $freePackage->limit_messages,
                    'subscription_ends_at' => now()->addDays($freePackage->duration_days),
                ]);
            }
        });
    }
}