<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class UserLogin extends Model
{
    use HasFactory;

    
    protected $fillable = [
        'user_id', 
        'ip_address', 
        'user_agent', 
        'location', 
        'status' 
    ];

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

    
    public function setStatusAttribute($value)
    {
        $this->attributes['status'] = strtolower($value);
    }

    
    public function getCreatedAtFormattedAttribute()
    {
        return $this->created_at->format('d M Y H:i:s');
    }

    /**
     * @param int $userId
     * @param string $status
     * @param string|null $location
     * @param string|null $ipAddress
     * @param string|null $userAgent
     */
    public static function record(
        int $userId, 
        string $status = 'success', 
        string $location = null, 
        string $ipAddress = null, 
        string $userAgent = null
    ) {
        self::create([
            'user_id' => $userId,
            'status' => $status,
            'location' => $location,
            'ip_address' => $ipAddress ?? request()->ip(),
            'user_agent' => $userAgent ?? request()->userAgent(),
        ]);
    }


    public function scopeLatestLogins($query, $limit = 10)
    {
        return $query->latest()->limit($limit);
    }

    
    public static function detectLocation()
    {
        if (class_exists(\Stevebauman\Location\Facades\Location::class)) {
            $location = \Location::get(request()->ip());
            return $location ? $location->cityName . ', ' . $location->countryName : null;
        }
        return null;
    }
}

