<?php
/**
 * Created by PhpStorm.
 * User: mruongyutthy
 * Date: 1/4/20
 * Time: 21:20
 */
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

class BaseModel extends Model
{
    use HasFactory;

    const RECORD_STATUS_FIELD   = 'record_status_id';
    const RECORD_STATUS_ACTIVE  = 1;
    const RECORD_STATUS_DELETE  = 0;

    const CREATED_AT_FIELD      = 'created_at';
    const CREATED_BY_FIELD      = 'created_by';
    const UPDATED_AT_FIELD      = 'updated_at';
    const UPDATED_BY_FIELD      = 'updated_by';

    protected static function boot(){
        parent::boot();
        static::creating(function ($model){
            $model->created_at = date('Y-m-d H:i:s');
            $model->created_by = Auth::id() ?? 1;
        });

        static::updating(function ($model){
            $model->updated_at = date('Y-m-d H:i:s');
            $model->updated_by = Auth::id() ?? 1;
        });
    }

    public static function getTableNameByScheme()
    {
        $__table = (new static())->table;
        $__database = (new static())->getConnection()->getDatabaseName();
        return $__database.'.'.$__table;

    }

    public static function getTableNameByConnection()
    {
        $__table = (new static())->table;
        $__database = (new static())->getConnection()->getName();
        return $__database.'.'.$__table;
    }

    public function createdByUser()
    {
        return $this->belongsTo(User::class, self::CREATED_BY_FIELD, 'id')->withDefault(function(){
            return new User();
        });
    }

    public function updatedByUser()
    {
        return $this->belongsTo(User::class, self::UPDATED_BY_FIELD, 'id')->withDefault(function(){
            return new User();
        });;
    }

}
