<?php

namespace App\Models\HRM;

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

class Cnssdeclaration extends Model implements Auditable
{
    use HasFactory, SoftDeletes, \OwenIt\Auditing\Auditable;
    protected $fillable = [
        'uid',
        'name',
        'status',
        'employee',
        'employee_id',
        'employee_pid',
        'month',
        'amount',
        'days',
        'hours',
        'salary ',
        'observation '
    ];



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


    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            if (empty($model->uid)) {
                $model->uid = (string) Str::ulid();
            }

            if (!empty($model->employee)) {
                $model->name = $model->employee['name'];
                $model->employee_id = $model->employee['id'];
                $model->employee_pid = $model->employee['pid'];
            }
        });

        static::updating(function ($model) {
            if ($model->isDirty('employee')) {
                $model->name = $model->employee['name'];
                $model->employee_id = $model->employee['id'];
                $model->employee_pid = $model->employee['pid'];
            }
        });
    }
}
