<?php

namespace App\Models;

use App\Support\DocumentNumberHelper;
use Illuminate\Database\Eloquent\Model;

class Matter extends Model
{
    protected $fillable = [
        'matter_number',
        'matter_title',
        'category_id',
        'type_id',
        'status_id',
        'priority_id',
        'description',
        'opened_date',
        'closed_date',
        'created_by',
        'updated_by',
    ];

    protected static function booted()
    {
        static::creating(function (Matter $matter) {
            if (empty($matter->matter_number)) {
                $matter->matter_number = DocumentNumberHelper::nextMatterNumber();
            }
        });
    }

    public function type()
    {
        return $this->belongsTo(MatterType::class, 'type_id');
    }

    public function category()
    {
        return $this->belongsTo(MatterCategory::class, 'category_id');
    }

    public function status()
    {
        return $this->belongsTo(MatterStatus::class, 'status_id');
    }

    public function priority()
    {
        return $this->belongsTo(MatterPriority::class, 'priority_id');
    }

    public function clients()
    {
        return $this->belongsToMany(Client::class, 'matter_clients', 'matter_id', 'client_id')
            ->withPivot(['role_id', 'is_primary_client', 'created_by', 'updated_by'])
            ->withTimestamps();
    }

    public function trustAccounts()
    {
        return $this->belongsToMany(TrustAccount::class, 'trust_account_matters', 'matter_id', 'trust_account_id')
            ->withTimestamps();
    }

    public function lawyers()
    {
        return $this->belongsToMany(User::class, 'matter_lawyers', 'matter_id', 'lawyer_id')
            ->withPivot(['role_id', 'is_lead_lawyer', 'created_by', 'updated_by'])
            ->withTimestamps();
    }

    public function case()
    {
        return $this->hasOne(LegalCase::class, 'matter_id', 'id');
    }

    public function cases()
    {
        return $this->hasMany(LegalCase::class, 'matter_id', 'id');
    }
}
