<?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 Spatie\Permission\Traits\HasRoles;
use Spatie\Permission\Models\Permission;
use Carbon\Carbon;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasRoles;

    protected $fillable = [
        'device_id',
        'name',
        'email',
        'phone',
        'imei',
        'otp',
        'expires_at',
        'is_verified',
        'login_mode',
        'profile_image',
        'status',
        'password',
        'is_trial',
        'trial_expires_at'
    ];

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

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
        ];
    }

    // Roles and Permissons
    public static function getPermissionGroups()
    {
        $permissionGroups = Permission::select('group_name as name', \DB::raw('MIN(id) as id'))
            ->groupBy('group_name')
            ->orderBy('id', 'asc')
            ->get();

        return $permissionGroups;
    }

    public static function getPermissionsByGroupName($groupName)
    {
        $permissions = Permission::select('name', 'id')
            ->where('group_name', $groupName)
            ->get();

        return $permissions;
    }

    public static function roleHasAllPermissions($role, $permissions)
    {
        $hasAllPermissions = true;

        foreach ($permissions as $permission) {
            if (!$role->hasPermissionTo($permission->name)) {
                $hasAllPermissions = false;
                return $hasAllPermissions;
            }
        }

        return $hasAllPermissions;
    }

    public function isExpired()
    {
        return Carbon::now()->greaterThan($this->expires_at);
    }

    // Relations
    public function userPackageDetails()
    {
        return $this->hasOne(UserPackage::class, 'user_id');
    }

    // New relationships
    public function connectionLogs()
    {
        return $this->hasMany(ConnectionLog::class);
    }

    public function activeConnections()
    {
        return $this->hasMany(ConnectionLog::class)
            ->whereNull('disconnected_at');
    }

    // New methods for license management
    public function isBlocked()
    {
        return in_array($this->status, ['blocked', 'banned', 'suspended']);
    }

    public function isTrialValid()
    {
        if (!$this->is_trial) return false;
        return !Carbon::now()->greaterThan($this->trial_expires_at);
    }

    public function hasActiveConnection()
    {
        return $this->activeConnections()->exists();
    }

    public function canConnect()
    {
        if ($this->isBlocked()) return false;
        if ($this->hasActiveConnection()) return false;
        return $this->isTrialValid() || !$this->isExpired();
    }
}
