<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class livechat_flow extends Model
{
    use HasFactory;

    protected $fillable = [
        'liveChatFlow',
        'active',
        'active_draft',
        'responseName'
    ];

    


    protected static function booted()
    {
        // Use retrieved event to automatically set the "image" attribute when loading an existing model

        static::updating(function ($model) {
            if ($model['timeBasedCreateAt']) {
                unset($model['timeBasedCreateAt']);
            }
            if ($model['timeBasedUpdatedAt']) {
                unset($model['timeBasedUpdatedAt']);
            }
            return;
        });
        static::retrieved(function ($model) {
            $model->setTimeValAttribute();
        });
    }

    // Define a method to set the "image" attribute
    protected function setTimeValAttribute()
    {
        if ($this->liveChatFlow) {
            $carbonDateTime = Carbon::parse($this->created_at);
            $convertedDateTime = $carbonDateTime->timezone(setting('default_timezone'));
            $dateFormat = 'd.m.y'; // Or use your setting function to check this
            $timeFormat = 'h:i A';
            $formattedDateTime = $convertedDateTime->format($dateFormat . ' ' . $timeFormat);
            $this['timeBasedCreateAt'] = $formattedDateTime;
        }
        if($this->active_draft){
            $carbonDateTime = Carbon::parse($this->updated_at);
            $convertedDateTime = $carbonDateTime->timezone(setting('default_timezone'));
            $formattedDateTime = $convertedDateTime->format(
                setting('date_format') . ' ' . setting('time_format'),
            );
            $this['timeBasedUpdatedAt'] = $formattedDateTime;
        }
    }
}
