<?php

namespace app\libraries;

use DateTime;

/**
 * Userstamp
 * 
 * SQL (DATETIME): 
 * ALTER TABLE `table_name` ADD `deleted_at` DATETIME NULL, ADD `updated_at` DATETIME NULL AFTER `deleted_at`, ADD `updated_by` INT NULL AFTER `updated_at`, ADD `created_at` DATETIME on update CURRENT_TIMESTAMP NULL AFTER `updated_by`, ADD `created_by` INT NULL AFTER `created_at`;
 * 
 * ALTER TABLE `table_name` ADD `delete_time` DATETIME NULL, ADD `update_time` DATETIME NULL AFTER `delete_time`, ADD `updated_by` INT NULL AFTER `update_time`, ADD `create_time` DATETIME on update CURRENT_TIMESTAMP NULL AFTER `update_time`, ADD `created_by` INT NULL AFTER `create_time`;
 */
class Userstamp
{
    public static $timestamp = false;

    private static function retrieveUserId()
    {
        return empty($_SESSION['userid']) ? 0 : $_SESSION['userid'];
    }

    public static function create($params = [], $by = 'created_by', $at = 'create_time')
    {
        $params[$by] = self::retrieveUserId();
        $params[$at] = !self::$timestamp ? date('Y-m-d H:i:s') : (new DateTime())->getTimestamp();

        self::$timestamp = false;
        return $params;
    }

    public static function update($params = [], $by = 'updated_by', $at = 'update_time')
    {
        $params[$by] = self::retrieveUserId();
        $params[$at] = !self::$timestamp ? date('Y-m-d H:i:s') : (new DateTime())->getTimestamp();

        self::$timestamp = false;
        return $params;
    }

    public static function delete($params = [], $by = 'updated_by', $at = 'deleted_at')
    {
        $params[$by] = self::retrieveUserId();
        $params[$at] = !self::$timestamp ? date('Y-m-d H:i:s') : (new DateTime())->getTimestamp();

        self::$timestamp = false;
        return $params;
    }
}
