<?php
declare(strict_types=1);

/**
 * Record the change history of the Users table.
 *
 */
namespace App\Model\Behavior;

use Cake\ORM\Behavior;
use Cake\ORM\Table;
use Cake\ORM\TableRegistry;
use Cake\Routing\Router;
use Cake\Http\Session;

class RegisterBehavior extends Behavior {


    private $fields = [
        'created_id',
        'created_date',
        'created_ip',
        'modified_id',
        'modified_date',
        'modified_ip'
    ];

    /**
     * afterSave
     * for INSERT,UPDATE
     *
     * @return bool
     */
    public function beforeSave(\Cake\Event\Event $event, $entity, $options): bool {
        $user = null;
        $auth = (new Session)->read('Auth');
        if(!empty($auth))
        {
            $user['User']['id'] = $auth->id;
        }
        $ip = Router::getRequest()->clientIp();
        $dateTimeObject = new  \DateTime('NOW');
        if(empty($user))
        {
            $user['User']['id'] = 0;
        }
        if ($entity->isNew())
        {
            $entity->set('created_id',  $user['User']['id']);
            $entity->set('modified_id', $user['User']['id']);
            $entity->set('created_date', $dateTimeObject->format("Y-m-d H:i:s"));
            $entity->set('modified_date', $dateTimeObject->format("Y-m-d H:i:s"));
            $entity->set('created_ip', $ip);
            $entity->set('modified_ip', $ip);
        } else
        {
            $entity->set('modified_id', $user['User']['id']);
            $entity->set('modified_date', $dateTimeObject->format("Y-m-d H:i:s"));
            $entity->set('modified_ip', $ip);
        }
        return true;
    }
}
