<?php

namespace App\Observers;

use Illuminate\Support\Carbon;

class ModelTimezoneObserver
{
    /**
     * Handle the "creating" event.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function creating($model)
    {
        $this->setTimestamps($model);
    }

    /**
     * Handle the "updating" event.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function updating($model)
    {
        $this->setTimestamps($model);
    }

    /**
     * Set the local timezone for created_at and updated_at timestamps.
     *
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    protected function setTimestamps($model)
    {
        $timezone = config('app.timezone'); // Get the configured timezone
        $localTime = Carbon::now($timezone); // Get current time in local timezone

        if (in_array('created_at', $model->getFillable())) {
            $model->created_at = $localTime;
        }

        if (in_array('updated_at', $model->getFillable())) {
            $model->updated_at = $localTime;
        }
    }
}
