<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class DynamicDnsClient extends Model
{
    protected $fillable = [
        'user_id',
        'dns_zone_id',
        'hostname',
        'token',
        'current_ip',
        'last_ip',
        'last_update',
        'update_count',
        'is_active',
        'notify_on_change',
        'ttl',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'notify_on_change' => 'boolean',
        'last_update' => 'datetime',
    ];

    /**
     * Generate unique token
     */
    public static function generateToken(): string
    {
        return Str::random(64);
    }

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

    /**
     * DNS Zone relationship
     */
    public function dnsZone()
    {
        return $this->belongsTo(DnsZone::class);
    }

    /**
     * Relație cu log-urile de actualizare
     */
    public function updateLogs()
    {
        return $this->hasMany(DynamicDnsUpdateLog::class);
    }

    /**
     * Get the update URL
     */
    public function getUpdateUrl(): string
    {
        return route('api.dyndns.update', [
            'token' => $this->token,
            'hostname' => $this->hostname,
        ]);
    }

    /**
     * Get time since last update
     */
    public function getTimeSinceUpdate(): ?string
    {
        if (!$this->last_update) {
            return 'Niciodată';
        }

        return $this->last_update->diffForHumans();
    }

    /**
     * Check if IP has changed
     */
    public function hasIpChanged(string $newIp): bool
    {
        return $this->current_ip !== $newIp;
    }

    /**
     * Update IP
     */
    public function updateIp(string $newIp): void
    {
        $this->last_ip = $this->current_ip;
        $this->current_ip = $newIp;
        $this->last_update = now();
        $this->update_count++;
        $this->save();
    }

    /**
     * Scope: Active clients only
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
