<?php

namespace App\Models;

use App\Scopes\InstancedModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;

/**
 * @property string $name
 * @property string $type
 * @property string $billing_deadline
 * @property string $distance_allowance
 * @property boolean $mail_on_new
 * @property boolean $allow_new
 * @property boolean $archived
 * @property Tenant $tenant
 */
class CostUnit extends InstancedModel
{
    protected $fillable = [
        'name',
        'tenant',
        'type',
        'billing_deadline',
        'distance_allowance',
        'mail_on_new',
        'allow_new',
        'archived',
    ];

    public function treasurers()  : BelongsToMany{
        return $this->belongsToMany(User::class, 'cost_unit_treasurers', 'cost_unit_id', 'user_id')
            ->withTimestamps();
    }

    public function resetTreasurers() {
        $this->treasurers()->detach();
        $this->save();
    }

    public function invoices() : hasMany {
        return $this->hasMany(Invoice::class);
    }

    public function estimates() : hasMany {
        return $this->hasMany(CostUnitEstimate::class);
    }

    public function tenant() : BelongsTo {
        return $this->belongsTo(Tenant::class, 'tenant', 'slug');
    }

    public function event() : HasOne {
        return $this->hasOne(Event::class);
    }
}
