<?php

/**
 * Created by Reliese Model.
 */

namespace App\Models;

use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

/**
 * Class File
 *
 * @property int $id
 * @property int $user_id
 * @property string $filename
 * @property string $dir
 * @property string $original_name
 * @property string $ext
 * @property string $mine
 * @property int $size
 * @property Carbon $created_at
 * @property Carbon $updated_at
 * @property User $user
 * @package App\Models
 * @property string $identifier
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereDir($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereExt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereFilename($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereIdentifier($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereMine($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereOriginalName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereSize($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\File whereUserId($value)
 * @mixin \Eloquent
 */
class File extends Model
{
	protected $table = 'files';

	protected $casts = [
		'user_id' => 'int',
		'size' => 'int'
	];

	protected $fillable = [
		'user_id',
        'identifier',
		'filename',
		'dir',
		'original_name',
		'ext',
		'mine',
		'size'
	];

	public function user()
	{
		return $this->belongsTo(User::class);
	}

    public function formatBytes($precision = 2)
    {
        $size = $this->size;

        if ($size > 0) {
            $size = (int) $size;
            $base = log($size) / log(1024);
            $suffixes = array(' bytes', ' KB', ' MB', ' GB', ' TB');

            return round(pow(1024, $base - floor($base)), $precision) . $suffixes[floor($base)];
        } else {
            return $size;
        }
    }
}
