<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Client extends Model
{
    protected $fillable = [
        'type', 
        'category',
    ];

    // Auto-append name and full_name attributes to output
    protected $appends = ['name', 'full_name'];

    /*
    |--------------------------------------------------------------------------
    | Relationships
    |--------------------------------------------------------------------------
    */
public function location()
{
    return $this->belongsTo(Location::class, 'location_id', 'id');
}

    public function person()
    {
        return $this->hasOne(Person::class, 'client_id', 'id');
    }

    public function organization()
    {
        return $this->hasOne(Organization::class, 'client_id', 'id');
    }

    public function account()
    {
        return $this->hasOne(Account::class, 'client_id', 'id');
    }

    public function creditRequests()
    {
        return $this->hasMany(CreditRequest::class, 'client_id', 'id');
    }

    public function scheduledVisits()
    {
        return $this->hasMany(ScheduledVisit::class, 'client_id', 'id');
    }

    /*
    |--------------------------------------------------------------------------
    | Accessors
    |--------------------------------------------------------------------------
    */

    public function getNameAttribute()
    {
        if ($this->type === 'person' && $this->person) {
            return $this->person->first_name . ' ' . $this->person->last_name;
        }

        if ($this->type === 'organization' && $this->organization) {
            return $this->organization->company_name;
        }

        return 'Unnamed Client';
    }

    public function getFullNameAttribute()
    {
        if ($this->type === 'person' && $this->person) {
            return $this->person->first_name . ' ' . $this->person->last_name;
        }

        if ($this->type === 'organization' && $this->organization) {
            return $this->organization->company_name ?: 'Unnamed Organization';
        }

        return 'Unnamed Client';
    }


    public function creditSeedMonitorings()
    {
        return $this->hasMany(CreditSeedMonitoring::class, 'farmer_id');
    }

    public function clientDocuments()
{
    return $this->hasMany(ClientDocument::class, 'client_id');
}

}
