<?php

namespace App\Http\Traits;


use Illuminate\Support\Facades\Storage;

trait CrudTrait
{
    public $model_name;
    public $view;
    public $route;
    public $per_page = 15;

    public function index()
    {
        $name = $this->model_name;
        $items = $name::paginate($this->per_page);
        return view($this->view.'.index', compact('items'));
    }

    public function create()
    {
        return view($this->view.'.create');
    }

    public function store(Request $request)
    {
        $name = $this->model_name;
        $item = $name::create($request->input());

        return redirect()->route('admin.'.$this->route.'.show');
    }

    public function show($id)
    {
        $name = $this->model_name;
        $item = $name::findOrFail($id);
        return view($this->view.'.show', compact('item'));
    }

    public function edit($id)
    {
        $name = $this->model_name;
        $item = $name::findOrFail($id);
        return view($this->view.'.edit', compact('item'));
    }

    public function update(Request $request, $id)
    {
        $name = $this->model_name;
        $item = $name::findOrFail($id);

        $item->fill($request->input());
        $item->save();

        return redirect()->route('admin.'.$this->route.'.show');
    }

    public function delete($id)
    {
        $name = $this->model_name;
        $item = $name::findOrFail($id);
        $item->delete();

        return redirect()->route('admin.'.$this->route.'.index');
    }

    /**
     * @param $file
     * @param $directory
     * @return bool
     */
    public function uploadFile($file, $directory)
    {
        if(isset($file)){
            $path = $file->storeAs($directory, $file->getClientOriginalName());
            return $path;
        }
        return false;
    }

    /**
     * @param $file
     * @param $directory
     * @return mixed
     */
    public function deleteFile($file, $directory)
    {
        return Storage::delete($directory."/".$file);
    }
}