<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class UserDevice extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'device_id',
        'fcm_token',
        'platform',
        'ip_country',
        'last_ip',
        'app_version',
    ];

    // Relations
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // Scopes
    public function scopeByPlatform($query, $platform)
    {
        return $query->where('platform', $platform);
    }

    public function scopeByCountry($query, $country)
    {
        return $query->where('ip_country', $country);
    }

    public function scopeWithFcmToken($query)
    {
        return $query->whereNotNull('fcm_token');
    }

    public function scopeActive($query, $days = 30)
    {
        return $query->where('updated_at', '>=', now()->subDays($days));
    }

    // Helper Methods
    public function updateLastSeen($ip = null)
    {
        $data = ['updated_at' => now()];
        
        if ($ip) {
            $data['last_ip'] = $ip;
        }
        
        $this->update($data);
    }

    public function updateFcmToken($token)
    {
        $this->update(['fcm_token' => $token]);
    }

    public function isActive($days = 30)
    {
        return $this->updated_at >= now()->subDays($days);
    }
}