<?php
namespace App\Models;

use Eloquent as Model;
use Illuminate\Support\Facades\Auth;
/**
 * Class BinderComposition
 * @package App\Models
 * @version October 11, 2019, 9:25 pm UTC
 *
 */
class CRUDAwareModel extends Model
{
   
    

    
    public static function boot() {
        parent::boot();

        // create a event to happen on updating
        static::updating(function($table)  {
            $table->updated_by = Auth::user()->id;
        });

        // create a event to happen on deleting
        static::deleting(function($table)  {
            $table->deleted_by = Auth::user()->id;
        });

        // create a event to happen on saving
        static::creating(function($table)  {
            $table->created_by = Auth::user()->id;
        });
    }

    public static function generateString($length = 6) {
        $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        $recipe = BondMaterialRecipe::where('material_id','=', $randomString)->first();
        if(!empty($recipe)){
            return generateMaterialId($length);
        }else{
            return $randomString;
        }
    }

    public function createdBy()
    {
        return $this->belongsTo('App\Models\User','created_by');
    }

    public function updatedBy()
    {
        return $this->belongsTo('App\Models\User','updated_by');
    }

    public function deletedBy()
    {
        return $this->belongsTo('App\Models\User','deleted_by');
    }
    
}