<?php

namespace App\Models;

use App\Http\Traits\LogsActivityCustom;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Contracts\Activity;
use Spatie\Activitylog\LogOptions;
use App\Http\Traits\Timezone;

class DepositOption extends Model
{
    use HasFactory, LogsActivityCustom, Timezone;
    protected $casts = [
        'created_at' => 'datetime:d-m-Y H:i:s',
   ];
    const ENABLE = 1;
    const DISABLE = 0;

    protected $table = 'deposit_option';

    protected static $recordEvents = ['deleted', 'created'];
    public $pageName = "Deposit Option";
    public $colName = "name";
    protected $fillable = [
        'name',
        'titles',
        'entries',
        'deposit_currency',
        'description',
        'min_value',
        'max_value',
        'require_file_upload',
        'reference_with_username',
        'notes',
        'content',
        'status',
    ];

    public function currency()
    {
        return $this->belongsTo(Currency::class, 'deposit_currency');
    }

    public function titles(): Attribute
    {
        return Attribute::make(
            function ($value) {
                return array_filter(explode(',', $value));
            },function ($value){
                if (is_string($value) || empty($value)) {
                    return $value;
                } else {
                    return implode(',', $value);
                }
            }
        );
    }

    public function entries(): Attribute
    {
        return Attribute::make(
            function ($value) {
                return array_filter(explode(',', $value));
            },function ($value){
                if (is_string($value) || empty($value)) {
                    return $value;
                } else {
                    return implode(',', $value);
                }
            }
        );
    }

    public function tapActivity(Activity $activity, string $eventName)
    {
        $activity->log_name = $eventName;
        if ($eventName == 'created') {
            $activity->description = $this->pageName . ' ' . $this->attributes['name'] . ' ' . $eventName;
        } elseif ($eventName == 'deleted') {
            $activity->description = $this->pageName . ' ' . $this->attributes['name'] . ' has been ' . $eventName;
        }
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('system')
            ->submitEmptyLogs(false)
            ->logFillable()
            ->logExcept(['created_at', 'updated_at']);
    }

}
