<?php

namespace App\Models\Bussiness;

use App\Models\Administration\Office;
use App\Models\Administration\Site;
use App\Models\Administration\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class Position extends Model
{
    use HasFactory;

    protected $table = 'ct_positions';
    public $timestamps = false;

    protected $fillable = [
        'id',
        'fk_site',
        'fk_office',
        'positionname',
        'visible',
        'available',
        'fk_usercreator',
        'created_at',
        'fk_userupdater',
        'updated_at',
        'is_active',
    ];

    protected $casts = [
        'id' => 'integer',
        'fk_site' => 'integer',
        'fk_office' => 'integer',
        'visible' => 'boolean',
        'available' => 'boolean',
        'fk_usercreator' => 'integer',
        'created_at' => 'timestamp',
        'fk_userupdater' => 'integer',
        'updated_at' => 'timestamp',
        'is_active' => 'boolean',
    ];

    protected $hidden = [
        'fk_site',
        'fk_office',
        'fk_usercreator',
        'fk_userupdater',
        'is_active',
    ];

    protected static function booted()
    {
        static::updated(function ($position) {
            Log::channel('position')->info('Position Updated', [
                'id' => $position->id,
                'fk_userupdater' => $position->fk_userupdater,
                'updated_at' => Carbon::now(),
                'changes' => $position->getChanges()
            ]);
        });
    }

    public function site()
    {
        return $this->belongsTo(Site::class, 'fk_site', 'id')->select('id', 'sitename');
    }

    public function office()
    {
        return $this->belongsTo(Office::class, 'fk_office', 'id')->select('id', 'officename');
    }

    public function collaborators()
    {
        return $this->hasMany(Collaborator::class, 'fk_position', 'id')->select('id', 'firstname', 'lastname', 'secondlastname', 'fk_position')->where('is_active', true);
    }

    public function user_creator()
    {
        return $this->hasOne(User::class, 'id', 'fk_usercreator')->select('id', 'username');
    }

    public function user_updater()
    {
        return $this->hasOne(User::class, 'id', 'fk_userupdater')->select('id', 'username');
    }
}
