<?php

namespace App\Models\HRM;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
use OwenIt\Auditing\Contracts\Auditable;
use Illuminate\Database\Eloquent\Casts\Attribute;

class Compensation extends Model implements Auditable
{
    use HasFactory, SoftDeletes, \OwenIt\Auditing\Auditable;
    protected $fillable = [
        'uid',
        'name',
        'status',
        'dueDate',
        'employee',
        'allowance',
        'approvedBy',
        'approvedAt',
    ];
    protected $casts = [
        'dueDate' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if (empty($model->uid)) {
                $model->uid = (string) Str::ulid();
            }
            if (!empty($model->employee) && !empty($model->allowance)) {
                $model->name = $model->employee['name'] .'-'.  $model->allowance['name'] .'-'. $model->allowance['amount'];
            }
        });
        static::updating(function ($model) {
            if ($model->isDirty('employee') || $model->isDirty('employee')) {
                $model->name = $model->employee['name'] . '-' .  $model->allowance['name'] . '-' . $model->allowance['amount'];
            }
        });
    }

    protected function employee(): Attribute
    {
        return Attribute::make(
            get: fn($value) => json_decode($value, true),
            set: fn($value) => json_encode($value),
        );
    }

    protected function allowance(): Attribute
    {
        return Attribute::make(
            get: fn($value) => json_decode($value, true),
            set: fn($value) => json_encode($value),
        );
    }
}
