<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PowerDnsChangelog extends Model
{
    protected $table = 'powerdns_changelog';

    protected $fillable = [
        'zone_name',
        'record_name',
        'record_type',
        'old_content',
        'new_content',
        'old_ttl',
        'new_ttl',
        'old_disabled',
        'new_disabled',
        'action',
        'user_id',
        'ip_address',
        'user_agent',
    ];

    protected $casts = [
        'old_disabled' => 'boolean',
        'new_disabled' => 'boolean',
    ];

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

    /**
     * Scope pentru filtrarea după zonă și înregistrare
     */
    public function scopeForRecord($query, $zoneName, $recordName)
    {
        // Gestionează atât numele cu punct la sfârșit cât și fără punct
        $recordNameWithDot = rtrim($recordName, '.') . '.';
        $recordNameWithoutDot = rtrim($recordName, '.');
        $zoneNameWithDot = rtrim($zoneName, '.') . '.';
        $zoneNameWithoutDot = rtrim($zoneName, '.');

        return $query->where(function ($q) use ($zoneNameWithDot, $zoneNameWithoutDot) {
                        $q->where('zone_name', $zoneNameWithDot)
                          ->orWhere('zone_name', $zoneNameWithoutDot);
                    })
                    ->where(function ($q) use ($recordNameWithDot, $recordNameWithoutDot) {
                        $q->where('record_name', $recordNameWithDot)
                          ->orWhere('record_name', $recordNameWithoutDot);
                    });
    }

    /**
     * Scope pentru filtrarea după utilizator
     */
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }
}
