<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Proclamatore extends Model
{
    use SoftDeletes, LogsActivity;

    protected $table = 'proclamatori';

    protected $fillable = ['nome', 'cognome', 'attivo'];

    protected function casts(): array
    {
        return [
            'nome' => 'encrypted',
            'cognome' => 'encrypted',
            'attivo' => 'boolean',
        ];
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['attivo']) // Do NOT log nome/cognome in audit (encrypted, GDPR)
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }

    /**
     * Full name (decrypted, only visible in PHP/UI).
     */
    public function getNomeCompletoAttribute(): string
    {
        return trim($this->cognome . ' ' . $this->nome);
    }

    public function assegnazioni()
    {
        return $this->hasMany(Assegnazione::class, 'proclamatore_id');
    }

    public function assegnazioniAperte()
    {
        return $this->hasMany(Assegnazione::class, 'proclamatore_id')
            ->whereNull('returned_at');
    }

    public function scopeAttivi($query)
    {
        return $query->where('attivo', true);
    }

    /**
     * Anonymize this proclamatore (GDPR right to be forgotten).
     */
    public function anonimizza(): void
    {
        $this->nome = 'Anonimo';
        $this->cognome = 'Proclamatore #' . $this->id;
        $this->attivo = false;
        $this->save();
        $this->delete(); // soft delete
    }
}
