<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class Soggetto extends Model
{
    use HasFactory;

    protected $table = 'soggetti';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'old_id',
        'nome',
        'cognome',
        'ragione_sociale',
        'codice_fiscale',
        'partita_iva',
        'email',
        'telefono',
        'indirizzo',
        'cap',
        'citta',
        'provincia',
        'tipo',
        'codice_univoco',
    ];

    /**
     * The units that belong to the subject.
     */
     
    public function ticketsRichiesti(): HasMany
    {
        return $this->hasMany(Ticket::class, 'soggetto_richiedente_id', 'id');
    }

    public function rateEmessaResponsabile(): HasMany
    {
        return $this->hasMany(RataEmessa::class, 'id_soggetto_responsabile', 'id');
    }

    public function proprieta() {
        return $this->hasMany(Proprieta::class);
    }

    protected static function booted()
    {
        static::creating(function ($soggetto) {
            if (empty($soggetto->codice_univoco)) {
                do {
                    $code = Str::upper(Str::random(8));
                } while (self::where('codice_univoco', $code)->exists());
                $soggetto->codice_univoco = $code;
            }
        });
    }
}