<?php

namespace App\Models\Application;

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

class Group extends Model
{
    use HasFactory;

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

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

    protected $casts = [
        'id' => 'integer',
        'fk_site' => 'integer',
        'fk_office' => 'integer',
        'fk_zone' => 'integer',
        'fk_promoter' => '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_zone',
        'fk_promoter',
        'fk_usercreator',
        'fk_userupdater',
        'is_active',
    ];

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

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

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

    public function zone()
    {
        return $this->belongsTo(Zone::class, 'fk_zone', 'id')->select('id', 'fk_city', 'zonename', 'fk_executive');
    }

    public function promoter()
    {
        return $this->belongsTo(Collaborator::class, 'fk_promoter', 'id')->select(
            'id',
            'fk_position',
            DB::raw("CONCAT(firstname, ' ', lastname, ' ', secondlastname) as fullname"),
            'commissionpercent'
        );
    }

    public function loans()
    {
        return $this->hasMany(Loan::class, 'fk_group', 'id');
    }

    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');
    }
}
