<?php
namespace App\Models;

use Eloquent as Model;
use Illuminate\Support\Facades\Auth;
use LangleyFoxall\RedactedModel\RedactedModel;
use Log;
/**
 * Class BinderComposition
 * @package App\Models
 * @version October 11, 2019, 9:25 pm UTC
 *
 */
class SensitiveCRUDAwareModel extends RedactedModel
{
   
    
    protected $redactedString = '0';
    
    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::saving(function($table)  {
            $table->created_by = Auth::user()->id;
        });
    }

    public static function generateMaterialId($length = 5) {
        // $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        // $charactersLength = strlen($characters);
        // $randomString = '';
        // for ($i = 0; $i < $length; $i++) {
        //     $randomString .= $characters[rand(0, $charactersLength - 1)];
        // }
        $number = 99999;
        $number1 = 10000;
        if($length == 5){
            $number = 99999;
            $number1 = 10000;
        }else if($length == 6){
            $number = 999999;
            $number1 = 100000;
        }
        $randomString = rand($number1,$number);
        $recipe = BondMaterialRecipe::where('material_id','=', $randomString)->first();
        if(!empty($recipe)){
            return self::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');
    }
    
    public function shouldRedactField($key)
	{
        $user = \Auth::user();
        Log::info('shouldRedactField '.$user->hasPermission('view.sensitive'));
        if ($user->hasPermission('view.sensitive')) { // you can pass an id or slug
            return false;
        }
		return true;
    }
    
}